Why I get Malformed UTF-8 data error on crypto-js?

Jon Sud picture Jon Sud · Sep 26, 2019 · Viewed 13.4k times · Source

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 });

Answer

Shlomi Levi picture Shlomi Levi · Sep 26, 2019

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 });