Bytes do not need quotes.
Read raw bytes and calculate a digest without loading an entire file.
01 The idea
Text is an interpretation of bytes; binary mode gives you the bytes directly. Images, archives, and arbitrary downloads should not be decoded as text. A cryptographic hash summarises the exact byte sequence. Reading fixed-size chunks keeps the working memory bounded, although a digest alone does not establish who produced a file.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from pathlib import Path
import hashlib
path = Path("payload.bin")
path.write_bytes(b"abc")
digest = hashlib.sha256()
with path.open("rb") as stream:
while chunk := stream.read(65536):
digest.update(chunk)
print(digest.hexdigest())ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
03 Under the hood
- 1
rb prevents text decoding. read(65536) requests at most that many bytes; the final chunk can be smaller.
- 2
The assignment expression stores each chunk and checks whether it is nonempty. Empty bytes signal end of file.
- 3
update() can be called repeatedly. The resulting digest matches hashing the entire content in one operation, provided the bytes and order are identical.
04 Your turn, builder
Hash the same bytes in two chunks and confirm the digest equals a one-shot hash.
Reveal one possible solution +
import hashlib
parts = hashlib.sha256()
parts.update(b"ab")
parts.update(b"c")
print(parts.digest() == hashlib.sha256(b"abc").digest())05 Check your signal
Why use rb for an image?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.