Search code examples
javascriptencryptioncryptojs

How to decrypt message with CryptoJS AES? I have a working node crypto example


I am able decrypt AES encrypted message using Node's crypto library as follow

const crypto = require('crypto');
const encryptedData = 'b6ab428efbcb93c2f483178114ac0608530e54428f1378c6d3be108531b730d1888e562044cd3acb8844a04d9d7602d83b96f0a758248ffd07cd9c530b76c91c';

const decryptResponse2 = (data) => {
  const key = 'F5:A4:F4:AB:BF:68:CF:86:51:B4:AA';
  const iv = Buffer.from(data.substring(0, 32), 'hex');
  const payload = data.substring(32);
  const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv).setAutoPadding(false);
  const decipherFinal = decipher.update(payload, 'hex', 'utf8') +   decipher.final('utf8');

  console.log(decipherFinal);
};

decryptResponse2(encryptedData);

I create a script using crypto-js library as that is available to be used in browser. The code I tried is as follow:

const crypto = require('crypto-js');
const encryptedData = 'b6ab428efbcb93c2f483178114ac0608530e54428f1378c6d3be108531b730d1888e562044cd3acb8844a04d9d7602d83b96f0a758248ffd07cd9c530b76c91c';

const decryptResponse = (data) => {
  const key = 'F5:A4:F4:AB:BF:68:CF:86:51:B4:AA';
  const iv = Buffer.from(data.substring(0, 32), 'hex');
  const payload = data.substring(32);
  let decryptedData = crypto.AES.decrypt(
    payload,
    key,
    {
      iv: iv,
      mode: crypto.mode.CBC,
      padding: crypto.pad.NoPadding
    });
  console.log(decryptedData.toString());
}

decryptResponse(encryptedData);

However, not only is it generating wrong decrypted data, the decrypted message is not even consistent. I don't know what I am doing wrong as I do not know much about encryption and decryption.

Any help will be apriciated.


Solution

  • Thanks to @GrafiCode pointing me to the right place, I was able to solve it using format property of config object.

    Following is the code:

    const crypto = require('crypto-js');
    const encryptedData = 'b6ab428efbcb93c2f483178114ac0608530e54428f1378c6d3be108531b730d1888e562044cd3acb8844a04d9d7602d83b96f0a758248ffd07cd9c530b76c91c';
    
    const decryptResponse = (data) => {
      const key = crypto.enc.Utf8.parse('F5:A4:F4:AB:BF:68:CF:86:51:B4:AA');
      const iv = crypto.enc.Hex.parse(data.substring(0, 32));
      const payload = data.substring(32);
      let decryptedData = crypto.AES.decrypt(
        payload,
        key,
        {
          iv: iv,
          mode: crypto.mode.CBC,
          // padding: crypto.pad.NoPadding,
          format: crypto.format.Hex
        });
      console.log(crypto.enc.Utf8.stringify(decryptedData));
    }
    
    decryptResponse(encryptedData);
    

    I commented out the padding: crypto.pad.NoPadding as there were non-printable characters at the end of the decryptedData when it was enabled.