HTML5 本身不支持 AES 加密,需用 Web Crypto API(推荐 AES-GCM 模式)或 CryptoJS 实现;Web Crypto 更安全但仅限 HTTPS,需派生密钥、随机 IV 并统一编解码。

HTML5 本身不内置 AES 加密能力,必须借助 JavaScript 加密库(如 CryptoJS 或原生 Web Crypto API)来实现字符串的 AES 加密。直接用纯 HTML5 标签或属性无法完成加密操作。
AES 加密推荐方案:使用 Web Crypto API(现代、安全、无需第三方库)
Web Crypto API 是浏览器原生支持的加密接口,支持 AES-GCM(推荐)、AES-CBC 等模式,无需引入外部脚本,且密钥管理更安全。
- 仅支持 HTTPS 环境(本地
file://或 HTTP 页面会报错) - 密钥需通过
crypto.subtle.generateKey()或importKey()创建/导入,不能明文传入字符串密钥 - 推荐使用 AES-GCM 模式:自动提供加密+认证,防止篡改
- 加密后输出为 ArrayBuffer,通常需转为 Base64 或 Hex 方便传输
简易 AES-GCM 加密/解密示例(可直接运行)
以下代码在 HTTPS 页面中可直接使用(例如部署在 localhost 或托管平台):
// 加密函数
async function encrypt(text, password) {
const enc = new TextEncoder();
const data = enc.encode(text);
const pwBytes = enc.encode(password);
const salt = crypto.getRandomValues(new Uint8Array(16));
// 从密码派生密钥(PBKDF2)
const keyMaterial = await crypto.subtle.importKey(
'raw', pwBytes, {name: 'PBKDF2'}, false, ['deriveKey']
);
const key = await crypto.subtle.deriveKey(
{name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256'},
keyMaterial, {name: 'AES-GCM', length: 256}, false, ['encrypt', 'decrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{name: 'AES-GCM', iv}, key, data
);
// 合并 salt + iv + ciphertext(Base64 输出)
const fullBuff = new Uint8Array(salt.length + iv.length + encrypted.byteLength);
fullBuff.set(salt, 0);
fullBuff.set(iv, salt.length);
fullBuff.set(new Uint8Array(encrypted), salt.length + iv.length);
return btoa(String.fromCharCode(...fullBuff));
}
// 解密函数(对应上面加密逻辑)
async function decrypt(b64Str, password) {
const enc = new TextEncoder();
const pwBytes = enc.encode(password);
const rawData = new Uint8Array(atob(b64Str).split('').map(c => c.charCodeAt(0)));
const salt = rawData.slice(0, 16);
const iv = rawData.slice(16, 28);
const ciphertext = rawData.slice(28);
const keyMaterial = await crypto.subtle.importKey(
'raw', pwBytes, {name: 'PBKDF2'}, false, ['deriveKey']
);
const key = await crypto.subtle.deriveKey(
{name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256'},
keyMaterial, {name: 'AES-GCM', length: 256}, false, ['encrypt', 'decrypt']
);
const decrypted = await crypto.subtle.decrypt(
{name: 'AES-GCM', iv}, key, ciphertext
);
return new TextDecoder().decode(decrypted);
}
若坚持用 CryptoJS(兼容旧环境,但注意安全风险)
CryptoJS 是纯 JS 库,支持浏览器直接引入,适合快速原型或兼容性要求高的场景,但存在以下限制:
立即学习“前端免费学习笔记(深入)”;
- 不支持真正的密钥派生(PBKDF2),
CryptoJS.enc.Utf8.parse("key")明文处理密钥,安全性弱 - 默认使用 ECDH 不安全的模式(如 ECB),务必手动指定 CBC/GCM 并配 IV
- 需自行处理 Base64 编解码与填充(如 Pkcs7)
- 建议仅用于非敏感数据或教学演示,生产环境优先选 Web Crypto
关键注意事项
AES 是对称加密,加解密必须使用完全相同的密钥、IV(初始向量)、算法参数和填充方式。常见错误包括:
- 加密用 AES-CBC,解密误用 AES-GCM
- IV 每次不随机或未随密文一起保存/传输
- 密钥长度不符(AES-128 需 16 字节,AES-256 需 32 字节)
- 字符串编码不一致(如加密用 UTF-8,解密误用 ASCII)
- Base64 解码前未处理 URL 安全字符(+ / =)
不复杂但容易忽略:加密不是“加个锁”,而是构建完整、可复现、可验证的数据转换流程。选对 API、管好密钥、统一编解码,才能真正落地。











