You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebCrypto调用unwrapKey时触发DataError的问题排查

问题分析与解决方案

你的代码触发DataError主要有三个核心问题:

  • 包装与解包的密钥格式不匹配:调用wrapKey时用'jwk'格式序列化公钥,但unwrapKey却指定'spki'格式解析,格式不一致直接导致解析失败。
  • wrapKey的算法参数错误:wrapKey的最后一个参数是**包装密钥(wrappingKey)**的算法配置,你错误传入了被包装密钥的512位模数参数,而wrappingKey是2000位的RSA-OAEP密钥,这里只需指定{name: 'RSA-OAEP', hash: 'SHA-256'}即可。
  • 被包装密钥的模数长度不安全:512位RSA属于已被破解的不安全长度,多数浏览器会限制这类密钥的操作,建议改用至少2048位的模数。

修正后的代码

// 生成包装用的RSA密钥对(改用符合安全标准的2048位模数)
const {privateKey: unwrappingKey, publicKey: wrappingKey} =
  await window.crypto.subtle.generateKey(
    {name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256'},
    true, ['decrypt', 'wrapKey', 'unwrapKey']);

// 生成被包装的RSA密钥对(同样使用2048位模数)
const {privateKey, publicKey} = await window.crypto.subtle.generateKey(
  {name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256'},
  true, ['encrypt', 'decrypt']);

// 用spki格式包装公钥,算法参数匹配wrappingKey的配置
const wrappedKey = await window.crypto.subtle.wrapKey(
  'spki', publicKey, wrappingKey,
  {name: 'RSA-OAEP', hash: 'SHA-256'});

// 解包时使用与包装一致的spki格式,参数正确匹配
const unwrappedKey = await window.crypto.subtle.unwrapKey(
  'spki', wrappedKey, unwrappingKey, 
  {name: 'RSA-OAEP', hash: 'SHA-256'}, // 解包密钥的算法配置
  {name: 'RSA-OAEP', hash: 'SHA-256'}, // 被解包密钥的算法配置
  true, ['encrypt']);
console.log(unwrappedKey);

关键修正说明

  1. 统一密钥格式:确保wrapKey和unwrapKey使用相同的密钥格式(这里用spki,也可以替换为jwk,但必须两边保持一致)。
  2. 修正算法参数:wrapKey的算法参数必须对应包装密钥的配置,不需要额外指定模数长度和公钥指数,因为这些信息已经包含在wrappingKey中。
  3. 升级密钥长度:将所有RSA密钥的模数长度改为2048位,避免浏览器因密钥不安全而拒绝操作,同时符合现代加密安全规范。

内容的提问来源于stack exchange,提问作者Jonah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:23:15