js实现加密
使用 Web Crypto API 进行加密
Web Crypto API 是现代浏览器提供的原生加密接口,支持 AES、RSA、SHA 等算法。以下示例展示如何使用 AES-GCM 加密数据:
async function encryptAES(text, password) {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const salt = crypto.getRandomValues(new Uint8Array(16));
const keyMaterial = await crypto.subtle.importKey(
'raw',
encoder.encode(password),
{ name: 'PBKDF2' },
false,
['deriveKey']
);
const key = await crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256'
},
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: iv },
key,
data
);
return {
ciphertext: Array.from(new Uint8Array(encrypted)),
iv: Array.from(iv),
salt: Array.from(salt)
};
}
使用 SJCL 库加密
Stanford JavaScript Crypto Library (SJCL) 是轻量级加密库,适合需要兼容旧浏览器的场景:

// 引入 SJCL 库后
function encryptWithSJCL(plaintext, password) {
const ciphertext = sjcl.encrypt(password, plaintext, {
iter: 10000,
ks: 256,
ts: 128,
mode: 'gcm'
});
return ciphertext;
}
RSA 非对称加密实现
使用 Web Crypto API 生成密钥对并加密:

async function generateRSAKeys() {
const keyPair = await crypto.subtle.generateKey(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: 'SHA-256'
},
true,
['encrypt', 'decrypt']
);
return {
publicKey: await crypto.subtle.exportKey('jwk', keyPair.publicKey),
privateKey: await crypto.subtle.exportKey('jwk', keyPair.privateKey)
};
}
async function rsaEncrypt(publicKey, data) {
const key = await crypto.subtle.importKey(
'jwk',
publicKey,
{ name: 'RSA-OAEP', hash: 'SHA-256' },
false,
['encrypt']
);
const encrypted = await crypto.subtle.encrypt(
{ name: 'RSA-OAEP' },
key,
new TextEncoder().encode(data)
);
return Array.from(new Uint8Array(encrypted));
}
哈希函数示例
使用 SHA-256 生成消息摘要:
async function hashSHA256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
注意事项
所有加密操作应在 HTTPS 环境下进行,确保传输安全。敏感密钥应妥善存储,避免硬编码在客户端代码中。Web Crypto API 仅在安全上下文(Secure Context)中可用。
对于生产环境,建议结合后端服务进行密钥管理和更复杂的加密流程。浏览器端加密应作为安全链中的一环,而非唯一保障。






