如何使用 SubtleCrypto API 在 Javascript 中计算本地文件的 SHA 哈希
以下示例使用 SubtleCrypto API 计算在文件输入中选择的文件的 SHA-256 哈希。校验和完全在客户端计算,文件完全不需要上传到服务器。
此代码已验证生成与在命令行运行 sha256sum 相同的校验和。
完整示例
你可以下载此文件,将其保存为 index.html 并在浏览器中打开。然后选择一个文件并检查开发者
index.html
<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>Check out similar posts by category:
Javascript
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow