Sub topic 13
Using SHA-256 to check integrity
This chapter assumes you know what a hash function is, why collisions are unavoidable, and the three cryptographic resistance properties from the previous chapters. It also assumes you can read basic Python and hexadecimal. Here you will use SHA-256 to answer one question: is this data exactly the data I expected?
What an integrity check does
SHA-256 belongs to the SHA-2 family. It maps input of any length to a 256-bit digest, which is 32 bytes or 64 hexadecimal characters. The same input always gives the same digest. A one-bit change in the input flips about half of the output bits, which is the avalanche effect you measured earlier.
An integrity check uses those two facts:
- Compute the digest of the data when you know it is good.
- Store or publish that digest.
- Later, hash the data you received and compare the new digest with the stored one.
If the digests match, the data is the same as the original. This relies on second-preimage and collision resistance. Finding a different input with the same SHA-256 digest takes roughly 2^256 work for a chosen target digest, or roughly 2^128 work to find any colliding pair. Neither is feasible today.
import hashlib
print(hashlib.sha256(b"abc").hexdigest())
print(hashlib.sha256(b"").hexdigest())
print(len(hashlib.sha256(b"abc").digest()), "bytes")The first line prints ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad. The second prints e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855, the digest of empty input. Both values are standard test vectors, so you can use them to confirm your environment is sane.
Hash bytes, not text
hashlib accepts only bytes. Passing a str raises TypeError. When you encode a string yourself, you choose the byte sequence being hashed:
"café".encode("utf-8")and"café".encode("latin-1")give different bytes, so different digests.- Unicode has more than one way to write some characters. A precomposed
éandefollowed by a combining accent look the same on screen but hash differently. - Text-mode file reads can translate line endings (
\r\nto\n), so a text-mode read of a file can produce a different digest from the same file read as bytes.
For files, always open in binary mode ("rb"). For text you control, agree on an encoding (UTF-8 is the usual choice) and a normalization form before hashing.
Hashing large files in chunks
Reading a 4 GB file into memory just to hash it is wasteful. SHA-256 processes input in 64-byte blocks and keeps a small internal state. hashlib exposes this through update(), so you can feed data in pieces. The result is identical to hashing everything at once.
import hashlib
import hmac
import os
import tempfile
def sha256_file(path: str, chunk_size: int = 1 << 20) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(chunk_size):
h.update(chunk)
return h.hexdigest()
def verify(path: str, expected_hex: str) -> bool:
actual = sha256_file(path)
return hmac.compare_digest(actual, expected_hex.strip().lower())
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "release.bin")
with open(path, "wb") as f:
f.write(b"release payload " * 100_000)
published = sha256_file(path)
print(published)
print(verify(path, published))
with open(path, "r+b") as f: # simulate corruption: flip one bit
first = f.read(1)
f.seek(0)
f.write(bytes([first[0] ^ 1]))
print(verify(path, published))This prints the digest, then True, then False. Note the details in verify:
strip().lower()normalizes the expected value. Hex digests are case-insensitive, but string comparison is not. Checksum files often contain trailing newlines.hmac.compare_digestcompares in constant time. For a public checksum this does not matter. It becomes important when you compare secret values such as MAC tags. Using one comparison habit everywhere avoids mistakes later.- The chunk size changes memory use and speed, not the result. Chunks of 64 KiB to 1 MiB are typical.
The command-line equivalents are sha256sum file on Linux, shasum -a 256 file on macOS, and Get-FileHash file in PowerShell.
The workflow for a download
A common use is checking a downloaded release against a published digest.
The diagram shows why the channel matters. The file comes from a mirror that you may not fully trust. The digest comes from the publisher. If an attacker controls the mirror, they can replace the file, but they cannot make it match a digest they cannot change.
What a plain digest does not protect against
SHA-256 detects change. It does not decide who made the change. The digest only helps if the attacker cannot alter it as well.
| Threat | Does a plain SHA-256 digest help? |
|---|---|
| Disk error or truncated download | Yes. Any change shows up as a mismatch. |
| Attacker swaps the file but not the digest | Yes, if the digest came from a trusted source. |
| Attacker swaps both file and digest on the same server | No. The attacker supplies a matching pair. |
| Attacker wants to forge a message in transit | No. Anyone can compute SHA-256, so anyone can attach a valid digest. |
When the digest is stored next to the file in the same place, it only protects against accidents. To resist an active attacker you need one of these:
- Publish the digest through a different, authenticated channel, such as the project's HTTPS site while the file lives on a third-party mirror.
- Sign the digest or the file with a digital signature (for example GPG or Sigstore), so you only need to trust the signer's public key.
- Use a keyed hash such as HMAC when both sides share a secret. The next chapter covers it.
Other places SHA-256 is used for integrity
- Content addressing. Container registries identify image layers by digest (
sha256:...). Fetching by digest means a registry cannot silently serve different content under the same name. - Lock files and package managers. pip's
--require-hashesmode and npm'sintegrityfield store a digest for each dependency, so a tampered package fails to install. - Deduplication. Storage systems hash blocks to find identical content. With a 256-bit digest, an accidental collision is negligible, so equal digests are treated as equal data.
- Merkle trees. Systems such as Git and certificate transparency logs hash data in a tree, so one root digest covers many items and you can prove a single item belongs with a short path of hashes.
Gotchas and edge cases
- Length extension. SHA-256 is built so that, given
H(m)and the length ofm, an attacker can computeH(m || padding || extra)without knowingm. This is whysha256(secret + message)is a broken way to authenticate messages. Use HMAC instead. For plain integrity checks of public data it is not a problem. - Truncation. Cutting a digest to 128 bits or fewer is common, such as short IDs in logs. It keeps preimage resistance reasonable, but the birthday bound on collisions drops to about 2^64 or lower. Truncate only when you can accept that.
- Short hex comparisons. Comparing only the first 8 characters of a digest, as some people do by eye, gives 32 bits of checking. An attacker could find a matching prefix with modest effort. Compare the full value.
- Speed. SHA-256 is fast but not instant. Modern CPUs with SHA extensions hash at gigabytes per second, so integrity checks are rarely the bottleneck. Do not reuse that speed for passwords, because it also helps an attacker guess.
- Choosing a variant. SHA-512 is often faster on 64-bit CPUs without SHA extensions. SHA-512/256 gives a 256-bit output and resists length extension. SHA-3 and BLAKE2/BLAKE3 are alternatives with different internal designs. For general integrity work, SHA-256 is the most widely supported choice.
Exercise
A project hosts app.tar.gz and app.tar.gz.sha256 on the same file server. A user downloads both, and sha256sum -c reports a match. Does this show the file is the one the authors released? Explain, and name one change that would fix it.
Show answer
No. It shows the two downloaded files agree, which catches corruption. An attacker who can modify the server can replace both the archive and its digest with a matching pair. Publishing the digest through a separate trusted channel, such as the project's HTTPS website, or signing the archive or digest with a key the user already trusts, would make the check meaningful against tampering.
Exercise
sha256_file reads the file with 1 MiB chunks. If you change the chunk size to 4 KiB, does the digest change? What changes?
Show answer
The digest does not change, because update() feeds the same byte sequence to the hash regardless of how it is split. Only memory use and speed change. A smaller chunk means more read calls and more Python overhead, and a larger chunk uses more memory.