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



