简体   繁体   English

更正javascript中所有文件类型的MD5哈希

[英]Correct MD5 hash in javascript for all filetypes

Using the library here: https://github.com/blueimp/JavaScript-MD5 I am attempting to correctly hash files in MD5 using javascript. 在这里使用库: https : //github.com/blueimp/JavaScript-MD5我正在尝试使用javascript正确哈希MD5中的文件。

So far I get correct hashes for text files but if I attempt to hash an image file I get an incorrect hash. 到目前为止,我得到了文本文件的正确哈希,但是如果我尝试对图像文件进行哈希,则会得到不正确的哈希。

This could be due to how the javascript FileReader reads the larger image files. 这可能是由于javascript FileReader如何读取较大的图像文件。 I have tried readAsBinaryString(), readAsArrayBuffer() and readAsText() none of which provide the correct hash with the given library. 我已经尝试过readAsBinaryString(),readAsArrayBuffer()和readAsText(),但是它们都不提供给定库的正确哈希值。

How should I be reading the file for this to provide a correct hash for all filetypes, is there a more appropriate library that works for all filetypes I should be using? 我应该如何为此读取文件以为所有文件类型提供正确的哈希,是否有更合适的库适用于我应该使用的所有文件类型?

HTML: HTML:

<input id="file-to-hash" type=file>
<button onclick="hashFile()">Hash</button>

Javascript: 使用Javascript:

function hashFile() {

 var file = document.getElementById('file-to-hash').files[0];

 var reader = new FileReader();
 reader.readAsArrayBuffer(file);
 reader.onload = readSuccess;
}

function readSuccess(evt){
 fileContents = evt.target.result;
 var hash = md5(fileContents);
}

There is now the SubtleCrypto API and its subtle.digest method. 现在有SubtleCrypto API及其subtle.digest方法。

You won't be able to get an MD5 hash from this API, because MD5 is not considered secure anymore . 您将无法从此API获取MD5哈希,因为MD5 不再被认为是安全的

But you'll be able to get an hash with other (more-secure) algorithms, such as SHA. 但是您将能够使用其他(更安全)的算法(例如SHA)获得哈希值。

 function getHash(buffer, algo = "SHA-256") { return crypto.subtle.digest(algo, buffer) .then(hash => { // here hash is an arrayBuffer, so we'll convert it to its hex version let result = ''; const view = new DataView(hash); for (let i = 0; i < hash.byteLength; i += 4) { result += ('00000000' + view.getUint32(i).toString(16)).slice(-8); } return result; }); } f.onchange = e => { const fR = new FileReader(); fR.onload = e => getHash(fR.result) .then(hash => console.log(hash)) // Chrome only accept it from an secure origin .catch(e => { if (e.code === 9) { console.log(`Be sure to be on the https page : https://stackoverflow.com/questions/44036218/`) } else { console.log(e.message) } }) fR.readAsArrayBuffer(f.files[0]); } 
 <input type="file" id="f"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM