Web Crypto API 提供浏览器原生加密功能,支持哈希、对称加密、非对称加密等;其核心模块包括 SHA-256 摘要、AES-GCM 加密解密、RSA 密钥生成与签名验证,且需在 HTTPS 环境下使用以确保安全。

Web Crypto API 是现代浏览器提供的一套强大的加密功能接口,允许开发者在客户端实现安全的加密操作。它支持多种常见的加密算法,包括哈希、对称加密、非对称加密、数字签名等,所有操作都在浏览器内部完成,无需依赖第三方库,提升了性能和安全性。
Web Crypto API 提供了以下几个核心功能模块:
以下是一些常见操作的代码示例,展示如何使用 Web Crypto API 实现基本加密功能。
1. 计算 SHA-256 哈希
立即学习“Java免费学习笔记(深入)”;
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); // 输出: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e
2. 使用 AES-GCM 进行对称加密与解密
async function encryptAES(key, plaintext) {
const encoder = new TextEncoder();
const data = encoder.encode(plaintext);
const iv = crypto.getRandomValues(new Uint8Array(12)); // GCM 推荐 IV 长度为 12 字节
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
data
);
return { encrypted, iv };
}
async function decryptAES(key, encryptedData, iv) {
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
key,
encryptedData
);
const decoder = new TextDecoder();
return decoder.decode(decrypted);
}
// 生成密钥并使用
crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
).then(async (key) => {
const { encrypted, iv } = await encryptAES(key, 'Secret message');
const decrypted = await decryptAES(key, encrypted, iv);
console.log(decrypted); // 输出: Secret message
});
3. 生成 RSA 密钥对并签名/验证
async function generateRSAKeyPair() {
return await crypto.subtle.generateKey(
{
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: 'SHA-256'
},
true,
['sign', 'verify']
);
}
async function signData(privateKey, data) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
return await crypto.subtle.sign('RSASSA-PKCS1-v1_5', privateKey, encodedData);
}
async function verifySignature(publicKey, signature, data) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
return await crypto.subtle.verify(
'RSASSA-PKCS1-v1_5',
publicKey,
signature,
encodedData
);
}
虽然 Web Crypto API 功能强大,但在实际使用中需要注意以下几点:
以上就是JavaScript加密算法_Web Crypto API的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号