WebCrypto API 基本应用
WebCrypto API 是现代浏览器原生支持的加密接口,提供对称加密、哈希、密钥生成等功能。以下为常见操作示例:
生成密钥(AES-GCM)
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true, // 是否可导出
["encrypt", "decrypt"]
);
加密数据
const iv = crypto.getRandomValues(new Uint8Array(12)); // 初始化向量
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
key,
new TextEncoder().encode("敏感数据")
);
哈希计算(SHA-256)
const digest = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode("待哈希内容")
);
JWT 签名与验证
结构组成 JWT 由三部分组成:
- Header(算法与类型)
- Payload(实际数据)
- Signature(签名)
手动签名示例
const header = btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }));
const payload = btoa(JSON.stringify({ user: "admin" }));
const signature = await crypto.subtle.sign(
"HMAC",
secretKey,
new TextEncoder().encode(`${header}.${payload}`)
);
const jwt = `${header}.${payload}.${btoa(String.fromCharCode(...new Uint8Array(signature)))}`;
验证流程
- 拆分 JWT 三部分
- 重新计算签名并与原始签名比对
- 检查过期时间(exp)等声明
非对称加密实践
RSA 密钥对生成
const keyPair = await crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
);
公钥加密
const encrypted = await crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
publicKey,
new TextEncoder().encode("机密信息")
);
私钥解密
const decrypted = await crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
encryptedData
);
安全注意事项
- 初始化向量(IV)必须随机且不可重复使用
- 存储私钥需使用安全机制(如 HTTPS-only Cookie)
- 浏览器控制台可能暴露密钥,生产环境需配合后端完成敏感操作
- 定期轮换加密密钥
性能优化建议
- Web Worker 处理耗时加密操作
- IndexedDB 缓存常用密钥
- 对大型数据采用混合加密(非对称加密对称密钥)
以上方法均需在 HTTPS 环境下使用,明文传输敏感数据无法保证安全性。实际项目中建议结合具体框架(如 CryptoJS、node-forge 等)进行二次封装。
1035

被折叠的 条评论
为什么被折叠?



