我正在尝试在javascript中创建文件的SHA256哈希,该哈希与通过将文件上传到https://www.virustotal.com
生成的哈希匹配我在这里创建了一个简化的示例表单:https://codepen.io/alecdhuse/project/editor/XmWJWz使用SubtleCrypto.digest()。
我正在使用的测试文件为:https://www.gravatar.com/avatar/fa1e75c20502f7732fd8a23fed6d4fea
示例代码为:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="">
<input type="file" id="file-input" />
</div>
<div style="margin-top:20px;">
<div>
<textarea rows="18" cols="80" id="output_text" autocomplete="off" tabindex="1"></textarea>
</div>
</div>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript">
function read_file(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
hash_file(contents);
};
reader.readAsText(file);
}
document.getElementById('file-input')
.addEventListener('change', read_file, false);
async function hash_file(file_text) {
const digest_hex = await digest_message(file_text);
$("#output_text").val(digest_hex);
}
async function digest_message(message) {
const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
return hashHex;
}
</script>
</html>
但是,以上代码生成的哈希与VirusTotal生成的哈希确实匹配:https://www.virustotal.com/gui/file/a10cee61be30957936c20bcbaa812d030a9eb2c6cf28d4eedaa1caebfc9aa14b/detection
感谢您的帮助,谢谢。