hashfilereadersha256subtlecrypto

Getting Subtlecrypto SHA-256 digest different from sha256sum in linux terminal and trying to get file digest


I am getting a different hexdigest for the same string using SHA256 algo in linux terminal and using crypto.subtle. Here is what I am getting:

$ echo "foobar" | sha256sum
aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f  -

and using crypto.subtle:

crypto.subtle.digest("SHA-256", new TextEncoder().encode("foobar")).then((hash) => {
    console.log("rohdas hash " + hash);
    let arr = [...new Uint8Array(hash)].map(c => c.toString(16).padStart(2, '0')).join('');     
    console.log(arr); }).catch(err => console.log(err));
}
//c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2

I am also trying to generate the SHA256 digest of a zip file, but running into some XRayWrapper errors.

This is the code for the file digest:

let reader = new FileReader();
reader.readAsArrayBuffer(new File('/data/myfile.zip'));
reader.onloadend = () => {
console.log(reader.result + " " + reader.result.byteLength);//[object ArrayBuffer] 336
window.crypto.subtle.digest('SHA-256', reader.result).then((calculatedHash) => {// warning1 here
    console.log("calculatedHash " + calculatedHash);//calculatedHash [object Opaque]
    let calculatedHashHex = [...new Uint8Array(calculatedHash)];// error2 here
}).catch((err) => {console.log("digest error " + err);});
*warning1*
JavaScript Warning: "XrayWrapper denied access to property Symbol.toPrimitive (reason: object is not safely Xrayable). See https://developer.mozilla.org/en-US/docs/Xray_vision for more information. Note that only the first denied property access from a given global object will be reported."
*error2*
JavaScript Error: "Error: Accessing TypedArray data over Xrays is slow, and forbidden in order to encourage performant code. To copy TypedArrays across origin boundaries, consider using Components.utils.cloneInto()."

Solution

  • I am able to generate the hash of the file. Even though for strings it is not matching (might be some issue with encoding, etc.), the file hash is matching with the sha256sum value. There was some issue with the "window" object instance I was using. Closing this question.

    Edit: Adding my solution as per request in comments.

    To the first part:

    I simply used echo -n "foobar" to get the hash that subtlecrypto generates. Apparently echo also passes the "\n" if not mindful. Lesson learnt.

    To the second part:

    I was making some changes in the firefox source code, and passing a window object from DOM to the lower layers. The crypto in it was unable to access the encoded text ArrayBuffer that I was passing to the digest function. So I used Components.Utils.importGlobalProperties(['crypto']) and it worked without any XRayWrapper errors.