WeCodeAcademy

HMAC: Proving a Message Is Genuine

A plain hash lets anyone recompute a digest, so an attacker who changes a message can just hash the new version. An HMAC (hash-based message authentication code) mixes a secret key into the hash. Only someone with the key can produce the right code, so a matching HMAC proves the message came from a key holder and was not altered.

APIs use this to sign webhook messages and cookies. Always compare codes with hmac.compare_digest.

Examplepython
Open in editor »
Quick check

What does an HMAC need that a plain hash does not?

Your turn: write the code

Sign the message 'order:42' with the key b'k3y' using HMAC-SHA256 and print the first 16 hex characters of the tag.

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.