objectif
Calculer l’empreinte sha256 sans charger tout le fichier en mémoire.
code minimal
import hashlib, tempfile, pathlib
with tempfile.TemporaryDirectory() as tmp:
p = pathlib.Path(tmp) / "data.bin"
p.write_bytes(b"x" * 1024 + b"y")
h = hashlib.sha256()
with p.open("rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
digest = h.hexdigest()
print(len(digest) == 64) # attendu: True (64 hex chars)
utilisation
import hashlib
data = b"abc"
print(hashlib.sha256(data).hexdigest().startswith("ba7816bf"))
variante(s) utile(s)
import hashlib, io
buf = io.BytesIO(b"A"*10_000)
h = hashlib.file_digest(buf, "sha256") # Python 3.11+
print(hasattr(h, "hexdigest"))
notes
- Itérez par blocs (8–64 Ko) pour limiter l’usage mémoire.
- file_digest est pratique en 3.11+; sinon boucle manuelle.