0

I am using crypto-js plain text encryption/decryption in my NodeJS app. When I tested the following code on the server-side everything works as expected:

 var encrypted_string = CryptoJS.AES.encrypt(input_string, '123Key');

 var bytes  = CryptoJS.AES.decrypt(encrypted_key.toString(), '123Key');
 var decryted_string = bytes.toString(CryptoJS.enc.Utf8);

However, when I send encrypted_string via AJAX call I get an error

My code for AJAX call is here:

let data = {}
data.encrypted_string = 'foo';
$.ajax({
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json',
    url: '/route/to/',
    success:function(response_data_json) {
        // do something
        }
    }
})

In route code:

var ciphertext = req.body.encrypted_string
var bytes  = CryptoJS.AES.decrypt(ciphertext.toString(), '123Key');
var decryted_string = bytes.toString(CryptoJS.enc.Utf8);

i get an error on bytes.toString... line

Malformed UTF-8 data

Thanks in advance for any guidance

goryef
  • 1,337
  • 3
  • 22
  • 37

1 Answers1

0

first I noticed a little typo: c <> n var ecnrypted_string = Cry...

however that's not your source of the issue.

What you're likely missing is the JSON.decode on the Server because your ciphertext var still contains that exact string you've send from the client which you can see like this:

let data = {};
data.encrypted_string = 'foo';
let stringified = JSON.stringify(data);
console.log(stringified);
console.log(stringified.toString());

The output for both logs would be: {"encrypted_string":"foo"} which ofcourse cannot be parsed by CryptoJS directly.

Hope this helps. Best, Sebo

magicbyt3
  • 143
  • 9
  • Actually the encrypted string seem fine when it's gets to the router. – goryef Nov 22 '19 at 16:22
  • 1
    so ciphertext would output 'foo' ? researching a bit further this seems to be related to an issue between UTF-8 and JSON because according to this answer here: https://stackoverflow.com/questions/27253150/json-stringify-to-utf-8 browsers can use only UCS-2 or UTF-16 encoding, if you'd change this to UTF-16 instead it should work: ```var decryted_string = bytes.toString(CryptoJS.enc.Utf16);``` – magicbyt3 Nov 22 '19 at 18:19