Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the hash of Blob using JavaScript

Tags:

javascript

I want to compare two Blobs to see if there are changes between them.

One way of doing this is by calculating the hash of the blobs and then comparing them, e.g.:

hash(firstBlob) === hash(secondBlob)

How can I calculate the hash of a Blob and check against another hash to see if they have changed?

like image 447
fernandohur Avatar asked Dec 17 '13 00:12

fernandohur


1 Answers

You can use the FileReader API to get the contents of the blob for comparison. If you have to use CryptoJS for this, you can use readAsBinaryString:

var a = new FileReader();
a.readAsBinaryString(blob);
a.onloadend = function () {
  console.log(CryptoJS.MD5(CryptoJS.enc.Latin1.parse(a.result)));
};

Note that readAsBinaryString is deprecated, so if you can use another library, such as SparkMD5, you could use an array buffer instead:

var a = new FileReader();
a.readAsArrayBuffer(blob);
a.onloadend = function () {
  console.log(SparkMD5.ArrayBuffer.hash(a.result));
};
like image 99
Qantas 94 Heavy Avatar answered Oct 13 '22 02:10

Qantas 94 Heavy