liveBook · Manning

HMAC

As explained in Real-World Cryptography

HMAC is a standardized keyed-hash message authentication code constructed from a cryptographic hash function and a secret key.

HMAC is a keyed message authentication code built from a cryptographic hash function. A sender and receiver share a secret key; the sender computes an authentication tag from the key and message, and the receiver recomputes it to detect tampering. HMAC protects integrity and authenticity, not message confidentiality. section 3.2 section 3.7

Use HMAC as a short verification protocol:

  • Share the same secret key between the communicating parties. section 3.2
  • Compute an HMAC tag over the message with the shared key. section 3.2
  • Send the message and tag; recompute the tag on receipt and compare the values in constant time. section 3.2 section 3.7
  • Add separate replay protection when older valid messages must be rejected. section 3.2

HMAC works with different hash functions and is commonly paired with SHA-2. Do not build a MAC by hashing a secret directly with SHA-256: Merkle–Damgård length-extension attacks can let an attacker extend or tamper with the authenticated input. Use HMAC with SHA-2, or KMAC with SHA-3. section 3.6 section 3.7

Authenticated messages in Rust

A sender initializes HMAC with SHA-256, updates it with the message, and returns the finalized tag. The receiver performs the same computation and verifies the supplied tag. The example uses the Rust hmac and sha2 libraries. section 3.2

Listing 3.1 Sending an authenticated message in Rust
use sha2::Sha256;
use hmac::{Hmac, Mac, NewMac};
 
fn send_message(key: &[u8], message: &[u8]) -> Vec<u8> {
    let mut mac = Hmac::<Sha256>::new(key.into());          #1
 
    mac.update(message);                                    #2
 
    mac.finalize().into_bytes().to_vec()                    #3
}

Inspect the paired Rust listings to see HMAC tag generation and verification as a minimal implementation workflow. section 3.2

How Real-World Cryptography covers it

How deep it goes
Explains keyed tag generation, verification, replay limits, length-extension risks, and constant-time comparison without detailing HMAC internals.
Examples
Demonstrates Rust sender and receiver functions using HMAC-SHA-256, message tags, and verification.
What it assumes
Assumes shared-key communication and hash functions, while introducing MAC purpose, tag verification, and replay limitations.
What you can do after
Apply it via Rust to authenticate messages, verify tags safely, and avoid direct SHA-256 MAC constructions.
How it connects
Connects HMAC with message authentication codes, cryptographic hash functions, SHA-2, SHA-3, KMAC, HKDF, and replay protection.

Also explained in

Compare how 4 books explain HMAC →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Real-World Cryptography. The section links point to the parts of the book it draws on.