Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 80 ยท Cryptography Basics

HMAC and Message Authentication

Learn how HMAC detects tampering with a secret key, why you must compare tags in constant time, and how to build a small signed token with hmac and hashlib.

A plain hash can tell you that data changed, but it cannot tell you who made it. Anyone can hash anything. If a server sends you amount=10 together with its SHA-256 digest, an attacker in the middle can change the amount to amount=1000 and simply recompute the digest.

A message authentication code (MAC) fixes this by mixing a secret key into the computation. Only someone who knows the key can produce a valid tag, so a correct tag proves two things at once: the message was not modified (integrity) and it came from a holder of the key (authenticity). The most widely used MAC is HMAC, short for hash-based message authentication code. In this lesson you'll use Python's hmac module, learn why tag comparison must be constant-time, and build a small signed token from scratch. If hashes are new to you, read Hash Functions and Integrity first.

How HMAC works

HMAC wraps a hash function H such as SHA-256. Simplified, it computes:

HMAC(key, message) = H( (key XOR opad) || H( (key XOR ipad) || message ) )

The key is padded to the hash's block size, combined with two fixed constants (ipad and opad), and the hash is applied twice, once inside the other. You never write this by hand; the structure matters because of an attack you can avoid by using it.

You might be tempted to build your own MAC as SHA-256(key + message). Don't. Hashes like SHA-256 are built on the Merkle-Damgard construction, which allows a length-extension attack: from H(key || m) and the length of the key, an attacker can compute H(key || m || padding || extra) for any extra without ever learning the key. HMAC's double hashing closes that hole, and so does SHA-3 and BLAKE2 used in keyed mode. The practical rule is simple: use hmac, never hash(key + data).

sequenceDiagram
    participant A as Sender (has key K)
    participant B as Receiver (has key K)
    A->>A: tag = HMAC(K, message)
    A->>B: message + tag
    B->>B: expected = HMAC(K, message)
    B->>B: compare tag and expected
    Note over B: Match: authentic and unmodified<br/>Mismatch: reject

Both sides share the key. The receiver recomputes the tag and compares it with the one that arrived.

HMAC in Python

The hmac module takes a key (bytes), a message (bytes) and the name of a hash. Here a shop signs a payment instruction and the receiver verifies it, once with the genuine message and once with a tampered one:

Python Sign and verify with HMAC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that hmac.compare_digest is used for the comparison. The next section explains why.

Comparing tags in constant time

If you write if expected == tag:, Python compares the two strings from the left and stops at the first different character. A tag that matches 10 characters takes very slightly longer to reject than one that matches 2. By measuring thousands of responses, an attacker can discover the correct tag one character at a time. This is a timing attack, and it has broken real systems that used ordinary comparison for API signatures.

hmac.compare_digest(a, b) always examines every byte regardless of where the first difference is, so the time reveals nothing. Timing on a laptop is noisy, so this demo counts how many characters the naive comparison inspects. That count is exactly the signal an attacker would measure:

Python Why naive comparison leaks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The attacker needs only 16 guesses per position to recover the prefix, instead of trying every combination. This is why the rule is absolute: compare secrets, tags and tokens with hmac.compare_digest (or secrets.compare_digest), never with ==.

Pitfalls when signing structured data

HMAC protects exactly the bytes you give it. Problems appear when the bytes are built carelessly. A classic bug is joining fields without a clear separator, so two different records produce the same byte string:

Python Ambiguous concatenation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Other common mistakes: signing only part of a request (an attacker changes the unsigned part), forgetting to bind an expiry time or a purpose to the tag (so a tag meant for one use can be replayed elsewhere), and using the same key for several different purposes. Add a context string such as b"password-reset|" to the signed data to separate purposes.

Building a signed token from scratch

A tag is only useful if it travels with the data. A tiny, self-contained token format has three parts: a payload, an expiry and the tag. This is the same idea as signed cookies and the signature part of a JWT, which you will meet in Sessions, Cookies and JWTs.

Python A signed token with expiry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The receiver never decodes the payload before checking the signature, and it checks the expiry after. Notice that the payload is only encoded, not encrypted: anyone holding the token can read role and user. A MAC gives integrity and authenticity, not secrecy. For secrecy you add encryption, covered in Symmetric Encryption and Modes.

Choosing keys and algorithms

  • Key length: use at least 32 random bytes for HMAC-SHA-256 (see Randomness, Key Management and Secrets). A short human-memorable string is a weak key.
  • Hash: HMAC-SHA-256 is a solid default. HMAC-SHA-1 is still considered safe as a MAC, but there is no reason to choose it for new designs.
  • Truncation: you may shorten a tag, but keep at least 128 bits for strong guarantees.
  • Key sharing: HMAC is symmetric. Everyone who can verify can also forge. If a third party must verify without being able to sign, you need a digital signature, which uses a key pair.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does HMAC provide that a plain SHA-256 hash does not?

    A key is mixed into the computation, so only holders of the key can create a valid tag. HMAC does not hide the message and does not stop replays unless you include a nonce or expiry.
  2. 2. Why should you use hmac.compare_digest instead of == for tags?

    An ordinary comparison stops at the first mismatch, so response time leaks how many leading characters were right. A constant-time comparison removes that signal.
  3. 3. What is wrong with using sha256(key + message) as a MAC?

    SHA-256 is a Merkle-Damgard hash, so given H(key + m) an attacker can compute the hash of an extended message without the key. HMAC's nested construction prevents this.
  4. 4. In the signed-token demo, what must the receiver do first?

    Nothing in the payload can be trusted until the signature has been verified, because an attacker controls those bytes.

Summary

  • A MAC adds a secret key to hashing, giving both integrity and authenticity.
  • Use hmac.new(key, msg, hashlib.sha256), never hash(key + msg), which allows length extension.
  • Compare tags with hmac.compare_digest to avoid timing leaks.
  • Sign unambiguous bytes (such as canonical JSON), and bind expiry, purpose and context into what you sign.
  • A MAC does not encrypt: the payload stays readable. It is also symmetric, so every verifier can forge.
  • Verify the tag before parsing or trusting any field of the data.

Next: Symmetric Encryption and Modes, where you'll learn how to keep data secret as well as authentic.