-1

I have JSON which I have AES encrypt with a secret on Node backend and send it to my React frontend. When I try to decrypt it on the frontend I get an error

"Malformed Utf-8" data error

When the encryption/decryption in their own respective boundaries works as expected. But when I try to make it a cross-platform thing then it fails. So what is the issue here?

Michael Nelles
  • 5,426
  • 8
  • 41
  • 57

1 Answers1

-1

yes you can do it, encrypt data on node and send it to react and encrypt the data on react and send it to your node server. I made it in this way:

in react:

import CryptoJS from "crypto-js";

function whatever(){        
    var passPhrase = process.env.YOURSECRETPHRASE || "Secret Phassphrase";    

    const handleSubmit(somedata){    
        var encrypted_data =CryptoJS.AES.encrypt(somedata,passPhrase).toString(); 

        send(encrypted_data);
    };
}

in node:

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

function whatever(dataString){
    var passPhrase = process.env.YOURSECRETPHRASE || "Secret Phassphrase";
    console.log("encrypted", dataString);
    var decrypted = CryptoJS.AES.decrypt(dataString, passPhrase);
    var decrypted_string = decrypted.toString(CryptoJS.enc.Utf8);
    console.log("decrypted", decryoted_string);
};

Note that i let the secret phrase in plain text for the example, but is recomended to use a environment variable like de process.env.YOURSECRETPHRASE. Note that is important to manage the utf-8 format to see the result in plain text again.

You also have to check that you have the same version of the crypto-js package installed by npm in your package.json. And that's it, if you will save sensitive data on a data base, is recomended to hash it with an algorithm like bcrypt from the bcrypt package or use another module from crypto-js like sha-256.