1

I have an encrypted string created in NodeJS using crypto

NodeJS:

const crypto = require('crypto');
const key = Buffer.from(SECRET_KEY, 'base64');  

encrypt(text) {
   const iv = crypto.randomBytes(16);
   let cipher = crypto.createCipheriv( 
       'AES-128-CBC', key, iv);
   let encrypted = cipher.update(text);
   encrypted = Buffer.concat([iv, encrypted, cipher.final()]); 
   return encrypted.toString('hex');
}

It is working perfectly and I can't change the NodeJS. Then, I try to decrypt it using React crypto-js, but it returns an empty string.

var CryptoJS = require("crypto-js");

const KEY = SECRET_KEY;

export const decrypt = (text) => {
    var bytes  = CryptoJS.AES.decrypt(text, KEY);
    return bytes.toString(CryptoJS.enc.Hex);
}

Am I missing any configuration in React?

Thanks

1 Answer 1

2

The CryptoJS code is missing:

  • Separation of IV and ciphertext.
  • Specification of the IV.
  • Suitable decoding for ciphertext, key and IV (using the corresponding CryptoJS encoder).

The following ciphertext was created with the NodeJS code:

d906539383bb4931c434d58daaf82dc95bc9d6833089a4fd0014b331060bc18fff2270b18c561cae36aebd48a82e9de5eaee31dc4ed059929fe37b9a468d9cdf

This can be decrypted with the CryptoJS code below:

const KEY = 'MDEyMzQ1Njc4OTAxMjM0NQ==';
function decrypt(text) {
    
    // Separate IV and ciphertext
    var iv = text.substring(0, 32);
    var ciphertext = text.substring(32);

    var bytes  = CryptoJS.AES.decrypt(
        {ciphertext: CryptoJS.enc.Hex.parse(ciphertext)}, 
        CryptoJS.enc.Base64.parse(KEY), 
        {iv: CryptoJS.enc.Hex.parse(iv)});  // pass IV
    
    return bytes.toString(CryptoJS.enc.Utf8); // or Hex as in the posted code 
}

var encryptedData = 'd906539383bb4931c434d58daaf82dc95bc9d6833089a4fd0014b331060bc18fff2270b18c561cae36aebd48a82e9de5eaee31dc4ed059929fe37b9a468d9cdf';
console.log(decrypt(encryptedData)); // The quick brown fox jumps over the lazy dog
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.