Distinguish Hash Digests from HMAC Authentication
Core idea
A cryptographic digest summarizes bytes without a secret key. Compare a digest to a trusted expected value to detect modification. HMAC uses a shared secret key and message to authenticate integrity to parties holding the key. Use hmac.compare_digest for tag comparison. HMAC does not encrypt data, establish unique sender identity among key holders or prevent replay by itself.
from hashlib import sha256original = b'count=4'expected = sha256(original).digest()print(sha256(original).digest() == expected)print(sha256(b'count=5').digest() == expected)The known original digest detects the fixture change; an attacker able to replace both data and digest defeats this check.
Expected output:
TrueFalseVerify a message tag
import hmackey = b'lesson-only-key'message = b'count=4'tag = hmac.digest(key, message, 'sha256')def verify(data, received): expected = hmac.digest(key, data, 'sha256') return hmac.compare_digest(expected, received)print(verify(message, tag))print(verify(b'count=5', tag))The tag matches the original bytes under the demonstration key. The hardcoded key is for teaching only.
Expected output:
TrueFalseCommon mistake
Do not use a plain SHA-256 digest as password storage; use an appropriate password hashing scheme with salt and work factor. In real HMAC use, manage strong secret keys and define freshness/replay policy.
Practice
Verify a known message and reject a modified one with the same tag. Explain why an unchanged valid message could still be replayed and why key rotation needs a policy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Hashing and HMAC
Check your understanding of hashing and hmac.
What is printed?
import hmacprint(hmac.compare_digest(b"abc", b"abc"))What is printed?
import hmacprint(len(hmac.digest(b"demo", b"x", "sha256")))What does HMAC require that a plain digest does not?
Does HMAC provide confidentiality?