Back
+20 XP
Concept

Message Authentication Codes: HMAC-SHA256

A plain hash only detects accidental corruption, not malicious tampering (an attacker modifies the payload and computes a new hash). An HMAC binds a secret key into the hash computation, ensuring payloads cannot be altered or forged in transit 🛡️🔑.

python
import hmac
import hashlib

secret_key = b"enterprise_api_secret_key"
payload = b"action=grant_admin&uid=42"

# Sign payload with HMAC-SHA256:
signature = hmac.new(secret_key, payload, hashlib.sha256).hexdigest()

# Recipient verifies authenticity:
recomputed = hmac.new(secret_key, payload, hashlib.sha256).hexdigest()
is_authentic = hmac.compare_digest(signature, recomputed)

print(f"Signature Valid: {is_authentic} 🚀")

# 65. Message Authentication Codes: HMAC-SHA256 If you transmit webhooks, session cookies, or distributed RPC commands over HTTP with only a raw SHA-256 checksum, a Man-In-The-Middle (MITM) proxy can intercept the request, change `role=guest` to `role=admin`, recompute `sha256(tampered_body)`, and forward it to your server 🛑. ```python # Raw Checksum (Easily Forged by Attacker): # Payload: {"role": "guest"} -> SHA256 = 1a2b... # Attacker intercepts: {"role": "admin"} -> SHA256 = 9f8e... (Valid checksum!) # HMAC Authentication (Impossible to Forge without Secret): # Payload: {"role": "admin"} -> HMAC(secret, body) -> Attacker doesn't know secret! ``` ### The HMAC Construction (RFC 2104) HMAC does not simply concatenate `hash(key + message)`. Simple concatenation is vulnerable to length-extension attacks. Instead, HMAC applies nested hashing with inner and outer padding constants: $$\text{HMAC}(K, m) = H\Big((K \oplus \text{opad}) \parallel H\big((K \oplus \text{ipad}) \parallel m\big)\Big)$$ 1. **Inner Hash**: The key is XORed with `ipad` (`0x36`) and prepended to the message. 2. **Outer Hash**: The inner result is hashed again with the key XORed with `opad` (`0x5c`). 3. **Provable Security**: Cryptographic proofs demonstrate that as long as the underlying hash compression function is sound, forging an HMAC without the secret key is mathematically impossible 🛡️🔑. --- ### Interactive Pop-Quiz 🧠 #### Why can an attacker not forge a valid HMAC signature for a tampered message even if they know the hash algorithm is SHA-256? - [ ] Because generating a valid HMAC requires possession of the confidential shared secret key 🛡️ - [ ] Because SHA-256 automatically sends an SMS alert to system administrators - [ ] Because HMAC packets can only travel over physical fiber optic cables - [ ] Because the operating system kernel blocks all forged IP addresses --- ### Practical Challenge 🎯 Implement `sign_payload(secret, payload)` and `verify_payload(secret, payload, signature)` using `hmac.new` with `hashlib.sha256` and `hmac.compare_digest`. Sign `b'ORDER_ID_1001'`. Verify the signature matches, then verify that changing the payload to `b'ORDER_ID_1002'` returns `False`. Print `'HMAC_VERIFIED'`. <details> <summary>Solution</summary> ```python import hmac import hashlib def sign_payload(secret, payload): return hmac.new(secret, payload, hashlib.sha256).hexdigest() def verify_payload(secret, payload, signature): expected = hmac.new(secret, payload, hashlib.sha256).hexdigest() return hmac.compare_digest(signature, expected) key = b"MY_SECRET_KEY" msg = b"ORDER_ID_1001" sig = sign_payload(key, msg) assert verify_payload(key, msg, sig) is True assert verify_payload(key, b"ORDER_ID_1002", sig) is False print("HMAC_VERIFIED") ``` </details>

Checkpoint

Why can an attacker not forge a valid HMAC signature for a tampered message even if they know the hash algorithm is SHA-256? 🧠

Practice

Implement `sign_payload(secret, payload)` and `verify_payload(secret, payload, signature)` using `hmac.new` with `hashlib.sha256` and `hmac.compare_digest`. Sign `b'ORDER_ID_1001'`. Verify the signature matches, then verify that changing the payload to `b'ORDER_ID_1002'` returns `False`. Print `'HMAC_VERIFIED'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks