Skip to content

Instantly share code, notes, and snippets.

@qwesda
Last active September 22, 2022 00:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save qwesda/ce80f561999ceeb0a31ec50a980149e9 to your computer and use it in GitHub Desktop.
Save qwesda/ce80f561999ceeb0a31ec50a980149e9 to your computer and use it in GitHub Desktop.
asmcrypto - example - hash large file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hash large File Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/asmCrypto/0.22.0/asmcrypto.min.js"></script>
<script type="text/javascript" language="javascript">
function on_hash_done(hash, time_elapsed_seconds) {
document.getElementById('progress').innerText = '';
document.getElementById('result').innerText = 'sha256: ' + hash + ' took: ' + time_elapsed_seconds + 's';
document.getElementById('file_input').disabled = false;
}
function on_hash_progress(progress, time_elapsed_seconds) {
document.getElementById('progress').innerText = Math.round(progress * 1000)/10 + '% ' + time_elapsed_seconds + 's';
}
function on_hash_error(error) {
document.getElementById('progress').innerText = '';
document.getElementById('error').innerText = error;
document.getElementById('file_input').disabled = false;
}
function hash_file(file, on_hash_done, on_hash_progress, on_hash_error) {
var file_size = file.size;
var chunk_size = 1 * 1024 * 1024;
var offset = 0;
var time_started = Date.now();
var hasher = new asmCrypto.SHA256();
var file_reader = new FileReader();
file_reader.onload = function(e) {
if (e.target.error === null) {
offset += e.loaded;
const uint8_data = new Uint8Array(e.target.result)
hasher.process(uint8_data);
} else {
on_hash_error(e.target.error);
return;
}
var time_elapsed_seconds = Math.floor((Date.now() - time_started) / 100) / 10;
on_hash_progress(offset / file_size, time_elapsed_seconds);
if (offset < file_size) {
file_reader.readAsArrayBuffer(file.slice(offset, chunk_size + offset));
} else {
hasher.finish();
on_hash_done(asmCrypto.bytes_to_hex(hasher.result), time_elapsed_seconds);
return;
}
}
file_reader.readAsArrayBuffer(file.slice(offset, chunk_size + offset));
}
function on_file_select(e) {
if (e.target.files.length == 1) {
document.getElementById('file_input').disabled = true;
document.getElementById('result').innerText = '';
hash_file(e.target.files[0], on_hash_done, on_hash_progress, on_hash_error);
}
}
</script>
</head>
<body>
<h1>SHA256 large file</h1>
<input id="file_input" type="file" onchange="on_file_select(event)" />
<div id="progress"></div>
<div id="result"></div>
<div id="error"></div>
</body>
</html>
@qwesda
Copy link
Author

qwesda commented Aug 1, 2019

Yes, that's right. I also found this at some point, but forgot to update the gist.

thx

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