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?
Generate SHA-256 Hashes for Files We can use the sha256sum command in two modes; binary and text (the default). On Linux, both modes generate the same SHA-256 hash, and so the default mode is used throughout this tutorial.
A cryptographic hash (sometimes called 'digest') is a kind of 'signature' for a text or a data file. SHA-256 generates an almost-unique 256-bit (32-byte) signature for a text. See below for the source code.
The SHA-256 algorithm is not yet easily cracked. Moreover SHA256 algorithm, such as SHA-512 algorithms compared to other secure top model is calculated more quickly is currently one of the most widely used algorithms. However, IT experts talk about allegations and developments that SHA-256 may be vulnerable very soon.
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")
This is an old question but I thought it's worth noting that asmCrypto
is significantly faster than jsSHA
, and faster than CryptoJS
and SJCL
https://github.com/vibornoff/asmcrypto.js/
There is also a lite version (a fork of the above) maintained by OpenPGP.js
https://github.com/openpgpjs/asmcrypto-lite
Which only includes SHA256, and a couple of AES features.
To use asmCrypto
You can simply do the following:
var sha256HexValue = asmCrypto.SHA256.hex(myArraybuffer);
I'm able to hash a 150MB+ file in < 2 seconds consistently in Chrome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With