Search code examples
javascriptnode.jsencryptionaescryptojs

NodeJS CryptoJS returns different AES-128-CBC encrypted value when using CryptoJS library in Javascript


I've been using this code in NodeJS to encrypt/decrypt using AES-128-CBC:

const CryptoJS = require('crypto-js');

var plaintext = 'TEST50';
var key = 'TXRZ3jThBP2dWnUN';
var iv = '2Mr9ca8KFEdAFGua';

key = CryptoJS.enc.Utf8.parse(key);
iv = CryptoJS.enc.Utf8.parse(iv);
var encrypted = CryptoJS.AES.encrypt(plaintext, key, { iv: iv, mode: CryptoJS.mode.CBC}).ciphertext.toString(
    CryptoJS.enc.Base64);
console.log(encrypted);


var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
    iv: iv,
}).toString(CryptoJS.enc.Utf8);
console.log(decrypted);

Encrypted: Je0mn7zUeYZ/4ZswNesNhQ==

Any tips or recommendations to solve this? Thanks!

I tried running the same code in Javascript and got a different encrypted value: G7Tvk9YMCUYRS7iRzE1U/g==

I'm expecting that the encrypted value should be the same in NodeJS since I can decrypt encrypted values from NodeJS in my Javascript code properly.


Solution

  • make sure you use the same version of crypto-js and use the same padding method in JavaScript and Node.js, padding: CryptoJS.pad.Pkcs7

    const CryptoJS = require('crypto-js'); //crypto-js": "4.0.0"
    
    var plaintext = 'TEST50';
    var key = 'TXRZ3jThBP2dWnUN';
    var iv = '2Mr9ca8KFEdAFGua';
    
    key = CryptoJS.enc.Utf8.parse(key);
    iv = CryptoJS.enc.Utf8.parse(iv);
    
    var encrypted = CryptoJS.AES.encrypt(plaintext, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    }).toString();
    
    console.log(encrypted); // Je0mn7zUeYZ/4ZswNesNhQ==
    
    
    var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    }).toString(CryptoJS.enc.Utf8);
    
    console.log(decrypted); // TEST50
    
    

    try in chrome

    <!DOCTYPE html>
    <html>
    <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
    <script>
      var plaintext = 'TEST50';
      var key = 'TXRZ3jThBP2dWnUN';
      var iv = '2Mr9ca8KFEdAFGua';
    
      key = CryptoJS.enc.Utf8.parse(key);
      iv = CryptoJS.enc.Utf8.parse(iv);
    
      var encrypted = CryptoJS.AES.encrypt(plaintext, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }).toString();
    
      console.log(encrypted);
    
      var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }).toString(CryptoJS.enc.Utf8);
    
      console.log(decrypted);
    </script>
    </body>
    </html>
    
    

    enter image description here