Javascript – Create SHA-256 hash from a Blob/File in javascript

hashhtmljavascriptperformancesha

I need to create a SHA-256 digest from a file (~6MB) inside the browser. The only way that I've managed to do it so far was like this:

var reader = new FileReader();
reader.onload = function() {
    // this gets read of the mime-type data header
    var actual_contents = reader.result.slice(reader.result.indexOf(',') + 1);
    var what_i_need = new jsSHA(actual_contents, "B64").getHash("SHA-256", "HEX");
}
reader.readAsDataURL(some_file);

While this works correctly, the problem is that it's very slow. It took ~2-3 seconds for a 6MB file. How can I improve this?

Best Answer

You may want to take a look at the Stanford JS Crypto Library

GitHub

Website with Examples

From the website:

SJCL is secure. It uses the industry-standard AES algorithm at 128, 192 or 256 bits; the SHA256 hash function; the HMAC authentication code; the PBKDF2 password strengthener; and the CCM and OCB authenticated-encryption modes.

SJCL has a test page that shows how long it will take.

184 milliseconds for a SHA256 iterative. And 50 milliseconds for a SHA-256 from catameringue.

Test page

Sample code:

Encrypt data: sjcl.encrypt("password", "data")

Decrypt data: sjcl.decrypt("password", "encrypted-data")