I have encrypted data in node.js using crypto module, how can I decrypt in react.js using crypto-js

Viewed 3327

in node.js below given example its working fine, using crypto module in node.js encryption works well, but I don't know how can i decrypt that data in react using crypto-js library.

const crypto = require('crypto');
const ENC_KEY = "6fa979f20126cb08aa645a8f495f6d85"; // set random encryption key
const IV = "7777777a72ddc2f1"; // set random initialisation vector

const phrase = "who let the dogs out";

var encrypt = ((val) => {
  let cipher = crypto.createCipheriv('aes-256-cbc', ENC_KEY, IV);
  let encrypted = cipher.update(val, 'utf8', 'base64');
  encrypted += cipher.final('base64');
  return encrypted;
});

var decrypt = ((encrypted) => {
  let decipher = crypto.createDecipheriv('aes-256-cbc', ENC_KEY, IV);
  let decrypted = decipher.update(encrypted, 'base64', 'utf8');
  return (decrypted + decipher.final('utf8'));
});

var encrypted_key = encrypt(phrase);
var original_phrase = decrypt(encrypted_key);
console.log(encrypted_key) // hUU10kfhDhOKA0jb4efuYq3BbtyiBl+EqhfYdTkSkiI=
console.log(original_phrase) // who let the dogs out

using 'crypto-js' in react, how can I decrypt that encrypted data which are done by 'crypto' module in node.js? in react I can encrypt the data,

import CryptoJS from 'crypto-js'
aesEncrypt(data) {
    let key = '6fa979f20126cb08aa645a8f495f6d85';
    let iv = '7777777a72ddc2f1';
    let cipher = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC
    });
    console.log(cipher.toString()); 
}
1 Answers

When you get encrypted data from backend, simply use decrypt function(same from above code) in frontend which has same ENC_KEY. It will return decrypted data.

Related