5

Using the HTML5 File API and any JavaScript crypto library, how can I generate an MD5 hash of the file?

To read the file:

var reader = new FileReader();

reader.onload = function(e) {
  var contents = e.target.result;
  // What goes here?
};

reader.readAsBinaryString(data.files[0]);

1 Answer 1

5

This goes there:

var reader = new FileReader();

reader.onload = function(e) {
  var contents = e.target.result;
  // This goes here:
  var hash = CryptoJS.MD5(CryptoJS.enc.Latin1.parse(contents));
};

Be sure you include the CryptoJS library:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. That gives me a hash, but it is not the correct hash (compared to Ruby, bash and an online JS hasher).
Are you using reader.readAsBinaryString to load in the file?
Yes I am using reader.readAsBinaryString(data.files[0]); (added to my question). I've also tried using reader.onloadend for the callback.
I just did some more research, and found that it may have to do with the string encoding. Try my edited answer, which adds an encoding step.
CryptoJS.MD5() returns an object, you'll have to call its toString() method to get the MD5 string.
|

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.