Hash Large Files with SHA-256 in Python Using Bounded Reads
A downloaded game asset bundle needs to match the checksum in its release manifest. Loading the entire bundle with read() works for a small fixture, but makes memory use grow with the file size.
Feed successive binary chunks into one SHA-256 object instead. This Python 3 implementation uses the standard library, returns a conventional hexadecimal digest, and lets file errors reach the caller.
Hash Bytes in Order
An incremental hash keeps state between updates. Calling update() twice hashes the same byte sequence as concatenating those two inputs and hashing once:
The hashlib reference defines this update behavior. Chunk boundaries do not become part of the input. Byte order does, so process chunks in file order.
Create the hash object once per file. Creating a fresh object for every chunk and joining its digests produces a different format; it does not produce the file’s SHA-256 checksum.
Read a File in Bounded Chunks
Save this helper as file_hash.py:
| |
Use binary mode so the input stays as bytes, without text decoding or newline conversion. A ZIP archive, a PNG, and a text file all follow the same byte-oriented path. Different newline bytes intentionally produce different digests.
Each read requests at most chunk_size bytes. The default is one mebibyte, or 1,048,576 bytes. The helper retains a bounded number of chunks plus fixed hash state and file buffering, so its working memory is O(chunk_size), independent of total file size. This is not a claim that the whole Python process uses exactly one mebibyte.
Stop only when a read returns empty bytes. A nonempty chunk shorter than the request still needs hashing, and another read can follow it. Empty files need no special branch: the untouched hash object supplies their digest.
Zero would make the first read look like end-of-file. A negative size could request the entire remaining file. Reject both before opening the file, and reject booleans and non-integers as configuration mistakes. Choose a reasonable chunk size for your application; this helper does not impose a maximum.
Check a Downloaded Asset
Save this command-line entry point as check_asset.py beside the helper:
| |
Run python check_asset.py assets.zip EXPECTED_SHA256, replacing EXPECTED_SHA256 with the release manifest’s digest. Uppercase hexadecimal is accepted and normalized for comparison; whitespace and a checksum-file line containing a filename are rejected. Pass only the digest argument.
A match exits successfully. A mismatch exits with status 1, and malformed arguments use argparse’s error exit. Missing files and read failures raise exceptions rather than returning a partial digest that could look successful. If wrapping this script in a build pipeline, retain its nonzero exit status.
Obtain the expected digest through a trusted release channel. An attacker who can replace both the file and its expected digest can make this comparison pass. Use the publisher’s signature verification process when the release provides one.
Test Empty Files and Chunk Boundaries
Save this as test_file_hash.py beside file_hash.py, then run python test_file_hash.py:
| |
The small in-memory reference hashes in the tests are deliberate: fixtures are tiny, and they check that changing read boundaries does not change the result. The all-byte-values fixture also catches accidental text decoding. The injected read error verifies that an interrupted calculation raises and exits the file context.
Keep the File Stable During Verification
Hash a completed download or an immutable build artifact. Reading in chunks does not create a filesystem snapshot. If another process overwrites the file during hashing, the bytes observed may not correspond to any single complete version.
Likewise, a successful check describes the bytes read during that calculation. It does not guarantee that a later open of the same path will see identical content. Arrange the download, verification, and installation steps so writers cannot replace or modify the artifact between those steps. Comparing sizes or modification times can help diagnose changes, but does not establish that guarantee.
On Python 3.11 and later, the standard library also provides hashlib.file_digest for hashing an open binary file. The explicit loop here makes its read-size policy visible and supports earlier Python 3 versions. Both approaches still require a stable input file and a trusted expected checksum.