An HMAC is a keyed message-authentication construction that combines a secret key with a cryptographic hash function. It lets a receiver detect changes to data and check that the creator knew the shared secret. A plain hash detects accidental corruption, but an attacker can replace both the data and its hash; an attacker cannot normally forge a matching HMAC without the key. section 4.5.1 section 4.7
Protecting a refunds file
A warehouse application creates refunds.json and an HMAC-SHA-256 value. The payments service recomputes the HMAC over the received file and compares it with the supplied value before parsing or processing refunds. If the file changes, or the value is missing or incorrect, the service rejects the file and processes no refunds. Matching values show that the file was not altered and that its creator knew the shared secret. section 4.6
Use HMAC with these practical boundaries in mind:
- Choose a secure hash such as SHA-256; HMAC supports SHA-2, SHA-3, and other hash functions. HMAC-SHA-256 produces 256 bits of output. section 4.5.1
- Do not replace HMAC with SHA256(message + secret). HMAC uses a deliberately designed key-mixing algorithm rather than simple concatenation. section 4.5.1
- Protect the shared key as carefully as a password. A 256-bit key is a reasonable SHA-256 default, while plain-text configuration and hardcoded keys risk theft. section 4.5.2 section 4.7
- HMAC provides integrity and authentication, not confidentiality or non-repudiation. Use authenticated encryption when encrypted data also needs tamper protection. section 5.2.2
Listing 4.5 Computing an HMAC using SHA-256 in Java
public static byte[] hmacSha256(byte[] key, byte[] data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data);
}
A small Java implementation shows the standard Mac API, algorithm name, key initialization, and final HMAC computation. section 4.5.2
HMAC uses a symmetric shared secret: both parties can generate and verify values, so it cannot prove which party created one or provide non-repudiation. RSA digital signatures use separate private and public keys, allowing broad verification and proof of authorship, but HMAC is faster for checks between trusted parties. section 6.5



