浏览器端 Crypto 加密模块使用介绍

2024-06-26 11:29:40 243
`crypto` 是一个现代浏览器提供的原生模块,允许在客户端进行安全的加密、解密和哈希生成、随机数生成等操作。它是 Web Cryptography API 的一部分,设计用于增强 Web 应用程序的安全性。

特点

  • 原生支持:无需额外安装或引入第三方库。
  • 高性能:浏览器原生实现,性能优越。
  • 多种算法:支持 AES、RSA、SHA 等常用加密算法。
  • 安全性:遵循现代加密标准,保证数据安全。

使用场景

  • 数据加密:在浏览器端加密敏感数据,以便安全传输或存储。
  • 消息摘要:生成消息的哈希值,用于数据完整性校验。
  • 随机数生成:生成加密强度的随机数,用于密钥生成或其他安全用途。

常用API介绍

1. crypto.subtle 接口

crypto.subtle 提供了一组方法,用于执行低级别的加密操作。

示例:生成 SHA-256 哈希

async function hashData(message) {
  const msgBuffer = new TextEncoder().encode(message);
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  return hashHex;
}

hashData('Hello, World!').then(console.log); // 输出 SHA-256 哈希值

示例:AES-GCM 加密和解密

async function encryptData(key, data) {
  const encoded = new TextEncoder().encode(data);
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const cipherText = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv }, key, encoded);
  return { iv: iv, cipherText: cipherText };
}

async function decryptData(key, iv, cipherText) {
  const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: iv }, key, cipherText);
  return new TextDecoder().decode(decrypted);
}

// 密钥生成
async function generateKey() {
  return crypto.subtle.generateKey(
    { name: 'AES-GCM', length: 256 },
    true,
    ['encrypt', 'decrypt']
  );
}

generateKey().then(key => {
  encryptData(key, 'Hello, World!').then(({ iv, cipherText }) => {
    decryptData(key, iv, cipherText).then(console.log); // 输出 "Hello, World!"
  });
});

2. crypto.getRandomValues() 方法

生成加密强度的随机数。

const array = new Uint8Array(16);
crypto.getRandomValues(array);
console.log(array); // 输出一个包含 16 个随机数的 Uint8Array

高级用法

示例:生成 RSA 密钥对并加密解密数据

async function generateRSAKeyPair() {
  return crypto.subtle.generateKey(
    {
      name: 'RSA-OAEP',
      modulusLength: 2048,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: 'SHA-256',
    },
    true,
    ['encrypt', 'decrypt']
  );
}

async function encryptRSA(publicKey, data) {
  const encoded = new TextEncoder().encode(data);
  return crypto.subtle.encrypt({ name: 'RSA-OAEP' }, publicKey, encoded);
}

async function decryptRSA(privateKey, encryptedData) {
  const decrypted = await crypto.subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, encryptedData);
  return new TextDecoder().decode(decrypted);
}

generateRSAKeyPair().then(({ publicKey, privateKey }) => {
  encryptRSA(publicKey, 'Hello, World!').then(encryptedData => {
    decryptRSA(privateKey, encryptedData).then(console.log); // 输出 "Hello, World!"
  });
});

这个示例展示了如何生成 RSA 密钥对,并使用公钥加密数据、私钥解密数据,适用于需要非对称加密的场景。

官方资料