dendisdon
dendisdon

Reputation: 33

MD5 Checksum differes from browser to Node js API

I am trying to perform a checksum on a file with javascript. I'm using a FileReader and using CryptoJS with the .MD5 method as well as the CryptoJS.enc.Hex encoding.

The checksums differ from the front end (above) and on the back end, where I am getting it from ExpressFIleUpload and also generated my own with the crypto module via crypto.createHash('md5') and getting a digest via hash.digest('hex'); and out of those two, (my own and ExpressFileUpload) they too, differ..

what is going on..?

        let img = document.createElement('img');
        img.file = data;

        let reader = new FileReader();
        reader.onload = (function (someelement) {
            return function (e) {
                let md5 = CryptoJS.MD5(e.target.result);
                let str = md5.toString(CryptoJS.enc.Hex);
                console.log('str', str); // will give one random md5
            };
        })(img);

        reader.readAsBinaryString(data);

then on the server using https://www.npmjs.com/package/express-fileupload

export async function(req, res, next) {
  console.log(req.files.file.md5) // some other md5
  
  const hash = crypto.createHash('md5');
  let buff = Buffer.from(req.files.file.data, "base64").toString('utf-8');

  // edit, this actually DOES come to the same if I remove 
  // .toString('utf-8')
  // as the req.files.file.md5

  hash.update(buff);

  let str = hash.digest("hex");
  console.log('other hash', str); // and some third completely different md5
}

can someone please explain what I am doing wrong?

Upvotes: 3

Views: 1701

Answers (1)

Julius Babies
Julius Babies

Reputation: 1861

Did you encode the e.target.result to UTF-8 in your front-end? I had kind of like the same problem, but then I realized, that I'd used the wrong encoding.

Try to encode your Plain String into utf-8 and hash it after that.

Upvotes: 1

Related Questions