24

I try to encrypt and decrypt this string using crypto-js:

const str = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI1ZDg5MjMxMjc5OTkxYjJhNGMwMjdjMGIiLCJoc2giOiIkMmEkMTMkWk53Y0cubjdRZFIybDA3S1RHd2RoLlN0QksudW5GSFVGLkZnZ0tQTGlUV2pOVEFqVy9SMm0iLCJncmFudCI6ImFjY2VzcyIsImlhdCI6MTU2OTI2ODUwMiwiZXhwIjoxNjAwODI2MTAyfQ.PQcCoF9d25bBqr1U4IhJbylpnKTYiad3NjCh_LvMfLE~3~null~undefined~434ce0149ce42606d8746bd9`;

But I got an error:

Error: Malformed UTF-8 data

What I doing wrong? How do I fix that?

The full code also on stackbliz:

import crypto from 'crypto-js';

const str = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI1ZDg5MjMxMjc5OTkxYjJhNGMwMjdjMGIiLCJoc2giOiIkMmEkMTMkWk53Y0cubjdRZFIybDA3S1RHd2RoLlN0QksudW5GSFVGLkZnZ0tQTGlUV2pOVEFqVy9SMm0iLCJncmFudCI6ImFjY2VzcyIsImlhdCI6MTU2OTI2ODUwMiwiZXhwIjoxNjAwODI2MTAyfQ.PQcCoF9d25bBqr1U4IhJbylpnKTYiad3NjCh_LvMfLE~9~null~undefined~434ce0149ce42606d8746bd9`;

const cryptoInfo = crypto.AES.encrypt(str, 'secret').toString();

console.log({ cryptoInfo });
const info2 = crypto.AES.decrypt(str, 'secret').toString(crypto.enc.Utf8);

console.log({ info2 });
Jon Sud
  • 10,211
  • 17
  • 76
  • 174

9 Answers9

15

Not sure why, but you have to wrap your string with an object and use JSON.stringify in order to make it works.

Here:

    import crypto from 'crypto-js';

    const str = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI1ZDg5MjMxMjc5OTkxYjJhNGMwMjdjMGIiLCJoc2giOiIkMmEkMTMkWk53Y0cubjdRZFIybDA3S1RHd2RoLlN0QksudW5GSFVGLkZnZ0tQTGlUV2pOVEFqVy9SMm0iLCJncmFudCI6ImFjY2VzcyIsImlhdCI6MTU2OTI2ODUwMiwiZXhwIjoxNjAwODI2MTAyfQ.PQcCoF9d25bBqr1U4IhJbylpnKTYiad3NjCh_LvMfLE~9~null~undefined~434ce0149ce42606d8746bd9`;

    const cryptoInfo = crypto.AES.encrypt(JSON.stringify({ str }), 'secret').toString();

    console.log({ cryptoInfo });
    const info2 = crypto.AES.decrypt(cryptoInfo, 'secret').toString(crypto.enc.Utf8);

    console.log({ info2 });

    const info3 = JSON.parse(info2);

    console.log({ str: info3.str });
Shlomi Levi
  • 3,114
  • 1
  • 23
  • 35
5

You forgot to pass the encrypted text as parameter to decrypt function.

In decrypt function you are passing original string, i.e. 'str' which is causing the problem in above code, here is the corret code.

import crypto from "crypto-js";

const str = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI1ZDg5MjMxMjc5OTkxYjJhNGMwMjdjMGIiLCJoc2giOiIkMmEkMTMkWk53Y0cubjdRZFIybDA3S1RHd2RoLlN0QksudW5GSFVGLkZnZ0tQTGlUV2pOVEFqVy9SMm0iLCJncmFudCI6ImFjY2VzcyIsImlhdCI6MTU2OTI2ODUwMiwiZXhwIjoxNjAwODI2MTAyfQ.PQcCoF9d25bBqr1U4IhJbylpnKTYiad3NjCh_LvMfLE~9~null~undefined~434ce0149ce42606d8746bd9`;

const cryptoInfo = crypto.AES.encrypt(JSON.stringify(str), "secret");

console.log({cryptoInfo});

const info2 = crypto.AES.decrypt(cryptoInfo.toString(), 'secret').toString(crypto.enc.Utf8);

console.log({ info2 });
Mahesh
  • 137
  • 1
  • 5
4

I encrypt a name and pass it as URL parameter. I was supprised, that the decrypt code did not work It was because of the "+" char generated in the encrypted parameter. Then using "encodeURIComponent" and "decodeURIComponent" it worked.

<script>
jQuery("#myBtn").click(function(){
    var clientname= jQuery("#myInput").val();
    var encrypted  = CryptoJS.AES.encrypt(clientname, "secret key 123");
    //my URL to call with encrypted client name
    jQuery("#output").append('<small id="myurl">https://www.xxxxx.com/?id='+encodeURIComponent(encrypted)+"</small>");
});
</script>  



var urlParams = new URLSearchParams(window.location.search);
var crypted_param = decodeURIComponent(urlParams.get('id'));
if(crypted_param && crypted_param != null && crypted_param != "" && crypted_param != "null"){   
    var decrypted = CryptoJS.AES.decrypt(crypted_param, "secret key 123");
    jQuery('#output1').val(decrypted.toString(CryptoJS.enc.Utf8));
}
    

Severine
  • 57
  • 1
2

Despite all the above suggestions check your Encryption Key and Secret Key. While decrypting Encryption Key should match with your Encryption Key which you have used at the time of encrypting.

Ahmer Saeed
  • 576
  • 5
  • 13
2
export function encryptTheValue(word, key = 'yourkey') {
  const encJson = CryptoJS.AES.encrypt(JSON.stringify(word), key).toString();
  const encData = CryptoJS.enc.Base64.stringify(
    CryptoJS.enc.Utf8.parse(encJson)
  );
  return encData;
}

export function decryptTheValue(word, key = 'yourkey') {
  const decData = CryptoJS.enc.Base64.parse(word).toString(CryptoJS.enc.Utf8);
  const bytes = CryptoJS.AES.decrypt(decData, key).toString(CryptoJS.enc.Utf8);
  return JSON.parse(bytes);
}

solution source github

TheEhsanSarshar
  • 2,677
  • 22
  • 41
0

Try this working example. https://stackblitz.com/edit/node-ugh35d?file=package.json,test_crypto.js

Just run npm start in the terminal. if npm i is not done please do.

Vinod Kumar
  • 108
  • 1
  • 4
  • 12
-1

I was experiencing the same issue, it seems the encrypted value is base64 and needs to be converted to utf-8 first. Example:

const utf8 = CryptoJS.enc.Base64.parse(value);
const decrypted = CryptoJS.DES.decrypt({ ciphertext: utf8 }, keyWords, { iv: ivWords });

I found the solution Here

-3

Might be this is slightly funny.. but this is how my senior has resolved this problem to me

We do have 2 different portals, assume XYZ portal and ABC portal (I am facing this issue in xyz portal) ABC is the portal where we login.. to redirect to XYZ portal..

So in local I have opened both xyz portal and ABC portal.. and the issue is resolved.. (Earlier I opened only xyz portal so I was facing the issue) :D

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 16 '22 at 12:31
-6

I've resolved my problem cleaning up the local storage.

enter image description here

legoscia
  • 39,593
  • 22
  • 116
  • 167
  • Oh my God, this actually was the problem faced by me with the addition of crypto library and when the new build was deployed for testing. Thanks man – Vipin kumar Jun 22 '23 at 12:32