JavaScript Web加密API
外观
JavaScript Web加密API[编辑 | 编辑源代码]
JavaScript Web加密API(Web Cryptography API)是一组用于在Web应用中执行基本加密操作的JavaScript接口,由W3C标准化。它允许开发者在浏览器环境中安全地生成密钥、加密/解密数据、签名验证以及散列计算,而无需依赖第三方库或服务器端处理。
概述[编辑 | 编辑源代码]
Web加密API通过
crypto.subtle
对象提供底层加密功能,支持以下操作:
- 对称加密(如AES)
- 非对称加密(如RSA、ECDSA)
- 散列函数(如SHA-256)
- 密钥生成与管理
- 安全随机数生成
该API设计遵循以下原则:
- 仅在HTTPS或localhost环境下可用(安全上下文)
- 异步操作(返回Promise对象)
- 限制导出未加密的密钥
核心概念[编辑 | 编辑源代码]
密钥类型[编辑 | 编辑源代码]
支持的算法[编辑 | 编辑源代码]
类型 | 算法名称 | 典型用途 |
---|---|---|
对称加密 | AES-CBC, AES-GCM | 数据加密 |
非对称加密 | RSA-OAEP, ECDH | 密钥交换 |
签名算法 | RSASSA-PKCS1-v1_5, ECDSA | 数字签名 |
散列 | SHA-1, SHA-256, SHA-512 | 数据完整性验证 |
基本使用示例[编辑 | 编辑源代码]
生成AES密钥[编辑 | 编辑源代码]
window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256, // 密钥长度
},
true, // 是否可导出
["encrypt", "decrypt"] // 密钥用途
).then(key => {
console.log("生成的密钥:", key);
}).catch(err => {
console.error("密钥生成失败:", err);
});
加密数据[编辑 | 编辑源代码]
async function encryptData(plaintext, key) {
const iv = window.crypto.getRandomValues(new Uint8Array(12)); // 初始化向量
const ciphertext = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv
},
key,
new TextEncoder().encode(plaintext)
);
return { iv, ciphertext };
}
// 使用示例
const data = "机密消息123";
encryptData(data, aesKey).then(result => {
console.log("加密结果:", {
iv: Array.from(result.iv),
ciphertext: new Uint8Array(result.ciphertext)
});
});
实际应用场景[编辑 | 编辑源代码]
密码学安全随机数[编辑 | 编辑源代码]
生成用于CSRF令牌的随机值:
function generateSecureToken(length) {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}
// 输出示例: "4f7a1b9c3e..."
客户端密码哈希[编辑 | 编辑源代码]
在发送到服务器前处理用户密码:
async function hashPassword(password, salt) {
const encoder = new TextEncoder();
const material = encoder.encode(password + salt);
const hash = await window.crypto.subtle.digest('SHA-256', material);
return Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
数学基础[编辑 | 编辑源代码]
Web加密API实现的算法基于以下数学概念:
- RSA加密:基于大数分解难题
- 椭圆曲线加密:基于椭圆曲线离散对数问题
安全注意事项[编辑 | 编辑源代码]
1. IV管理:每次加密应使用唯一的初始化向量 2. 密钥存储:避免在客户端长期存储敏感密钥 3. 算法选择:
* 避免使用已破解算法(如RC4、MD5) * 推荐使用AES-GCM、SHA-256等现代算法
4. 错误处理:妥善捕获并处理加密操作中的异常
浏览器兼容性[编辑 | 编辑源代码]
大多数现代浏览器支持Web加密API:
- Chrome 37+
- Firefox 34+
- Edge 12+
- Safari 11+
可通过以下代码检测支持情况:
if (!window.crypto || !window.crypto.subtle) {
console.warn("Web Cryptography API not supported!");
}
进阶主题[编辑 | 编辑源代码]
- Web Workers中的加密:将计算密集型操作移出主线程
- 密钥导入/导出:使用JWK格式交换密钥
- 性能优化:批量处理加密操作
- 与WebAuthn集成:用于生物识别认证