crypto.subtle
接口crypto.subtle
提供了一组方法,用于执行低级别的加密操作。
async function hashData(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
hashData('Hello, World!').then(console.log); // 输出 SHA-256 哈希值
async function encryptData(key, data) {
const encoded = new TextEncoder().encode(data);
const iv = crypto.getRandomValues(new Uint8Array(12));
const cipherText = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv }, key, encoded);
return { iv: iv, cipherText: cipherText };
}
async function decryptData(key, iv, cipherText) {
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: iv }, key, cipherText);
return new TextDecoder().decode(decrypted);
}
// 密钥生成
async function generateKey() {
return crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
}
generateKey().then(key => {
encryptData(key, 'Hello, World!').then(({ iv, cipherText }) => {
decryptData(key, iv, cipherText).then(console.log); // 输出 "Hello, World!"
});
});
crypto.getRandomValues()
方法生成加密强度的随机数。
const array = new Uint8Array(16);
crypto.getRandomValues(array);
console.log(array); // 输出一个包含 16 个随机数的 Uint8Array
async function generateRSAKeyPair() {
return crypto.subtle.generateKey(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: 'SHA-256',
},
true,
['encrypt', 'decrypt']
);
}
async function encryptRSA(publicKey, data) {
const encoded = new TextEncoder().encode(data);
return crypto.subtle.encrypt({ name: 'RSA-OAEP' }, publicKey, encoded);
}
async function decryptRSA(privateKey, encryptedData) {
const decrypted = await crypto.subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, encryptedData);
return new TextDecoder().decode(decrypted);
}
generateRSAKeyPair().then(({ publicKey, privateKey }) => {
encryptRSA(publicKey, 'Hello, World!').then(encryptedData => {
decryptRSA(privateKey, encryptedData).then(console.log); // 输出 "Hello, World!"
});
});
这个示例展示了如何生成 RSA 密钥对,并使用公钥加密数据、私钥解密数据,适用于需要非对称加密的场景。