Search code examples
encryptioncryptographyjavascriptaesnode.js

How to generate the same AES encrypted message in crypto-js?


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=


Solution

  • "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.