How to calculate md5 checksum of blob using CryptoJS

蓝咒 提交于 2021-02-20 06:51:15

问题


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 ?


回答1:


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).



来源:https://stackoverflow.com/questions/34492637/how-to-calculate-md5-checksum-of-blob-using-cryptojs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!