[SOLVED] How to decrypt in node js that is sent from react by encrypting? () – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Manas S. Roy

I want to encrypt all my request from the client end and decrypt it in backend side. I am useing Crypto-Js in the react for the encryption. I am getting the encrypted request when i console it as req.body . But how can I decrypt it in my node js side? I am getting error with crypto in node js side. This is what I have tried so far:

React.js

transformRequest: [
    (data, headers) => {
      
      var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), '&CzHaI!ux0C1av5#fwD$4^lAN%haKqo0').toString();
      console.log(ciphertext);
      return ciphertext;
    },
    ...axios.defaults.transformRequest,
  ],

Nodejs:(created a middlewire)

let decryptionService = function(req, res, next) {
let decryptionData = decryptMessage(req.body)

console.log(decryptionData);
next();
}

in the decryp.js file:

function decryptMessage(msg){

// secret key generate 32 bytes of random data
const Securitykey = "&CzHaI!ux0C1av5#fwD$4^lAN%haKqo0";



const decipher = crypto.createDecipheriv(algorithm, Securitykey, initVector);

console.log("Decrypted decipher: " + JSON.stringify(decipher));


let decryptedData = decipher.update(msg, "hex", "utf-8");

console.log("Decrypted decryptedData: " + decryptedData);


decryptedData += decipher.final("utf8");

console.log("Decrypted message: " + decryptedData);

return decryptedData;
}



Solution

Try below code. It works for me

var bytes  = crypto.AES.decrypt(msg, Securitykey);
var decryptedData = JSON.parse(bytes.toString(crypto.enc.Utf8));


This Question was asked in StackOverflow by Manas S. Roy and Answered by Ramkumar G It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?