12

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?

2 Answers 2

12

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));
};
Sign up to request clarification or add additional context in comments.

7 Comments

@RaymondWu: seems you're correct, fixed the answer. Thanks!
you sould define the onloadend method before the call to readAsBinaryString or readAsArrayBuffer : otherwise, with a small enough buffer, you might get the onloadend event handler registered after the event was triggered
@Thierry: I don't think that's ever happened in my experience -- IIRC readAs* is defined to be asynchronous, which means the onloadend function will be defined before the event is called.
Asynchronous doesn't mean that. Asynchronous means it might run after the next instruction. It might also run before. In this particular case, we observe that most of the time it running after the next instruction. It is not guaranteed though.
Since the behavior is browser specific, and may be async, it's best to assume it is. Therefore, it's best to set the event handlers before calling the function that will lead to the event being emitted.
|
10

I know this is kind of old but for someone looking for a better and newer solution please use the Crypto API and a SHA-256 or higher variant for the algorithm since MD5 has exploitable flaws.

var a = new FileReader();
a.readAsArrayBuffer(blob);
a.onloadend = function () {
  let hashPromise = crypto.subtle.digest("SHA-256", a.result);// it outputs a promise
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.