May*_*r S 8 javascript encryption aes
如何在 JavaScript 中使用 AES(高级加密标准)实现加密和解密。
为什么是 AES(高级加密标准)?
安全性:与其他提交的密码相比,竞争算法将根据它们抵抗攻击的能力来判断,尽管安全强度被认为是竞争中最重要的因素。
成本:打算在全球、非排他性和免版税的基础上发布,候选算法将在计算和内存效率方面进行评估。
小智 14
function encrypt(message = '', key = ''){
var message = CryptoJS.AES.encrypt(message, key);
return message.toString();
}
function decrypt(message = '', key = ''){
var code = CryptoJS.AES.decrypt(message, key);
var decryptedMessage = code.toString(CryptoJS.enc.Utf8);
return decryptedMessage;
}
console.log(encrypt('Hello World'));
console.log(decrypt('U2FsdGVkX1/0oPpnJ5S5XTELUonupdtYCdO91v+/SMs='))Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>Run Code Online (Sandbox Code Playgroud)
为什么要在 JavaScript 中实现 AES?与原生(或 wasm)实现相比,它会非常慢。幸运的是,您可以直接在浏览器中访问本机实现(如果您更改一些内容,甚至可以访问IE11)。它非常快(根据不久前发布在 Webkit 博客上的一些基准测试,速度快了数百倍)并且它不需要 50kb 的库。
在此示例中使用 GCM,但如果您不需要身份验证,则可以使用 CTR 模式:
const key = await crypto.subtle.generateKey({name: 'AES-GCM', length: 128}, true, ['encrypt', 'decrypt'])
const text = "confidential message"
// IV must be the same length (in bits) as the key
const iv = await crypto.getRandomValues(new Uint8Array(16))
const cyphertext = await crypto.subtle.encrypt({name: 'AES-GCM', tagLength: 32, iv}, key, new TextEncoder().encode(text))
Run Code Online (Sandbox Code Playgroud)
这将导致cyphertext包含带有加密字符串和 4 字节身份验证标签的 ArrayBuffer(特定于 GCM,其他 AES 模式将只生成加密数据)。只要您拥有用于加密的密钥和 IV,您就可以轻松地解密它。
const cleartext = await crypto.subtle.decrypt({name: 'AES-GCM', tagLength: 32, iv}, key, cyphertext)
console.log(new TextDecoder().decode(cleartext))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43268 次 |
| 最近记录: |