How to Hash Large Files in the Browser (SHA-256, Streaming WASM)
crypto.subtle.digest('SHA-256', buffer) is the first thing most of us reach for when we need a file hash in JavaScript. It works, until someone drops a 5 GB disk image on the page. digest() has no streaming API: it wants
crypto.subtle.digest('SHA-256', buffer) is the first thing most of us reach for when we need a file hash in JavaScript. It works, until someone drops a 5 GB disk image on the page. digest() has no streaming API: it wants the whole file in one ArrayBuffer, so memory grows with the file and the tab eventually dies.
We hit this while building a checksum verifier that compares downloads against a published SHA-256, MD5 or a whole SHA256SUMS list, without uploading anything. Here is the approach we ended up with and the details that took longer than expected.
Read the file in slices, feed a streaming hasher
A File is a Blob, and Blob.slice() is cheap: it returns a view, and nothing is read until you ask for the bytes. So the loop is simple:
const CHUNK = 4 * 1024 * 1024; // 4 MiB
export async function hashFile(
file: Blob,
onProgress?: (ratio: number) => void,
signal?: AbortSignal,
) {
const { createSHA256 } = await import('hash-wasm'); // lazy: only when needed
const hasher = await createSHA256();
hasher.init();
for (let offset = 0; offset < file.size; offset += CHUNK) {
if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');
const end = Math.min(file.size, offset + CHUNK);
const chunk = new Uint8Array(await file.slice(offset, end).arrayBuffer());
hasher.update(chunk);
onProgress?.(end / file.size);
}
return hasher.digest(); // lowercase hex
}
Only one 4 MiB slice is alive at a time, so the memory peak does not depend on file size. That is why the tool has no file size limit at all, while our other file tools cap input at 50 MB.
hash-wasm gives incremental init / update / digest hashers for MD5, SHA-1, SHA-256, SHA-512 and CRC32, compiled to WebAssembly. We load it with a dynamic import(), so the page doesn't download it until the first digest is actually needed.
A few choices worth explaining:
-
4 MiB slices. Small enough that memory stays flat, large enough that the per-slice overhead (one
arrayBuffer()promise, one WASM call) disappears in the total. -
Several algorithms in one pass. If a list contains both an MD5 and a SHA-256 for the same file, we create both hashers and call
update()on each with the same chunk. The file is read once. - Files one after another, not in parallel. Hashing three files at once means three slices in memory at once, plus whatever the browser buffers. Sequential processing keeps the peak predictable.
-
Cancellation between slices. We check the
AbortSignalbefore and after each read. Files that already finished keep their result; the rest are marked as cancelled.
One honest caveat: we only make claims about memory, not speed. A 5 GB image still has to be read end to end, and how long that takes depends on the device and on where the file lives.
Guess the algorithm from the hash length
Users paste a hash and don't want to pick "SHA-256" from a dropdown. Hex length is unambiguous for the common algorithms:
| Hex length | Algorithm |
|---|---|
| 8 | CRC32 |
| 32 | MD5 |
| 40 | SHA-1 |
| 64 | SHA-256 |
| 128 | SHA-512 |
We keep this mapping in one table and nowhere else. A BSD-style line (SHA256 (file.iso) = âŚ) carries an explicit tag, so the length check is skipped there.
Parsing real-world SHA256SUMS lists
This took more code than the hashing. People paste whatever the release page shows, so the parser tries four layouts in order and uses the first that matches:
-
BSD, from
shasum --tag:SHA256 (normal.zip) = 1c5f⌠-
GNU, from
sha256sum/md5sum:1c5f⌠normal.zip(a leading*for binary mode is dropped) -
Bare digest:
SHA256: 1C5FâŚwith labels,0xand inner spaces stripped - Name first, hash last: what you get when you copy a table from a release page
Other details that matter in practice:
- Strip a UTF-8 BOM and accept CRLF line endings (lists generated on Windows).
- Skip blank lines and lines starting with
#or;. Count everything else that fails to parse and report it with a reason. Don't drop it silently. - Cap the list at 2,000 lines, and tell the user how long the list was if you truncate.
- Strip paths and quotes from names, so
"./dist/a.iso"matches a file calleda.iso. Compare names case-insensitively. - Compare hashes after
trim()andtoLowerCase(). Output always uses lowercase hex, which is whatsha256sum,shasumandcertutilprint.
Pairing list entries with files
The rule that needed the most thought: when do file names matter?
- If the list holds exactly one bare hash, compare it against every file, names ignored. This is the common "paste the hash from the download page" case.
- If the list has several entries, match by name. A file with no matching entry still gets its hash computed (with the algorithm most common in the list) and is reported as "not found in the list", so you can compare it by eye.
- If the same name appears with two different hashes, compare both and flag it. This usually means the list mixes two release versions.
When a comparison fails, a few cheap checks give better hints than "mismatch":
- 0 bytes means the download failed.
- Under 1 KB means you probably saved an error page.
- Hash matches another entry in the list means you are checking the wrong file.
Results
The output matches the command-line tools byte for byte. On our test sample (normal.zip, 652 bytes), the page shows the same SHA-256 as shasum -a 256 and the same MD5 as md5 -q. Up to 50 files run per batch, and the results can be exported as CSV through a blob URL built in the page.
"Nothing is uploaded" is checkable. Open DevTools â Network while a check runs: the page loads its own code and the WASM module, and no request contains file data.
If you need this without writing it yourself, the tool is live at gingertool.com/en/file-tools/checksum-verifier. Questions about the parser edge cases are welcome in the comments.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes â full credit and traffic to the original publisher.