1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| // AES-GCM加密
async function encryptAESGCM(plaintext, key) {
// 生成随机IV(12字节推荐)
const iv = crypto.getRandomValues(new Uint8Array(12));
// 导入密钥
const cryptoKey = await crypto.subtle.importKey(
'raw',
key,
{ name: 'AES-GCM' },
false,
['encrypt']
);
// 加密
const encrypted = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv
},
cryptoKey,
new TextEncoder().encode(plaintext)
);
return {
ciphertext: new Uint8Array(encrypted),
iv: iv
};
}
// AES-GCM解密
async function decryptAESGCM(ciphertext, iv, key) {
// 导入密钥
const cryptoKey = await crypto.subtle.importKey(
'raw',
key,
{ name: 'AES-GCM' },
false,
['decrypt']
);
// 解密
const decrypted = await crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: iv
},
cryptoKey,
ciphertext
);
return new TextDecoder().decode(decrypted);
}
// 使用示例
async function example() {
// 生成256位密钥
const key = crypto.getRandomValues(new Uint8Array(32));
// 加密
const plaintext = 'Hello, AES Encryption!';
const { ciphertext, iv } = await encryptAESGCM(plaintext, key);
console.log('密文:', Array.from(ciphertext).map(b => b.toString(16).padStart(2, '0')).join(''));
console.log('IV:', Array.from(iv).map(b => b.toString(16).padStart(2, '0')).join(''));
// 解密
const decrypted = await decryptAESGCM(ciphertext, iv, key);
console.log('解密:', decrypted);
}
|