17370845950

JavaScript加密算法_Web_Crypto_API使用
Web Crypto API 提供浏览器端安全加密功能,支持哈希、加密/解密、签名和密钥生成。1. 需在 HTTPS 或 localhost 环境使用,通过 crypto.subtle 调用异步方法。2. 支持 SHA-256 哈希、AES-GCM 对称加密(含 IV)、RSA-OAEP 非对称加密等操作。3. 推荐使用 PBKDF2 派生密钥,避免明文密码直接作密钥,确保安全性。所有操作不暴露密钥,禁用弱算法,保障数据安全。

Web Crypto API 提供了一套强大的加密功能,可以在浏览器端安全地执行常见的加密操作,比如哈希、加密/解密、签名和密钥生成。它支持现代加密算法,且所有操作都在安全上下文中进行(需要 HTTPS 或本地开发环境),防止敏感数据暴露给 JavaScript 层。

1. 基本使用条件

使用 Web Crypto API 需要注意以下几点:

  • 必须在安全上下文中运行(HTTPSlocalhost
  • 通过全局对象 crypto.subtle 访问核心加密方法
  • 所有方法返回 Promise,需用 async/await 或 .then() 处理异步结果

2. 常见加密操作示例

2.1 SHA-256 哈希计算

将字符串转换为 ArrayBuffer 后进行哈希处理:

async function hashString(str) {
  const encoder = new TextEncoder();
  const data = encoder.encode(str);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  return Array.from(new Uint8Array(hashBuffer))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}
// 使用示例
hashString('hello world').then(console.log); // 输出: "b94d..."

2.2 AES-GCM 加密与解密

AES-GCM 是推荐的对称加密方式,提供认证加密(防篡改):

async function encryptAES(keyStr, plaintext) {
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(keyStr),
    { name: 'AES-GCM' },
    false,
    ['encrypt']
  );
  const iv = crypto.getRandomValues(new Uint8Array(12)); // 初始化向量
  const ciphertext = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv },
    key,
    encoder.encode(plaintext)
  );
  return { ciphertext, iv };
}

async function decryptAES(keyStr, { ciphertext, iv }) {
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(keyStr),
    { name: 'AES-GCM' },
    false,
    ['decrypt']
  );
  const decrypted = await crypto.subtle.decrypt(
    { name: 'AES-GCM', iv },
    key,
    ciphertext
  );
  return new TextDecoder().decode(decrypted);
}

2.3 RSA-OAEP 非对称加密

适用于加密小数据或传输对称密钥:

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 encryptWithPublicKey(publicKey, data) {
  const encoder = new TextEncoder();
  const encrypted = await crypto.subtle.encrypt(
    { name: 'RSA-OAEP' },
    publicKey,
    encoder.encode(data)
  );
  return encrypted;
}

3. 密钥管理建议

避免直接使用密码作为密钥。应通过 PBKDF2 派生密钥:

async function deriveKey(password, salt) {
  const encoder = new TextEncoder();
  const baseKey = await crypto.subtle.importKey(
    'raw',
    encoder.encode(password),
    { name: 'PBKDF2' },
    false,
    ['deriveKey']
  );
  return await crypto.subtle.deriveKey(
    {
      name: 'PBKDF2',
      salt: salt,
      iterations: 100000,
      hash: 'SHA-256'
    },
    baseKey,
    { name: 'AES-GCM', length: 256 },
    true,
    ['encrypt', 'decrypt']
  );
}

Web Crypto API 的设计目标是安全性优先,因此不暴露原始密钥值,也不支持弱算法。合理使用可以实现安全的数据保护机制。