DEV Community

Rajesh Pabbu
Rajesh Pabbu

Posted on

Client Side - Compute the SHA-256 hash of a file that is selected in a file input

Code

<html>
<body>
<input type="file" id="myfile" onchange="onMyfileChange(this)" />
<script type="text/javascript">
function onMyfileChange(fileInput) {
if (fileInput.files[0] == undefined) {
return;
}
var filename = fileInput.files[0].name;
// var filesize = fileInput.files[0].size;
var reader = new FileReader();
reader.onload = function (ev) {
console.log('File', filename, ':');
//
crypto.subtle
.digest('SHA-256', ev.target.result)
.then((hashBuffer) => {
// Convert hex to hash, see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, '0'))
.join(''); // convert bytes to hex string
console.log(hashHex);
})
.catch((ex) => console.error(ex));
};
reader.onerror = function (err) {
console.error('Failed to read file', err);
};
reader.readAsArrayBuffer(fileInput.files[0]);
}
</script>
</body>
</html>

Demo

https://stackblitz.com/edit/vitejs-vite-9xawha?file=index.html

References: Thank you all for the below

https://emn178.github.io/online-tools/sha256_checksum.html
https://hash-file.online/
https://emn178.github.io/online-tools/sha256_checksum.html
https://hash.online-convert.com/sha256-generator
https://techoverflow.net/2021/11/26/how-to-compute-sha-hash-of-local-file-in-javascript-using-subtlecrypto-api/
https://gist.github.com/miguelmota/6bae57a971676f570a767dbd12ca4c55/revisions
https://ilikekillnerds.com/2020/04/how-to-get-the-hash-of-a-file-in-node-js/

Top comments (0)