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:

1
2
3
4
5
6
7
8
9
import hashlib

digest = hashlib.sha256()
digest.update(b"a")
digest.update(b"bc")

print(digest.hexdigest())
# ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
print(digest.hexdigest() == hashlib.sha256(b"abc").hexdigest())  # True

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import hashlib


def sha256_file(path, chunk_size=1024 * 1024):
    """Return the SHA-256 hex digest of bytes read from a file."""
    if type(chunk_size) is not int:
        raise TypeError("chunk_size must be an integer")
    if chunk_size <= 0:
        raise ValueError("chunk_size must be positive")

    digest = hashlib.sha256()
    with open(path, "rb") as source:
        while True:
            chunk = source.read(chunk_size)
            if not chunk:
                break
            digest.update(chunk)

    return digest.hexdigest()

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import argparse
import re

from file_hash import sha256_file

parser = argparse.ArgumentParser(description="Check a file's SHA-256 digest")
parser.add_argument("path")
parser.add_argument("expected", help="Trusted 64-digit hexadecimal SHA-256")
args = parser.parse_args()

if re.fullmatch(r"[0-9a-fA-F]{64}", args.expected) is None:
    parser.error("expected must contain exactly 64 hexadecimal digits")

actual = sha256_file(args.path)
if actual != args.expected.lower():
    raise SystemExit("SHA-256 mismatch: " + actual)

print("SHA-256 matches: " + actual)

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import hashlib
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

from file_hash import sha256_file


class FileHashTests(unittest.TestCase):
    def test_known_vectors(self):
        vectors = [
            (b"", "e3b0c44298fc1c149afbf4c8996fb924"
                   "27ae41e4649b934ca495991b7852b855"),
            (b"abc", "ba7816bf8f01cfea414140de5dae2223"
                      "b00361a396177a9cb410ff61f20015ad"),
        ]
        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "asset.bin"
            for data, expected in vectors:
                path.write_bytes(data)
                for chunk_size in (1, 2, 3, 1024):
                    self.assertEqual(sha256_file(path, chunk_size), expected)

    def test_binary_data_and_boundaries(self):
        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "asset.bin"
            for size in (0, 1, 63, 64, 65, 255, 256, 257, 4097):
                data = (bytes(range(256)) * 17)[:size]
                path.write_bytes(data)
                expected = hashlib.sha256(data).hexdigest()
                for chunk_size in (1, 64, 256, 1024):
                    self.assertEqual(sha256_file(path, chunk_size), expected)

    def test_invalid_sizes_and_missing_file(self):
        with tempfile.TemporaryDirectory() as directory:
            missing = Path(directory) / "missing.bin"
            for value in (0, -1):
                with self.assertRaises(ValueError):
                    sha256_file(missing, value)
            for value in (True, False, 1.5, "1024", None):
                with self.assertRaises(TypeError):
                    sha256_file(missing, value)
            with self.assertRaises(FileNotFoundError):
                sha256_file(missing)

    def test_read_failure_closes_file(self):
        with patch("builtins.open") as opened:
            source = opened.return_value.__enter__.return_value
            source.read.side_effect = [b"partial", OSError("read failed")]
            with self.assertRaises(OSError):
                sha256_file("asset.bin", 8)
            opened.return_value.__exit__.assert_called_once()


if __name__ == "__main__":
    unittest.main()

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.