WebCrypto API:DOMException:提供的数据太小

2023-12-15

我想在客户端解密消息(react.js) using Web Crypto API这是在后端加密的(node.js),但是我遇到了一个奇怪的问题,并且不知道出了什么问题(我也检查了this)

node.js

function encrypt(message){
    const KEY = crypto.randomBytes(32)
    const IV = crypto.randomBytes(16)
    const ALGORITHM = 'aes-256-gcm';
    const cipher = crypto.createCipheriv(ALGORITHM, KEY, IV);
    let encrypted = cipher.update(message, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    const tag = cipher.getAuthTag()
    let output = {
        encrypted,
        KEY: KEY.toString('hex'),
        IV: KEY.toString('hex'),
        TAG: tag.toString('hex'),
     }
    return output;
}

react.js

function decrypt() {
let KEY = hexStringToArrayBuffer(data.KEY);
let IV = hexStringToArrayBuffer(data.IV);
let encrypted = hexStringToArrayBuffer(data.encrypted);
let TAG = hexStringToArrayBuffer(data.TAG);

window.crypto.subtle.importKey('raw', KEY, 'AES-GCM', true, ['decrypt']).then((importedKey)=>{
  window.crypto.subtle.decrypt(
    {
      name: "AES-GCM",
      iv: IV,
    },
    importedKey,
    encrypted
  ).then((plaintext)=>{
    console.log('plainText: ', plaintext);
  })
})

function hexStringToArrayBuffer(hexString) {
  hexString = hexString.replace(/^0x/, '');
  if (hexString.length % 2 != 0) {
    console.log('WARNING: expecting an even number of characters in the hexString');
  }
  var bad = hexString.match(/[G-Z\s]/i);
  if (bad) {
    console.log('WARNING: found non-hex characters', bad);    
  }
  var pairs = hexString.match(/[\dA-F]{2}/gi);
  var integers = pairs.map(function(s) {
    return parseInt(s, 16);
  });
  var array = new Uint8Array(integers);
  return array.buffer;
} 

后端的加密是没有任何错误的,但是当想要在客户端解密消息时,浏览器(chrome)给出了这个错误:DOMException: The provided data is too small当我运行程序时firefox浏览器给我这个错误:DOMException: The operation failed for an operation-specific reason。太不清楚了!!

顺便问一下有什么用athentication tag in AES-GCM需要在客户端解密吗?


GCM是经过验证的加密。解密需要身份验证标签。它用于检查密文的真实性,只有在确认后才执行解密。
由于该标签未应用在您的 WebCrypto 代码中,因此身份验证和解密会失败。

WebCrypto 期望将标签附加到密文中:密文|标签.

下面代码中的数据是使用 NodeJS 代码创建的(请注意,NodeJS 代码中存在一个错误:密钥不是存储在 IV 中,而是存储在output):

decrypt();
 
function decrypt() {

    let KEY = hexStringToArrayBuffer('684aa9b1bb4630f802c5c0dd1428403a2224c98126c1892bec0de00b65cc42ba');
    let IV = hexStringToArrayBuffer('775a446e052b185c05716dd1955343bb');
    let encryptedHex = 'a196a7426a9b1ee64c2258c1575702cf66999a9c42290a77ab2ff30037e5901243170fd19c0092eed4f1f8';
    let TAGHex = '14c03526e18502e4c963f6055ec1e9c0';
    let encrypted = hexStringToArrayBuffer(encryptedHex + TAGHex)

    window.crypto.subtle.importKey(
        'raw', 
        KEY,
        'AES-GCM', 
        true, 
        ['decrypt']
    ).then((importedKey)=> {
        window.crypto.subtle.decrypt(
            {
                name: "AES-GCM",
                iv: IV,
            },
            importedKey,
            encrypted
        ).then((plaintext)=>{
            console.log('plainText: ', ab2str(plaintext));
        });
    });
}

function hexStringToArrayBuffer(hexString) {
    hexString = hexString.replace(/^0x/, '');
    if (hexString.length % 2 != 0) {
        console.log('WARNING: expecting an even number of characters in the hexString');
    }
    var bad = hexString.match(/[G-Z\s]/i);
    if (bad) {
        console.log('WARNING: found non-hex characters', bad);    
    }
    var pairs = hexString.match(/[\dA-F]{2}/gi);
    var integers = pairs.map(function(s) {
        return parseInt(s, 16);
    });
    var array = new Uint8Array(integers);
    return array.buffer;
} 

function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WebCrypto API:DOMException:提供的数据太小 的相关文章

随机推荐

  • 如何使用tensorflow进行文本分类?

    我是张量流和机器学习的新手 我在编写张量流代码时遇到问题 该代码的文本分类类似于我尝试使用 sklearn 库进行的文本分类 我在对数据集进行矢量化并向张量流层提供输入方面面临着重大问题 我确实记得对标签进行了一次热编码 但前面的张量流层不
  • Twitter 模块 python 'module' 对象没有属性 Oauth

    我正在尝试遵循这个基本示例here Code import twitter XXX Go to http dev twitter com apps new to create an app and get values for these
  • 随机化神经网络输入顺序的影响

    在我的高级算法和数据结构课程中 我的教授要求我们选择任何我们感兴趣的主题 他还告诉我们要研究它并尝试实施解决方案 我选择神经网络是因为它是我长期以来想学习的东西 我已经能够使用神经网络实现 AND OR 和 XOR 该神经网络的神经元使用阶
  • 共享变量的过时值

    在阅读实践中的并发性时 我读到 NoVisibility展示了一种不充分的方法 同步程序可能会导致令人惊讶的结果 陈旧的数据 当 的时候 读者线程检查ready 它可能会看到一个过时的值 除非 每次访问变量时都会使用同步 这是 可能会看到该
  • 分离数据框列中的值并融化

    我有一个数据框 我想在其中分隔 Client ID 列中的值并融化 因此每一行都包含一个 Client ID 以及相应的 Account Name 和所有者 gt head df Account Owner Account Name Cli
  • C++ 将带有分隔符的文本文件读取到结构数组中

    我正在尝试从格式类似于此的文本文件中读取数据 knife object 0 bag object 15 kitchen room 400 放入由结构体组成的数组中 这是我到目前为止所拥有的 但它只读取第一个元素然后返回垃圾 include
  • 提供 SOAP/XML + REST/JSON 的最佳方式是什么?

    我正在创建一个通用 Web 服务 该服务可能有许多不同的客户端 其中一些我目前无法预料 我已经有了一个很好的 Java 服务 API 并且希望在此基础上提供一个 Web 服务外观 SOAP 与 REST 争论的双方都有很大的争论 这让我想知
  • 数组中的随机数而不连续两次重复相同的数字?

    我正在使用 Swift 和 SpriteKit 制作一个游戏 其中我根据数组将对象移动到随机位置 由 CGPoints 组成的数组 let easyArray CGPointMake 0 0 CGPointMake 126 6 0 CGPo
  • 如何从基于年份的大数据集中获取多个矩阵

    在我开始之前 这里是我正在处理的数据的一小部分 我提前为它太大而道歉 注意这只是一个非常大的数据集的前 30 行 mydata lt structure list ParkName c SEP CSSP SEP ONF SEP ONF SE
  • 为什么Object类的方法可以在接口中使用?

    以下接口和类已成功编译 下面的输出中提到了问题 interface MyInterface class MyClass implements MyInterface class InterDoubt static MyInterface m
  • 有条件导入《盖茨比》中的图书馆

    我正在尝试这样做 if typeof window undefined import Keyboard from react simple keyboard import react simple keyboard build css in
  • 如何生成静态链接的可执行文件?

    我正在尝试使用 Rust 创建一个静态可执行文件 我是not尝试静态链接特定库 我试图创建一个可执行文件根本不使用动态链接 我有以下 否则有效 测试 cat hello rs fn main print Hello world n rust
  • mysql_num_rows():提供的参数不是有效的 MySQL 结果资源[重复]

    这个问题在这里已经有答案了 if mysql num rows result echo no match found 它抛出一个错误 Warning mysql num rows supplied argument is not a val
  • {|_,e| e.length>1} Ruby 中下划线 (_) 有什么用?

    country UK US RS EU UK US group by e e keep if e e length gt 1 UK gt UK UK US gt US US 有什么用 下划线 在第二个块中 有人可以详细解释一下吗 这个问题在
  • ASP.NET 4.0中涉及参数时如何指定url映射?

    问题 我有一个网站 里面有一些文章 使用数据库在单个页面上写入结果来访问文章 当要访问某一篇文章时 我需要文章编号我只需要访问该页面 http www mysite Articles aspx a article id 这很好 但不是很友好
  • Angular.module 缩小错误

    花费了最长时间试图弄清楚为什么缩小不起作用 我已经根据网络上的众多建议通过数组对象注入了我的提供者之前的功能 但仍然是 未知提供者 aProvider Regular var app angular module bpwApp ui boo
  • C# Linq Where 两个日期之间的日期

    我正在尝试让 linq 语句获取两个日期之间的所有记录 但我不太确定需要更改什么才能使其正常工作 a Start gt startDate endDate var appointmentNoShow from a in appointmen
  • Oracle Select * 返回行,但 Select count(1) 返回 0

    所以 这很奇怪 是我以前从未见过的 我希望有人能给出神奇的答案来阐明这个问题 SELECT FROM TABLE returns rows a lot of rows however SELECT COUNT 1 FROM TABLE re
  • 使用 Apache HttpClient 定义源 IP 地址

    我正在开发一个具有以下需求的项目 使用源ip地址A访问远程服务器XX YY ZZ WW上的http服务S 使用源ip地址B访问远程服务器XX YY ZZ WW上的http服务T 同上 XX YY ZZ WW 是我无法控制的主机 我的服务器在
  • WebCrypto API:DOMException:提供的数据太小

    我想在客户端解密消息 react js using Web Crypto API这是在后端加密的 node js 但是我遇到了一个奇怪的问题 并且不知道出了什么问题 我也检查了this node js function encrypt me