Lesson 2.13: HMAC and message authentication
A plain hash proves that data didn't change by accident, but anyone can compute one, so an attacker who changes a message can recompute its hash too. HMAC mixes a secret key into the hash: only someone with the key can make a valid tag. That's how payment providers sign webhooks, APIs sign requests and cookies are protected against tampering. In the lab you verify two 'payment succeeded' webhooks with openssl and the shared secret, catch one whose amount was changed, and write the check the way the shop's PHP code must do it, with hash_hmac and hash_equals.
17 min
You will learn to
- Explain why a plain hash doesn't prove authenticity
- Explain HMAC and message authentication codes
- Verify an HMAC with openssl dgst -hmac
- Verify one in PHP with hash_hmac and hash_equals
- Name defences against replayed messages
Key terms
- MAC
- Message Authentication Code: a short tag computed from a message and a secret key; it proves integrity and that the sender knew the key.
- HMAC
- A standard way to build a MAC from a hash function and a key (RFC 2104).
- Shared secret
- A key known to both sides of a communication and nobody else.
- Webhook
- An HTTP request a service sends to your server when something happens, such as a payment.
- Replay attack
- Sending a valid, captured message again to repeat its effect.
← Security headers · All lessons · Threat actors and their motives →