cryptojs:如何生成AES密码 [英] cryptojs: How to generate AES passphrase
问题描述
我想为我的AES加密生成一个256位密码.当我在加密后检查密码时,它与我的初始密码不同.我究竟做错了什么?还是有一些我不知道的安全机制?
I want to generate a 256bit password for my AES encryption. When I check the password after the encryption it is different from my initial password. What am I doing wrong? Or is there some security mechanism I am not aware of?
我的代码:
password=Generate_key();
var encrypted = CryptoJS.AES.encrypt("Message", password);
//Those two should be the same
document.write(password+"<br>");
document.write(encrypted.key);
function Generate_key() {
var key = "";
var hex = "0123456789abcdef";
for (i = 0; i < 64; i++) {
key += hex.charAt(Math.floor(Math.random() * 16));
//Initially this was charAt(chance.integer({min: 0, max: 15}));
}
return key;
}
输出为
0b05308c9a00f07044416bad7a51bacd282fc5c0c999551a4ff15c302b268b204df875993770411044fb35953166ee7833c32ca0741e9fec091dfa10138039e8
0b05308c9a00f07044416bad7a51bacd282fc5c0c999551a4ff15c302b268b20 4df875993770411044fb35953166ee7833c32ca0741e9fec091dfa10138039e8
这是正常现象吗,还是我在这里做错了什么?感谢您的帮助!
Is this normal or am I doing something wrong here? Thanks for help!
推荐答案
加密是通过密钥完成的,密钥是一组二进制位,而不是密码,它表示人类可读的字符串.
Encryption is done with a key, which is a set of binary bits, not a password, which implies a human-readable string.
要从密码转到密钥,可以使用基于密码的密钥派生功能,例如PBKDF2.Crypto-JS已经具有内置PBKDF2函数,即
To go from a password to a key, one can use a Password Based Key Derivation Function, such as PBKDF2. Crypto-JS already has a PBKDF2 function built-in, i.e.
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/pbkdf2.js"></script>
<script>
var salt = CryptoJS.lib.WordArray.random(128/8);
var key128Bits = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 128/32 });
var key256Bits = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 256/32 });
var key512Bits = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 512/32 });
var key512Bits1000Iterations = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 512/32, iterations: 1000 });
</script>
通常,使用尽可能多的迭代次数.
In general, use as high an iteration count as you can get away with.
Salt应该是一个随机值,如上例所示;当然,您需要将该值与迭代计数一起存储,以便在给定相同密码的情况下获得相同的密钥.
Salt should be a random value, as in the example above; you'll need, of course, to store that value along with the iteration count in order to get the same key given the same passphrase.
这篇关于cryptojs:如何生成AES密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!