简体   繁体   中英

File hash (Crypto-JS): same result in Chrome & Firefox / different result in Safari

I'm trying to make a hash of a file, through Crypto-JS .

The idea is to make a hash of the first bytes (ie from 10 to 100 ).

The result is not the same in Safari (last), as in Chrome & Firefox (both last): any idea about what's wrong in Safari?

JSfiddle

Hash function

const hashthefile = (filetoHash) => {
    return new Promise((resolve, reject) => {

        var start = 10;
        var stop = 100;

        // set reading operations through the FileReader API
        var reader = new FileReader();
        reader.onloadend = function(event) {
            // when the entire read request has been completed
            if (event.target.readyState == FileReader.DONE) {
                var data = event.target.result;
                var encrypted = CryptoJS.SHA256(data).toString();
                resolve(encrypted);
            }
        }
        // handle error
        reader.onerror = function(event) {
            reject('reading error')
        };
        // slice the file according to first and last bytes defined
        // complete API there: https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice
        var blob = filetoHash.slice(start, stop + 2);
        // launch the file sliced reading as a base64 encoded string
        reader.readAsDataURL(blob);
    });
}

I think I figure out how to have a consistent hash across Chrome, Firefox & Safari :

  • instead of readAsDataURL
  • use readAsArrayBuffer

Open to more advices and precisions of wiser coders (still don't know why using readAsDataURL produce a Safari-specific result).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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