Lesson 11 of 15
HMAC — Keyed Hash
HMAC — Hash-based Message Authentication Code
A bare hash does not authenticate who sent — anyone can compute it. A MAC (Message Authentication Code) requires knowing a secret key to produce the authentication tag.
Naive Approach and Its Flaw
The simplest idea: (concatenate key and message). This is vulnerable to a length-extension attack for hash functions like SHA-1 and SHA-2: given , an attacker can compute without knowing .
HMAC Construction
The HMAC standard (RFC 2104) avoids length extension by applying the key twice:
where ipad = 0x36 repeated and opad = 0x5C repeated.
Our Simplified HMAC
We implement a simplified version using DJB2:
Wrapping the message with the key on both sides (like HMAC's double-key structure) prevents simple concatenation attacks.
Properties of MACs
- Unforgeability — without the key, an attacker cannot produce a valid MAC
- Verification — recompute MAC and compare; use constant-time comparison in production
- Different keys → different MACs for the same message
Your Task
Implement:
djb2_hash(s)— DJB2 hash (hash=5381, hash = hash*33 XOR ord(c), return hash & 0xFFFFFFFF)hmac_simple(message, key)— returnsdjb2_hash(key + message + key) & 0xFFFFFFFF
Python runtime loading...
Loading...
Click "Run" to execute your code.