0

I tried setting iv or not setting iv, but encrypted messages were always different.

import CryptoJS from "crypto-js";
const iv = CryptoJS.lib.WordArray.create([0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f]);
const a = CryptoJS.AES.encrypt("my message", "my secret", {iv: iv}).toString();
console.log(a);

Some outputs were U2FsdGVkX1/7vfxMQ5nTdcBqjLjirF5LutKPUpPKkxI=, U2FsdGVkX18+075efZU5tMZyIziirm0e6O6u4ZPXVcA=

user2790103
  • 315
  • 3
  • 11
  • There might be some randomizer included (i.e. timestamp or similar) that accounts for your experiences. I am not familiar with `crypto-js`, however, are you able to decrypt both messages using "my secret"? – dmuensterer Jun 22 '20 at 07:33
  • check this: https://stackoverflow.com/questions/16600509/aes-encrypt-in-cryptojs-and-decrypt-in-coldfusion ? – Jing Jiang Jun 22 '20 at 08:34

2 Answers2

4

"my secret" is a password, not a key. CryptoJS.AES.encrypt is doing a key derivation function (internally) to derive a key from the password. One of the inputs to the key derivation function is a randomly generated salt. So, the derived key is different each time you run CryptoJS.AES.encrypt, even with the same inputs, and this is why you're getting a different result every time you run it.

See CryptoJS and key/IV length for an example of how to pass a key to CryptoJS.AES.encrypt instead of a password. This eliminates the need for the key derivation function, and you'll get the same result every time.

mti2935
  • 11,465
  • 3
  • 29
  • 33
-1
var algorithm = 'aes256';

 // Encrypt

function Encrypt(word, key) { 
var cipher = crypto.createCipher(algorithm, key);
var encrypted = cipher.update(word, 'utf8', 'hex') + cipher.final('hex');
return encrypted;
}

 //Decrypt

function Decrypt(word, key) {
var decipher = crypto.createDecipher(algorithm, key);
var decrypted = decipher.update(word, 'hex', 'utf8') + 
decipher.final('utf8');  
return decrypted;
}