Search code examples
javascriptnode.jsbase64cryptojs

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


I get an error trying to decode a file with crypto-js (containing a long base64 encoded string)

Error: Malformed UTF-8 data

What am I doing wrong and how do I fix it?

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

console.log(decode());

function decode() {
  // INIT
  const data = fs.readFileSync("./base64.txt", "utf-8"); // Base64 encoded string
  const encoded = data.toString();

  // PROCESS
  const encodedWord = CryptoJS.enc.Base64.parse(encoded); // encodedWord via Base64.parse()
  const decoded = CryptoJS.enc.Utf8.stringify(encodedWord); // decode encodedWord via Utf8.stringify() 
  return decoded;
}


Solution

  • I think you're reading the base64 file incorrectly. Try it like this, and see if it works;

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

    and then pass the data directly to,

    const encodedWord = CryptoJS.enc.Base64.parse(data);
    

    Or

    const data = fs.readFileSync("./base64.txt");
    const encoding = data.toString('base64');
    

    See if this resolves the issue.