Web Crypto API 提供浏览器端安全加密功能,支持哈希、加密/解密、签名和密钥生成。1. 需在 HTTPS 或 localhost 环境使用,通过 crypto.subtle 调用异步方法。2. 支持 SHA-256 哈希、AES-GCM 对称加密(含 IV)、RSA-OAEP 非对称加密等操作。3. 推荐使用 PBKDF2 派生密钥,避免明文密码直接作密钥,确保安全性。所有操作不暴露密钥,禁用弱算法,保障数据安全。

Web Crypto API 提供了一套强大的加密功能,可以在浏览器端安全地执行常见的加密操作,比如哈希、加密/解密、签名和密钥生成。它支持现代加密算法,且所有操作都在安全上下文中进行(需要 HTTPS 或本地开发环境),防止敏感数据暴露给 JavaScript 层。
使用 Web Crypto API 需要注意以下几点:
2.1 SHA-256 哈希计算
将字符串转换为 ArrayBuffer 后进行哈希处理:
立即学习“Java免费学习笔记(深入)”;
async function hashString(str) {
const encoder = new TextEncoder();
const data = encoder.encode(str);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
// 使用示例
hashString('hello world').then(console.log); // 输出: "b94d..."
2.2 AES-GCM 加密与解密
AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。它不是新的编程语言,而是一种使用现有标准的新方法,最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容,不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。《php中级教程之ajax技术》带你快速
2114
AES-GCM 是推荐的对称加密方式,提供认证加密(防篡改):
async function encryptAES(keyStr, plaintext) {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(keyStr),
{ name: 'AES-GCM' },
false,
['encrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12)); // 初始化向量
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
encoder.encode(plaintext)
);
return { ciphertext, iv };
}
async function decryptAES(keyStr, { ciphertext, iv }) {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(keyStr),
{ name: 'AES-GCM' },
false,
['decrypt']
);
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
key,
ciphertext
);
return new TextDecoder().decode(decrypted);
}
2.3 RSA-OAEP 非对称加密
适用于加密小数据或传输对称密钥:
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(publicKey, data) {
const encoder = new TextEncoder();
const encrypted = await crypto.subtle.encrypt(
{ name: 'RSA-OAEP' },
publicKey,
encoder.encode(data)
);
return encrypted;
}
避免直接使用密码作为密钥。应通过 PBKDF2 派生密钥:
async function deriveKey(password, salt) {
const encoder = new TextEncoder();
const baseKey = await crypto.subtle.importKey(
'raw',
encoder.encode(password),
{ name: 'PBKDF2' },
false,
['deriveKey']
);
return await crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256'
},
baseKey,
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
}
Web Crypto API 的设计目标是安全性优先,因此不暴露原始密钥值,也不支持弱算法。合理使用可以实现安全的数据保护机制。
以上就是JavaScript加密算法_Web_Crypto_API使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号