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

调用Web Crypto API的deriveKey时抛出DOMException问题求助

问题原因及解决方案

问题出在PBKDF2参数中的salt类型:

  • 浏览器的Web Crypto API严格遵循规范,要求salt必须是二进制数据类型(比如Uint8Array),不能直接传入字符串。
  • Node.js的webcrypto实现做了隐式兼容,会自动把字符串转换为二进制,所以代码能正常运行,但浏览器不支持这种隐式处理,因此抛出DOMException。

修改后的代码

只需要把字符串类型的salt转换成Uint8Array即可:

const IV = new Uint8Array([
  181, 205, 79, 202, 71, 30,
  192, 175, 44,  93, 57, 15,
  106, 207, 83, 179
]);

// 将字符串salt转换为Uint8Array
const SALT = new TextEncoder().encode("I'm so salty!");

async function generateKey(password, crypto) {
  const enc = new TextEncoder();
  const keyMaterial = await crypto.subtle.importKey(
    "raw",
    enc.encode(password),
    "PBKDF2",
    false,
    ["deriveBits", "deriveKey"],
  );

  return await crypto.subtle.deriveKey(
    {
      name: "PBKDF2",
      salt: SALT,
      iterations: 100000,
      hash: "SHA-256",
    },
    keyMaterial,
    { "name": "AES-GCM", "length": 256},
    true,
    ["encrypt", "decrypt"],
  );
}

调用代码保持不变,现在在Firefox浏览器中就能正常执行了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:35:34