Hashing#
CPython hashes work via hash(obj) for hashable objects
(everything immutable with a stable identity). Use it for set /
dict membership; do not use it for crypto or persistence (it’s
randomised per process by default).
hash((1, 2, 3))
hash("operator")
Cryptographic hashes (hashlib) for content addressing,
integrity, password storage (with KDF), digital signatures.
import hashlib
h = hashlib.sha256()
with open("payload.bin", "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
digest = h.hexdigest()
For password storage, never raw SHA-256. Use hashlib.scrypt,
passlib, or argon2-cffi. Stretching matters; speed is
the attacker’s friend.
HMAC for keyed authentication.
import hmac
hmac.compare_digest(expected, received) # constant-time
References#
dict for the in-memory hash table.