实现说明
异步流被 await 线性化,失败处理保持局部。
keyBytes、key、iv、plaintext 定义在模块顶层,中间不经过函数作用域。
使用要点
- 用到了
crypto,需要在浏览器环境运行,Node 里直接跑会缺 API。 - 直接运行文件,输出会带上标签,比如
ciphertext bytes:、round trip:、tampered rejected——输出的每一行都能指回产生它的那次调用。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件用顶层绑定保存自己的状态:keyBytes、key、iv。
核心语句
const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt', 'decrypt']);
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext);
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
代码示例
// AES-GCM: authenticated encryption through WebCrypto
const keyBytes = new Uint8Array(32).fill(9);
const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt', 'decrypt']);
const iv = crypto.getRandomValues(new Uint8Array(12));
const plaintext = new TextEncoder().encode('transfer 42 coins to alice');
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext);
console.log('ciphertext bytes:', ciphertext.byteLength); // includes the 16-byte auth tag
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
console.log('round trip:', new TextDecoder().decode(decrypted) === 'transfer 42 coins to alice');
// tampering with authenticated ciphertext fails instead of returning garbage
const tampered = new Uint8Array(ciphertext);
tampered[0] ^= 1;
try {
await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, tampered);
console.log('tampered accepted');
} catch {
console.log('tampered rejected');
}