How to calculate md5 blob checksum using CryptoJS

Upload a file to chunks using the Blob API. Here I want to check the md5 checksum of the blob. When I tried the code below, it works fine for text files, but it returns a 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 md5 blob checksum correctly for all file types?

+5
source share
1 answer

Use the following code to create the 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 little easier):

  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 the core.js , lib-typedarrays.js ( important ), and md5.js from the CryptoJS library.
See This fiddle for a complete example (due to access control to the data source it will not work on the fiddle, try on the local server).

+8
source

Source: https://habr.com/ru/post/1239347/


All Articles