Skip to content

Instantly share code, notes, and snippets.

@eungjun-yi
Last active January 26, 2022 09:59
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save eungjun-yi/11282867 to your computer and use it in GitHub Desktop.
Save eungjun-yi/11282867 to your computer and use it in GitHub Desktop.
<html>
<!-- You may need to download them from https://github.com/brix/crypto-js/tree/release-3.1.2/build -->
<script src="rollups/sha1.js"></script>
<script src='components/lib-typedarrays-min.js'></script>
<body>
<script>
function sha1sum() {
var oFile = document.getElementById('uploadFile').files[0];
var sha1 = CryptoJS.algo.SHA1.create();
var read = 0;
var unit = 1024 * 1024;
var blob;
var reader = new FileReader();
reader.readAsArrayBuffer(oFile.slice(read, read + unit));
reader.onload = function(e) {
var bytes = CryptoJS.lib.WordArray.create(e.target.result);
sha1.update(bytes);
read += unit;
if (read < oFile.size) {
blob = oFile.slice(read, read + unit);
reader.readAsArrayBuffer(blob);
} else {
var hash = sha1.finalize();
console.log(hash.toString(CryptoJS.enc.Hex)); // print the result
}
}
}
</script>
<form name="uploadForm">
<input id="uploadFile" type="file" onchange="sha1sum();" />
<input type="submit" value="Send" />
</form>
</body>
</html>
@jamesmontalvo3
Copy link

I had to modify your WordArray.create call to add byte length:

var bytes = CryptoJS.lib.WordArray.create( e.target.result, e.target.result.byteLength );

Without this I got a Uncaught RangeError: Invalid array length error. However, this is still not computing the sha1 the same as on my backend.

@jamesmontalvo3
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment