Web Cryptography API 提供标准化加密功能,支持哈希、对称与非对称加密等操作,通过 crypto.subtle 实现密钥管理、数据加密解密及签名验证,需在 HTTPS 下运行且密钥安全受保护。
Web Cryptography API 是现代浏览器提供的一套底层加密功能,允许开发者在客户端安全地执行常见的加密操作,比如生成密钥、加密解密数据、签名与验证、哈希计算等。它不依赖第三方库,直接通过 JavaScript 调用系统级加密模块,提升了安全性与性能。
Web Cryptography API 提供了 crypto.subtle 接口(称为 SubtleCrypto),支持以下核心功能:
以下是几个常见场景的代码示例,展示如何使用 Web Cryptography API 实现加密功能。
将字符串转换为 ArrayBuffer,然后计算其哈希值:
async function hashData(data) {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
// 使用
hashData('hello world').then(console.log); // 输出: "2ef7bde608ce5404e97d5f042f95f89f1c232871..."
2. 使用 AES-GCM 加密与解密
对称加密适合加密大量数据,密钥需保密:
async function encryptAES(data, key) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
const iv = crypto.getRandomValues(new Uint8Array(12)); // 初始化向量
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
encodedData
);
return { encrypted, iv };
}
async function decryptAES(encryptedData, key, iv) {
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
key,
encryptedData
);
const decoder = new TextDecoder();
return decoder.decode(decrypted);
}
// 生成密钥
async function generateKey() {
return await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
}
3. 使用 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 encryptWithPublicKey(data, publicKey) {
const encoder = new TextEncoder();
const encoded = encoder.encode(data);
return await crypto.subtle.encrypt(
{ name: 'RSA-OAEP' },
publicKey,
encoded
);
}
虽然 Web Cryptography API 功能强大,但使用时需注意以下几点:
基本上就这些。Web Cryptography API 提供了一种标准化、安全的方式来处理加密任务,减少对第三方库的依赖,是现代 Web 安全的重要组成部分。