Awesome
Awesome

Reputation: 6609

How to calculate md5 checksum of blob using CryptoJS

Uploading file in chunks using Blob API. Here I want to check the md5 checksum of the blob. When I tried the below code it is working fine for text files, but it is returning different value for binary files.

var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onloadend = function () {
    var mdsum = CryptoJS.MD5(reader.result);
    console.log("MD5 Checksum",mdsum.toString());
};

How to calculate the md5 checksum of blob correctly for all types of files ?

Upvotes: 10

Views: 11817

Answers (1)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19060

Use the following code to create a correct md5 hash:

  function calculateMd5(blob, callback) {
    var reader = new FileReader();
    reader.readAsArrayBuffer(blob);
    reader.onloadend = function () {
      var wordArray = CryptoJS.lib.WordArray.create(reader.result),
          hash = CryptoJS.MD5(wordArray).toString();
      // or CryptoJS.SHA256(wordArray).toString(); for SHA-2
      console.log("MD5 Checksum", hash);
      callback(hash);
    };
  }

Update (a bit simpler):

 function calculateMd5(blob, callback) {
    var reader = new FileReader();
    reader.readAsBinaryString(blob);
    reader.onloadend = function () {
      var  hash = CryptoJS.MD5(reader.result).toString();
      // or CryptoJS.SHA256(reader.result).toString(); for SHA-2
      console.log("MD5 Checksum", hash);
      callback(hash);
    };
  }

Be sure to include core.js, lib-typedarrays.js (important) and md5.js components from CryptoJS library.
Please see this fiddle for a complete example (because of origin access control it won't work on fiddle, try it on your local server).

Upvotes: 17

Related Questions