概述混合加密将对称密钥用非对称算法包裹。本文演示 RSA-OAEP + AES-GCM 的端到端协作。生成与导入密钥async function genRSA() {
return crypto.subtle.generateKey({ name:'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1,0,1]), hash: 'SHA-256' }, true, ['encrypt','decrypt']);
}
async function genAES() { return crypto.subtle.generateKey({ name:'AES-GCM', length:256 }, true, ['encrypt','decrypt']); }
包裹与解包async function wrapAES(aesKey, rsaPublic) {
const raw = await crypto.subtle.exportKey('raw', aesKey);
return crypto.subtle.encrypt({ name:'RSA-OAEP' }, rsaPublic, raw);
}
async function unwrapAES(wrapped, rsaPrivate) {
const raw = await crypto.subtle.decrypt({ name:'RSA-OAEP' }, rsaPrivate, wrapped);
return crypto.subtle.importKey('raw', raw, { name:'AES-GCM' }, true, ['encrypt','decrypt']);
}
文件加解密async function encryptFile(aesKey, file) {
const iv = crypto.getRandomValues(new Uint8Array(12));
const ab = await file.arrayBuffer();
const buf = await crypto.subtle.encrypt({ name:'AES-GCM', iv }, aesKey, ab);
return { iv, bytes: new Uint8Array(buf) };
}
async function decryptBytes(aesKey, iv, bytes) {
const buf = await crypto.subtle.decrypt({ name:'AES-GCM', iv }, aesKey, bytes);
return new Uint8Array(buf);
}

发表评论 取消回复