JavaScript AES 加解密(高级加密标准)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51531021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript AES encryption and decryption (Advanced Encryption Standard)
提问by Mayur S
How to implement encryption and decryption using AES (Advanced Encryption Standard) in JavaScript.
如何在 JavaScript 中使用 AES(高级加密标准)实现加密和解密。
Why AES (Advanced Encryption Standard) ?
为什么是 AES(高级加密标准)?
Security:Competing algorithms were to be judged on their ability to resist attack, as compared to other submitted ciphers, though security strength was to be considered the most important factor in the competition.
安全性:与其他提交的密码相比,竞争算法将根据它们抵抗攻击的能力来判断,尽管安全强度被认为是竞争中最重要的因素。
Cost:Intended to be released under a global, nonexclusive and royalty-free basis, the candidate algorithms were to be evaluated on computational and memory efficiency.
成本:打算在全球、非排他性和免版税的基础上发布,候选算法将在计算和内存效率方面进行评估。
采纳答案by Mayur S
AES is very Simple and powerful encryption and decryption method. Please see my below example that will very easy to use in your ready code.
AES 是一种非常简单而强大的加密和解密方法。请参阅我下面的示例,它很容易在您准备好的代码中使用。
Just need to call encryptMessageand decryptMessagefnuction. I already provided running example below.
只需要打电话encryptMessage和decryptMessage功能。我已经在下面提供了运行示例。
How to called these methods:
如何调用这些方法:
code.encryptMessage('Welcome to AES !','your_password');
code.decryptMessage('U2FsdGVkX1/S5oc9WgsNyZb8TJHsuL7+p4yArjEpOCYgDTUdkVxkmr+E+NdJmro9','your_password')
let code = (function(){
return{
encryptMessage: function(messageToencrypt = '', secretkey = ''){
var encryptedMessage = CryptoJS.AES.encrypt(messageToencrypt, secretkey);
return encryptedMessage.toString();
},
decryptMessage: function(encryptedMessage = '', secretkey = ''){
var decryptedBytes = CryptoJS.AES.decrypt(encryptedMessage, secretkey);
var decryptedMessage = decryptedBytes.toString(CryptoJS.enc.Utf8);
return decryptedMessage;
}
}
})();
console.log(code.encryptMessage('Welcome to AES !','your_password'));
console.log(code.decryptMessage('U2FsdGVkX1/S5oc9WgsNyZb8TJHsuL7+p4yArjEpOCYgDTUdkVxkmr+E+NdJmro9','your_password'))
<!DOCTYPE html>
<html>
<head>
<title>E2EE</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
</head>
<body>
</body>
</html>
You can also refer my githubcode repository for more references.
您还可以参考我的github代码库以获取更多参考。
https://github.com/shedagemayur/JavaScriptCode/tree/master/AES
https://github.com/shedagemayur/JavaScriptCode/tree/master/AES
回答by
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='))
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
回答by Touffy
Why would you want to implement AES in JavaScript? it would be extremely slow compared to a native (or wasm) implementation. Luckily, you have access to a native implementation right in the browser(even IE11 if you change a few things). It's very fast (hundreds of times faster according to some benchmarks posted a while ago on the Webkit blog) and it doesn't require 50kb libraries.
为什么要在 JavaScript 中实现 AES?与原生(或 wasm)实现相比,它会非常慢。幸运的是,您可以直接在浏览器中访问本机实现(如果您更改一些内容,甚至可以访问IE11)。它非常快(根据不久前发布在 Webkit 博客上的一些基准测试,速度快了数百倍)并且它不需要 50kb 的库。
Using GCM in this example but you can use CTR mode if you don't need the authentication:
在此示例中使用 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))
That will result in cyphertextcontaining an ArrayBuffer with the encrypted string and a 4-byte authentication tag (that's specific to GCM, other AES modes will just produce the encrypted data). You can decrypt it just as easily, as long as you have the key and IV used for encryption.
这将导致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))
回答by Touffy
below code was worked for me
下面的代码对我有用
encryptMessage: function(messageToencrypt = '', secretkey = ''){
var encryptedMessage = CryptoJS.AES.encrypt(messageToencrypt, secretkey);
return encryptedMessage.toString();
},
decryptMessage: function(encryptedMessage = '', secretkey = ''){
var decryptedBytes = CryptoJS.AES.decrypt(encryptedMessage, secretkey);
var decryptedMessage = decryptedBytes.toString(CryptoJS.enc.Utf8);
return decryptedMessage;
}
Thanks
谢谢
回答by ajimae
If you are building a react or nodejs app, you can simply use this library ncrypt-jsto encrypt and decrypt your data.
如果你正在构建一个 react 或 nodejs 应用程序,你可以简单地使用这个库ncrypt-js来加密和解密你的数据。
usage:
用法:
es5
es5
var ncrypt = require('ncrypt-js'); // or var { encrypt, decrypt } = require('ncrypt-js);
let encryptData = ncrypt.encrypt('super secret data', 'secret_key');
// or
// let encryptData = encrypt('super secret data', 'secret_key');
console.log(encryptData); // 11ab949601eb136f58ac3fe846e30d76.f9ce133b20adc35eef32af95957547abbb6fbfc5cb91cd14f5b0a088bd031883963cde1a56fd62fe2aeb75451a065d21
var decryptedData = ncrypt.decrypt(encryptData);
// or
// var decryptedData = decrypt(encryptData);
console.log(decryptedData); // super secret data
es6
es6
import ncrypt from 'ncrypt-js'; // or import { encrypt, decrypt } from 'ncrypt-js';
const encryptData = ncrypt.encrypt('super secret data', 'secret_key');
// or
// const encryptData = encrypt('super secret data', 'secret_key');
console.log(encryptData); // 11ab949601eb136f58ac3fe846e30d76.f9ce133b20adc35eef32af95957547abbb6fbfc5cb91cd14f5b0a088bd031883963cde1a56fd62fe2aeb75451a065d21
const decryptedData = ncrypt.decrypt(encryptData);
// or
// const decryptedData = decrypt(encryptData);
console.log(decryptedData); // super secret data

