JavaScript密码学_WebCryptoAPI加密解密实战

WebCrypto API 提供加密、解密、签名等功能,支持 AES-GCM 对称加密和 RSA-OAEP 非对称加密,通过 generateKey 创建密钥,encrypt/decrypt 实现数据加解密,exportKey/importKey 管理密钥,需配合 HTTPS 与后端保障安全。

WebCrypto API 是现代浏览器提供的强大工具,用于执行常见的密码学操作,比如加密、解密、签名、哈希和密钥生成。它支持 AES、RSA、ECDSA 等多种算法,并且运行在安全的上下文中(如 HTTPS),能有效防止敏感数据暴露。下面通过实际示例展示如何使用 WebCrypto API 实现对称加密与非对称加密的基本流程。

使用 AES-GCM 进行对称加密与解密

对称加密适用于加密大量数据,加密和解密使用相同的密钥。AES-GCM 模式提供机密性和完整性验证,是推荐使用的模式之一。

生成 AES 密钥并加密字符串:

说明: 使用 crypto.subtle.generateKey() 生成一个 256 位的 AES-GCM 密钥。

代码示例:


async function encryptData(plainText) {
  // 生成密钥
  const key = await crypto.subtle.generateKey(
    { name: "AES-GCM", length: 256 },
    true,
    ["encrypt", "decrypt"]
  );

  // 编码文本为 ArrayBuffer
  const encoder = new TextEncoder();
  const data = encoder.encode(plainText);

  // 生成随机 IV(初始化向量)
  const iv = crypto.getRandomValues(new Uint8Array(12));

  // 执行加密
  const encrypted = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv: iv },
    key,
    data
  );

  // 返回密文、IV 和密钥(实际中密钥不应直接返回)
  return {
    encrypted: Array.from(new Uint8Array(encrypted)),
    iv: Array.from(iv),
    key: key // 注意:生产环境应妥善管理密钥
  };
}
解密数据:

说明: 使用之前保存的密钥、IV 和密文进行解密。


async function decryptData(encryptedData, iv, key) {
  const encryptedBuffer = new Uint8Array(encryptedData).buffer;
  const ivBuffer = new Uint8Array(iv).buffer;

  const decrypted = await crypto.subtle.decrypt(
    { name: "AES-GCM", iv: ivBuffer },
    key,
    encryptedBuffer
  );

  const decoder = new TextDecoder();
  return decoder.decode(decrypted);
}

使用 RSA-OAEP 实现非对称加密

非对称加密适合加密小量数据或传输对称密钥。公钥加密,私钥解密。

生成 RSA 密钥对:

说明: 创建一对公私钥,公钥可用于加密,私钥用于解密。


async function generateRSAKeyPair() {
  return await crypto.subtle.generateKey(
    {
      name: "RSA-OAEP",
      modulusLength: 2048,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256"
    },
    true,
    ["encrypt", "decrypt"]
  );
}
使用公钥加密,私钥解密:

async function rsaEncrypt(plainText, publicKey) {
  const encoder = new TextEncoder();
  const data = encoder.encode(plainText);

  const encrypted = await crypto.subtle.encrypt(
    { name: "RSA-OAEP" },
    publicKey,
    data
  );

  return Array.from(new Uint8Array(encrypted));
}

async function rsaDecrypt(encryptedData, privateKey) {
  const encryptedBuffer = new Uint8Array(encryptedData).buffer;

  const decrypted = await crypto.subtle.decrypt(
    { name: "RSA-OAEP" },
    privateKey,
    encryptedBuffer
  );

  const decoder = new TextDecoder();
  return decoder.decode(decrypted);
}

密钥导出与导入(可选)

有时需要将密钥保存或传输。WebCrypto 支持以 jwk 格式导出密钥。


async function exportKey(key) {
  const jwk = await crypto.subtle.exportKey("jwk", key);
  return jwk; // 可序列化为 JSON
}

async function importKey(jwk) {
  return await crypto.subtle.importKey(
    "jwk",
    jwk,
    { name: "AES-GCM", length: 256 },
    true,
    ["encrypt", "decrypt"]
  );
}

基本上就这些。WebCrypto API 提供了安全且标准化的方式处理前端加密任务。注意:不要在客户端依赖 JavaScript 加密来实现完整安全,它只是整体安全策略的一部分,比如防止明文传输。密钥管理、HTTPS 和后端验证同样重要。