asmcrypto / asmcrypto.js

JavaScript Cryptographic Library with performance in mind.
MIT License
659 stars 182 forks source link

Silent failures to produce the correct hash result #151

Open acdha opened 6 years ago

acdha commented 6 years ago

At some point the API changed in a way which causes the SHA functions to return technically correct but wrong results. I had a web worker which looked like this:

    for (
        let reader = new FileReaderSync(), start = 0, end;
        start < fileSize;
        start = end
    ) {
        end = start + Math.min(BLOCK_SIZE, fileSize - start);
        let slice = file.slice(start, end);
        let bytes = reader.readAsArrayBuffer(slice);
        sha256.process(bytes);
    }

This worked with older versions but with the current version it returns the hash of an empty buffer (e.g. SHA-256 = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855) because ArrayBuffer doesn't have a length property and so the data length loop exits immediately without an error:

https://github.com/asmcrypto/asmcrypto.js/blob/b6eb05d7e8ad52e00079dbdf33e8a62e691aaba8/src/hash/hash.ts#L34-L37

It wasn't that hard to find this and change sha256.process(bytes) to sha256.process(new Uint8Array(bytes)) but it'd be really nice if that code threw an exception to make the problem obvious since it might otherwise go unnoticed until someone actually checked the hashes or wondered why every file returned the same hash.