javascriptcryptographyaescryptojs

CryptoJs.AES encryption result is not as expected result


I use crypto-js to encrypt data in javascript. The code is:

const ps = CryptoJS.AES.encrypt('789', 'qwertyuiopasdfghjklzxcvbnmQWERTY', {
    iv: 'qwertyuiopasdfgh',
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
});
console.log(ps.toString());

That 789 is my string and qwertyuiopasdfghjklzxcvbnmQWERTY is secret key. Output is:

U2FsdGVkX1/7qI5ivsfqwo1/2ta6br74JjchhUxOL9Y=

But in online crypto websites, result is not the same as mine. for example https://anycript.com/crypto or https://www.javainuse.com/aesgenerator have same result with 256 bits for key size:

rTCEJwv7cF51UeuIVOqgxA==

That is different from mine. I examined different values for padding parameters but the result is not as expected result yet. What is wrong with crypto-js?


Solution

  • CryptoJS applies a key derivation function to derive the key and IV when the key material is passed as string, s. The Cipher Input. For the key material to be used directly as key, it must be passed as WordArray. In this case, the IV must also be passed as WordArray.
    CryptoJS provides encoders for conversion to a WordArray, e.g. the Utf8 encoder that you need: CryptoJS.enc.Utf8.

    const ps = CryptoJS.AES.encrypt(
      '789', 
      CryptoJS.enc.Utf8.parse('qwertyuiopasdfghjklzxcvbnmQWERTY'), // pass key as WordArray
      {
        iv: CryptoJS.enc.Utf8.parse('qwertyuiopasdfgh'), // pass IV as WordArray
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
    console.log(ps.toString()); // rTCEJwv7cF51UeuIVOqgxA==
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js"></script>