js实现gcm加密
GCM加密简介
GCM(Galois/Counter Mode)是一种结合了计数器模式(CTR)和Galois消息认证码(GMAC)的加密模式,提供机密性和完整性保护。在JavaScript中,可以通过Web Crypto API实现GCM加密。
生成密钥
使用crypto.subtle.generateKey方法生成AES-GCM密钥。密钥长度可以是128、192或256位。

const generateKey = async () => {
return await window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"]
);
};
加密数据
使用crypto.subtle.encrypt方法进行加密。需要提供初始化向量(IV)和可选的附加认证数据(AAD)。

const encryptData = async (key, data, iv) => {
return await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv,
additionalData: new TextEncoder().encode("Optional AAD"),
tagLength: 128,
},
key,
new TextEncoder().encode(data)
);
};
解密数据
使用crypto.subtle.decrypt方法进行解密。需要提供相同的IV和AAD。
const decryptData = async (key, encryptedData, iv) => {
return await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv,
additionalData: new TextEncoder().encode("Optional AAD"),
tagLength: 128,
},
key,
encryptedData
);
};
完整示例
以下是一个完整的GCM加密解密示例。
(async () => {
const key = await generateKey();
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const data = "Secret message";
const encrypted = await encryptData(key, data, iv);
console.log("Encrypted:", new Uint8Array(encrypted));
const decrypted = await decryptData(key, encrypted, iv);
console.log("Decrypted:", new TextDecoder().decode(decrypted));
})();
注意事项
- IV必须是唯一的,每次加密都应使用不同的IV。IV不需要保密,但不应重复使用。
- AAD是可选的,用于提供额外的完整性保护,但不参与加密过程。
- GCM模式通常比CBC模式更高效且更安全,适合高性能要求的场景。
通过Web Crypto API实现的GCM加密在现代浏览器中广泛支持,适用于需要高安全性的Web应用。






