hashlib, hmac and secrets
Three small modules of the standard library do most of the cryptographic work in everyday security tools. hashlib fingerprints files and messages, hmac proves that a message came from someone who holds a key, and secrets makes tokens that nobody can guess. Each is easy to call and easy to misuse: a hash used where a MAC was needed, a comparison that leaks how many characters were right, a session token from the random module. This lesson uses all three correctly and shows what the wrong version looks like. The theory behind them is in Applied Cryptography; the survey lesson Hashing is the gentle start.
Definitions
- Cryptographic hash (SHA-256, SHA-3, BLAKE2): a fixed-size fingerprint of any input. Changing one bit changes about half of the output bits; finding two inputs with the same hash is infeasible. It has no key: anyone can compute it.
- MAC (message authentication code), here HMAC (RFC 2104): a hash mixed with a secret key. Only key holders can produce a valid tag, so it proves integrity and origin.
- Constant-time comparison:
hmac.compare_digest(a, b)takes the same time whether the first byte or the last one differs. - CSPRNG: a cryptographically secure pseudo-random generator.
secretsuses the operating system's (os.urandom). Therandommodule is a Mersenne Twister: fast, reproducible from a seed, and predictable after 624 outputs, so it is for simulations only.
Hashes and MACs
A lab service receives webhook calls. The sender and receiver share a key; the sender puts HMAC-SHA256(key, body) in a header. The example uses a fixed key so the output is stable; real code loads the key from a secret store and generates it with secrets.token_bytes(32).
import hashlib, hmac
body = b'{"event":"deploy","service":"www.lab.test","version":"1.4.2"}'
print("sha256 ", hashlib.sha256(body).hexdigest())
print("sha3_256 ", hashlib.sha3_256(body).hexdigest()[:32], "...")
print("blake2b ", hashlib.blake2b(body, digest_size=16).hexdigest())
# Large files: hash in chunks so memory stays small.
h = hashlib.sha256()
for chunk in [body[:20], body[20:]]:
h.update(chunk)
print("chunked equal:", h.hexdigest() == hashlib.sha256(body).hexdigest())
KEY = bytes.fromhex("6c61622d6f6e6c792d77656268f06b2d6b65792d30303031") # lab-only fixed key
tag = hmac.new(KEY, body, hashlib.sha256).hexdigest()
print("hmac ", tag)
def verify(body, received_tag):
expected = hmac.new(KEY, body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received_tag)
tampered = body.replace(b"1.4.2", b"6.6.6")
print(verify(body, tag), verify(tampered, tag))
# An attacker who changes the body can recompute a plain hash, but not the HMAC:
print("plain hash of tampered:", hashlib.sha256(tampered).hexdigest()[:16], "... (anyone can make this)")sha256 a6360e17cd99c587706c52a5d03e0b6826bca4bc018f6428b56b07f9c8a919a7
sha3_256 b5f83e7a14739ab5be7a909e722dd9ea ...
blake2b 73e55ae349f5a74686bd3ec2c573b37b
chunked equal: True
hmac 29ee7c87324a09d36d7ecfa008ceeeb49c864830de8caae13c748e0802f1b319
True False
plain hash of tampered: 52c1f0a368462e8d ... (anyone can make this)
The plain SHA-256 protects nothing against an attacker who can change the message, because they simply recompute it. The HMAC check fails on the tampered body, and the attacker cannot produce a new valid tag without the key.
Why the comparison matters
A naive expected == received comparison of strings stops at the first differing character. If an attacker can measure response times precisely, they can guess a tag one character at a time. Real timing attacks need many samples and a quiet network; the example makes the leak visible by counting the characters each comparison examines instead of measuring the clock.
import hmac
def naive_equal(a, b, stats):
if len(a) != len(b):
return False
for x, y in zip(a, b):
stats["steps"] += 1
if x != y:
return False # early exit: work done depends on the secret
return True
secret_tag = "7f3a9c"
for guess in ["000000", "700000", "7f0000", "7f3a00", "7f3a9c"]:
stats = {"steps": 0}
ok = naive_equal(secret_tag, guess, stats)
print(f"guess {guess}: steps {stats['steps']} equal {ok} compare_digest {hmac.compare_digest(secret_tag, guess)}")guess 000000: steps 1 equal False compare_digest False
guess 700000: steps 2 equal False compare_digest False
guess 7f0000: steps 3 equal False compare_digest False
guess 7f3a00: steps 5 equal False compare_digest False
guess 7f3a9c: steps 6 equal True compare_digest True
Each correct leading character costs the naive comparison one more step, which is the signal a timing attacker measures. compare_digest does not stop early, so its running time does not depend on how many characters match.
Tokens that can't be guessed
import secrets, string
token = secrets.token_urlsafe(32) # 32 bytes = 256 bits from the OS CSPRNG
print(len(token), "characters, URL-safe")
print(len(secrets.token_hex(16)), "hex characters for 128 bits")
alphabet = string.ascii_letters + string.digits
pw = "".join(secrets.choice(alphabet) for _ in range(20))
print(len(pw), "characters from", len(alphabet), "symbols")
import math
print(f"strength: {20 * math.log2(len(alphabet)):.1f} bits")
print(f"a 6-digit code has only {6 * math.log2(10):.1f} bits: rate-limit it")43 characters, URL-safe
32 hex characters for 128 bits
20 characters from 62 symbols
strength: 119.1 bits
a 6-digit code has only 19.9 bits: rate-limit it
The token values are never printed: they differ on every run, which is the point. Their length is what you check.
How misuse is detected
- Grep the code for
import randomnear words liketoken,password,session,nonce,key; for==on values named*sig*,*tag*,*mac*,*token*; formd5(/sha1(used on passwords. Static analysers (Bandit's B311 forrandom, B303/B324 for weak hashes) flag many of these. - Look at the data: tokens that are short, sequential, time-based or share a prefix point to a weak generator.
- Review the protocol: if a "signature" is a plain hash of the message, anyone can forge it.
How it is fixed
- Integrity against attackers needs a key: HMAC (or a digital signature), never a bare hash.
- Compare secrets with
hmac.compare_digest, both sides of the same type (bothstror bothbytes). - Use
secrets(token_bytes,token_urlsafe,choice) for anything an attacker must not predict; 128 bits or more for tokens. - Passwords need slow, salted hashes (Argon2id, scrypt, bcrypt, PBKDF2), not SHA-256. In the browser's Python use
cryptography'sScryptorPBKDF2HMAC, becausehashlib.scryptandhashlib.pbkdf2_hmacare missing in Pyodide. - Avoid MD5 and SHA-1 for anything security-relevant; they are fine only as non-security checksums or lookup keys.
Pitfalls
hash(x)is Python's built-in hash for dictionaries: not cryptographic, and forstrandbytessalted per process (PYTHONHASHSEED), so it is not even stable between runs.- Length-extension.
sha256(key + message)as a MAC is broken for SHA-2 (an attacker can append data); HMAC's construction exists to prevent this. - Hex versus bytes.
hexdigest()is twice as long asdigest(); comparing one to the other is alwaysFalse. - Seeding for tests. A fixed key in an example is fine; a fixed key in production is a leaked key.
Practice
1. A download page publishes file.tar.gz and its SHA-256 on the same server. What does checking the hash protect against, and what not?
It detects accidental corruption and a modified mirror, if the hash comes from elsewhere. It does not protect against an attacker who controls the server: they replace both. A signature (GPG, Sigstore) with a key you trust does.
2. How many bits does secrets.token_urlsafe(16) carry, and how long is the string?
16 bytes = 128 bits. Base64url without padding uses 4 characters per 3 bytes: 16 bytes give 22 characters.
3. Change verify so it accepts the tag as raw bytes from a header given in hex. What can go wrong?
Decode with bytes.fromhex(tag) inside a try (invalid hex raises ValueError: treat it as a failed check), compute hmac.new(...).digest() and compare bytes with bytes. Comparing the hex string with the raw digest would always fail.
Test yourself
Why can't a plain SHA-256 of a message prove it was not changed by an attacker?
- SHA-256 is broken
- Anyone can recompute the hash of the modified message; there is no key
- Hashes are too short
- SHA-256 only works on files
What does the naive comparison leak in the example?
- The key
- How many leading characters of the guess are correct, through the work it does
- Nothing
- The message
Which call makes a session token?
random.getrandbits(128)secrets.token_urlsafe(32)hash(user)hashlib.md5(user.encode())
In the browser's Python (Pyodide), which is the right way to derive a key from a password?
hashlib.pbkdf2_hmachashlib.sha256(password)cryptography'sScryptorPBKDF2HMAChmac.new(password)