Search code examples
javascriptencryptionaespbkdf2

Why is AES function returning different value?


Why is AES with same secret phrase and message returns different values each time? Let's say we have a same salt for each PBKDF2 functions( I know it's bad, it's just for an example). Let's say we are entering same passphrase each time.

var salt = "5J07c/a7+2bf=15$56aQc75Ub55=60&0";
console.log(req.body.password);
console.log(salt);
var PBKDF2hash = crypto.PBKDF2(req.body.password, salt, { keySize: 256/32 });
console.log(PBKDF2hash.toString());
var AEScipher = crypto.AES.encrypt(req.body.password, PBKDF2hash);
console.log(AEScipher.toString());

In this case we receive same PBKDF2hash (as expected), but any time AES provides different chipher.

zz
5J07c/a7+2bf=15$56aQc75Ub55=60&0
3949676666ed318087a52896be98dc80b0cad99f4b662d48565283f71a2ace80
U2FsdGVkX19O1pqgL+V6Chk8NdiJQhf15N1uEfYXgxw=
zz
5J07c/a7+2bf=15$56aQc75Ub55=60&0
3949676666ed318087a52896be98dc80b0cad99f4b662d48565283f71a2ace80
U2FsdGVkX1/C7GAmLJvfFAHyOYj7LKZI5278/ZoeA3M=

These answers says the thing is salt is differrent and cbc mode matters. In my case salt is constant and I've switched to other modes. Output is still different each time.


Solution

  • The initialization vector used in CBC mode is a random block, so each encryption will be different. An IV is sort of like a salt, except when encrypting a message there is no reason to ever specify any specific IV to use (a random IV should always be used). The IV is often put in front of the first block of the encrypted message.