Cryptojs: How to Generate AES Passphrase

I want to create a 256-bit password for my AES encryption. When I verify the password after encryption, it is different from my initial password. What am I doing wrong? Or is there some kind of security mechanism that I don't know about?

My code is:

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; } 

The output is ie

0b05308c9a00f07044416bad7a51bacd282fc5c0c999551a4ff15c302b268b20 4df875993770411044fb35953166ee7833c32ca0741e9fec091dfa10138039e8

Is this normal, or am I doing something wrong here? Thanks for the help!

+6
source share
2 answers

I have found a solution. You can define your own key using var encrypted = CryptoJS.AES.encrypt ("Message", key, {iv: iv});

So my source code is:

 key=CryptoJS.enc.Hex.parse(Generate_key()); iv=CryptoJS.enc.Hex.parse(Generate_key()); var encrypted = CryptoJS.AES.encrypt("Message", key, { iv: iv }); 
+1
source

Encryption is performed using a key, which is a set of binary bits, not a password, which implies a human-readable string.

To switch from a password to a key, you can use a password-based key detection function such as PBKDF2. Crypto-JS already has a built-in PBKDF2 function, 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 the largest iteration counter possible since you can leave.

The salt should be a random variable, as in the example above; Of course, you will need to save this value along with the number of iterations in order to get the same key with the same passphrase.

+9
source

All Articles