MoltasDev
MoltasDev

Reputation: 65

.toString not encoding bytes to utf8 text?

I am trying to encrypt a string and then decrypt it. However, the conversion from bytes to text isn't working properly.

Code:

var cjs = require("crypto-js");
const fs = require("file-system");

var text1 = "Some text to be encrypted";

var ctext = cjs.AES.encrypt(text1, "key 123").toString();

var bytes = cjs.AES.decrypt(ctext, "key 123");

var uctext = bytes.toString();
console.log(bytes + "   "+uctext);
//console.log("\n\n\n\n\n\n" + uctext);
console.log(text1 === uctext);

The code outputs bytes on both "sides" and the variable that is supposed to be equal to the original text is still just bytes.

Upvotes: 0

Views: 958

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

You need to do this const uctext = bytes.toString(cjs.enc.Utf8);. Basically convert it to utf before comparing.

full code

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

const text1 = "Some text to be encrypted";

const ctext = cjs.AES.encrypt(text1, "key 123").toString();

const bytes = cjs.AES.decrypt(ctext, "key 123");

const uctext = bytes.toString(cjs.enc.Utf8);
console.log(`${bytes }   ${uctext}`);
// console.log("\n\n\n\n\n\n" + uctext);
console.log(text1 === uctext);

Upvotes: 1

Related Questions