user14009873
user14009873

Reputation:

Not returning anything base64 decode

I try to decrypt a file with crypto-js (in this file there is a long string of encrypted base64). but I don't get anything back the file is empty and the log too.

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

fs.writeFile("2pac.txt", decode(), (err) => {
  if (err) throw err;
  // success case, the file was saved
  console.log("Lyric saved!");
});

function decode() {
  // INIT
  const encoded = fs.readFileSync("./base64.txt", { encoding: "base64" });
  // PROCESS

  const decoded = CryptoJS.enc.Utf8.stringify(encoded); // decode encodedWord via Utf8.stringify() '75322541'
  console.log(decoded);
  return decoded;
}

In the console.log I get the test but I don't get anything(even undefined).

Upvotes: 0

Views: 337

Answers (1)

Kunal Kukreja
Kunal Kukreja

Reputation: 769

Replace this line:

const decoded = CryptoJS.enc.Utf8.stringify(encoded);

with:

const decoded = CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(encoded));

EDIT:

Reading base64 data from file is another problem. The data imported from the file with the encoding option set to base64 does guarantee a string instead of a buffer but it expects the input to be utf-8 encoding the base64 string again (double encoding).

To fix this, change the following:

const encoded = fs.readFileSync("./base64.txt", { encoding: "base64" });

to:

const encoded = fs.readFileSync("./base64.txt").toString();

Upvotes: 1

Related Questions