Show contents
Chapter 2 of 6 · 20 min
HMAC: preventing forgery
By the end of this chapter, you'll be able to
- Show that an unauthenticated ciphertext can be modified without knowing the key
- Compute an HMAC-SHA256 with the hmac module
- Check the signature of a notification with a constant-time comparison
- Explain why we encrypt and then authenticate the result
Encrypting is not enough: malleability
With a stream cipher, ciphertext = message ^ stream. If an attacker guesses the shape of the message (a transfer, a form), they can change a byte of the ciphertext: the same change will appear in the decrypted message. The cipher is said to be malleable.
import hashlib
def keystream(key, nonce, n):
s, i = b"", 0
while len(s) < n:
s += hashlib.sha256(key + nonce + i.to_bytes(8, "big")).digest()
i += 1
return s[:n]
def xor(a, b):
return bytes(x ^ y for x, y in zip(a, b))
key, nonce = b"key known only to the bank", b"n-17"
order = b"transfer 001000 F CFA to Kofi"
encrypted = xor(order, keystream(key, nonce, len(order)))
# The attacker does not know the key, but knows the format: the amount is at position 9.
# XOR with ("0" ^ "9") changes the digit "0" into "9" in the decrypted message.
modified = bytearray(encrypted)
modified[9] ^= ord("0") ^ ord("9")
print(xor(bytes(modified), keystream(key, nonce, len(order))).decode())
transfer 901000 F CFA to Kofi
Without the key, the attacker turned a transfer of 1,000 into 901,000 F CFA. Encryption hides the content, but does not guarantee integrity. Another building block is needed.
HMAC: a keyed fingerprint
A MAC (Message Authentication Code) is a fingerprint computed with a secret key. Only those who know the key can compute it; so a correct fingerprint proves that the message comes from one of them and has not been modified. HMAC is the standard construction built from a hash function such as SHA-256. Python provides it in the hmac module.
If the tags differ by a single bit, the notification is rejected.
Text description of the animation
- The payment service prepares the notification.
- It computes the tag with the secret key shared with your shop.
- The tag travels with the message, for example in an HTTP header.
- Your shop recomputes the tag on the received message, with its copy of the key.
- If the tags differ by a single bit, the notification is rejected.
import hashlib
import hmac
key = b"key-shared-with-the-payment-service"
def sign(message):
return hmac.new(key, message, hashlib.sha256).hexdigest()
def verify(message, tag):
return hmac.compare_digest(sign(message), tag)
notification = b'{"order": 1042, "status": "paid", "amount": 15000}'
tag = sign(notification)
print("tag:", tag[:24], "...")
print("genuine :", verify(notification, tag))
forged = notification.replace(b"15000", b"150")
print("forged :", verify(forged, tag))
made_up = b'{"order": 2077, "status": "paid", "amount": 90000}'
print("made up :", verify(made_up, hashlib.sha256(made_up).hexdigest())) # without the key
tag: 9e1926b496b04c9269cba916 ...
genuine : True
forged : False
made up : False
Without the key, it is impossible to compute the tag of a made-up or modified message. That is how payment services and platforms (Stripe, GitHub and many others) sign the notifications they send to their customers' sites.
Encrypt, then authenticate
To get confidentiality and integrity, we encrypt the message, then compute the HMAC over the ciphertext (and the nonce). On receipt, we check the tag before decrypting: a modified ciphertext is rejected without even being read. That is the encrypt-then-MAC principle. Authenticated modes such as AES-GCM do both in a single operation, with two internal keys.
Mini-lab: each key gives a different tagPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: sorting payment notifications
Your shop received four notifications. Write a function process(notifications, key) that displays ship order N for each genuine notification with the status paid, and REJECTED for the others (missing or wrong tag).
notifications = [
{"body": b'{"order": 1042, "status": "paid"}', "signature": "..."}, # genuine
{"body": b'{"order": 1043, "status": "paid"}', "signature": "..."}, # body changed after signing
{"body": b'{"order": 1044, "status": "paid"}', "signature": None}, # no signature
{"body": b'{"order": 1045, "status": "paid"}', "signature": "..."}, # genuine
]
Hint 1
hmac.new(key, body, hashlib.sha256).hexdigest(). For order 1043, sign another body (for example with order 1003).Hint 2
None) must be rejected before any computation: if not signature or not hmac.compare_digest(...). The json module reads the body: json.loads(body).Show the solution and common mistakes
import hashlib
import hmac
import json
key = b"key-shared-with-the-payment-service"
def sign(body):
return hmac.new(key, body, hashlib.sha256).hexdigest()
notifications = [
{"body": b'{"order": 1042, "status": "paid"}', "signature": sign(b'{"order": 1042, "status": "paid"}')},
{"body": b'{"order": 1043, "status": "paid"}', "signature": sign(b'{"order": 1003, "status": "paid"}')},
{"body": b'{"order": 1044, "status": "paid"}', "signature": None},
{"body": b'{"order": 1045, "status": "paid"}', "signature": sign(b'{"order": 1045, "status": "paid"}')},
]
def process(notifications, key):
for n in notifications:
expected = hmac.new(key, n["body"], hashlib.sha256).hexdigest()
if not n["signature"] or not hmac.compare_digest(expected, n["signature"]):
print("REJECTED")
continue
data = json.loads(n["body"]) # read the content only after checking
if data["status"] == "paid":
print("ship order", data["order"])
process(notifications, key)
ship order 1042
REJECTED
REJECTED
ship order 1045
The order matters: we check the signature on the exact bytes received, and only then read the JSON.
Common mistakes:
- Recomputing the HMAC on the JSON after reading and rewriting it (
json.dumps(json.loads(body))): spaces or key order change, and genuine signatures fail. - Accepting a notification without a signature "for testing" and forgetting to remove that exception in production.
- Putting the HMAC key in published source code: it must come from an environment variable or a secrets vault.
Summary
- 1Encryption without authentication is malleable: the message can be changed without knowing the key.
- 2An HMAC is a keyed fingerprint: only someone who knows the key can produce it.
- 3A tag is checked with hmac.compare_digest, never with ==.
- 4Encrypt, then authenticate the ciphertext, and check before decrypting; AES-GCM does both.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.