HMAC in Java: Message Authentication Codes with HmacSHA256
An HMAC is a hash mixed with a secret key. Anyone can compute a plain SHA-256, but only someone with the key can compute the right HMAC, so a matching tag proves that the message is unchanged and came from a key holder. Java computes HMACs with javax.crypto.Mac.
Contents
How HMAC works
A message authentication code (MAC) is a short tag computed from a message and a secret key. Anyone holding the key can compute the tag for a message and check a tag they receive; without the key, an attacker cannot produce a valid tag for any message they have not seen tagged. HMAC (RFC 2104, 1997) builds a MAC from an ordinary hash function such as SHA-256:
HMAC(K, m) = H((K' xor opad) || H((K' xor ipad) || m))
Here K'ipadopadSHA-256(key + message)
| SHA-256 | HMAC-SHA256 | |
|---|---|---|
| Inputs | Message | Message and secret key |
| Who can compute it | Anyone | Only key holders |
| Proves the message is unchanged | Only if the hash comes from a trusted channel | Yes |
| Proves who sent it | No | A holder of the shared key |
In Java, HMAC is a javax.crypto.MacHmacSHA256SecretKey
HMAC built by hand
To see that the formula above is all there is, the program implements HMAC-SHA256 with MessageDigestMac
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class HmacByHand {
static final int BLOCK = 64; // SHA-256 processes 64-byte blocks
// RFC 2104: H((K xor opad) || H((K xor ipad) || message))
static byte[] hmacSha256(byte[] key, byte[] message) throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
if (key.length > BLOCK) {
key = sha.digest(key); // long keys are hashed first
}
byte[] k = Arrays.copyOf(key, BLOCK); // then padded with zeros
byte[] ipad = new byte[BLOCK];
byte[] opad = new byte[BLOCK];
for (int i = 0; i < BLOCK; i++) {
ipad[i] = (byte) (k[i] ^ 0x36);
opad[i] = (byte) (k[i] ^ 0x5c);
}
sha.update(ipad);
byte[] inner = sha.digest(message);
sha.update(opad);
return sha.digest(inner);
}
static byte[] mac(byte[] key, byte[] message) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(message);
}
public static void main(String[] args) throws Exception {
HexFormat hex = HexFormat.of();
byte[] msg = "what do ya want for nothing?".getBytes(StandardCharsets.US_ASCII);
byte[] key = "Jefe".getBytes(StandardCharsets.US_ASCII);
System.out.println("by hand: " + hex.formatHex(hmacSha256(key, msg)));
System.out.println("Mac: " + hex.formatHex(mac(key, msg)));
// A key longer than the block size is replaced by its hash
byte[] longKey = new byte[100];
Arrays.fill(longKey, (byte) 0xaa);
byte[] hashedKey = MessageDigest.getInstance("SHA-256").digest(longKey);
System.out.println("100-byte key and its SHA-256 give the same tag: "
+ MessageDigest.isEqual(mac(longKey, msg), mac(hashedKey, msg)));
// Short keys are zero-padded, so trailing zero bytes do not change the tag
System.out.println("key \"Jefe\" and \"Jefe\\0\" give the same tag: "
+ MessageDigest.isEqual(mac(key, msg), mac(Arrays.copyOf(key, 5), msg)));
// Why not SHA-256(key + message)? It is a different (and extendable) value
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(key);
System.out.println("SHA-256(key + message) equals the HMAC: "
+ MessageDigest.isEqual(sha.digest(msg), mac(key, msg)));
}
}
Output:
by hand: 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
Mac: 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
100-byte key and its SHA-256 give the same tag: true
key "Jefe" and "Jefe\0" give the same tag: true
SHA-256(key + message) equals the HMAC: false
- The hand-written version and
produced the same 32-byte tag, which is also the value published in RFC 4231.Mac - A 100-byte key is longer than the 64-byte block, so it is replaced by its SHA-256 hash: the long key and its hash gave identical tags. Keys longer than the block add nothing, so 32 to 64 random bytes is the useful range.
- Short keys are padded with zero bytes, so "Jefe" and "Jefe" followed by a zero byte are the same key. That is harmless for random keys, but a reason never to build keys from strings with variable endings.
is a different value from the HMAC, and unlike the HMAC it is open to length extension.SHA-256(key + message)
Computing and checking an HMAC
A plain hash detects changes only if the attacker cannot replace the hash too; a keyed tag can only be replaced by someone with the key. The program first reproduces test case 2 from RFC 4231, which publishes expected HMAC-SHA256 values, to confirm the code computes the standard algorithm. It then signs an order with a random key and checks three receivers: one that gets the message unchanged, one that gets a changed amount, and one that uses the wrong key.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class HmacBasics {
static byte[] hmac(byte[] key, String message) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
}
public static void main(String[] args) throws Exception {
// RFC 4231, test case 2: key "Jefe"
byte[] jefe = "Jefe".getBytes(StandardCharsets.UTF_8);
String rfc = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843";
String tag = HexFormat.of().formatHex(hmac(jefe, "what do ya want for nothing?"));
System.out.println("HMAC-SHA256 = " + tag);
System.out.println("matches RFC 4231 test case 2: " + tag.equals(rfc));
// A real key: random, 256 bits, from KeyGenerator
SecretKey key = KeyGenerator.getInstance("HmacSHA256").generateKey();
System.out.println("generated key length: " + key.getEncoded().length * 8 + " bits");
String order = "{\"orderId\":42,\"amount\":1999}";
byte[] good = hmac(key.getEncoded(), order);
// The receiver recomputes the tag and compares in constant time
byte[] received = hmac(key.getEncoded(), order);
System.out.println("untouched message verifies: " + MessageDigest.isEqual(good, received));
byte[] tampered = hmac(key.getEncoded(), order.replace("1999", "1"));
System.out.println("changed amount verifies: " + MessageDigest.isEqual(good, tampered));
byte[] otherKey = KeyGenerator.getInstance("HmacSHA256").generateKey().getEncoded();
System.out.println("tag made with another key: "
+ MessageDigest.isEqual(good, hmac(otherKey, order)));
}
}
Output (the generated key is random, the rest is the same on every run):
HMAC-SHA256 = 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
matches RFC 4231 test case 2: true
generated key length: 256 bits
untouched message verifies: true
changed amount verifies: false
tag made with another key: false
- The tag matches the RFC value exactly.
- The receiver does not "decrypt" anything: it recomputes the HMAC over the message it received and compares. Changing 1999 to 1 or using a different key gives a different tag.
- The key should be random and at least as long as the hash output, 256 bits for HMAC-SHA256.
produces such a key. "Jefe" in the test vector is a deliberately weak key from the RFC, not an example to copy.KeyGenerator compares in constant time. A comparison that stops at the first wrong byte lets an attacker measure how many leading bytes of a forged tag are right and guess the tag byte by byte.MessageDigest.isEqual
Keys, streaming and the Mac API
The MacMessageDigest
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;
import java.util.HexFormat;
import java.util.TreeSet;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class MacApi {
public static void main(String[] args) throws Exception {
TreeSet<String> hmacs = new TreeSet<>();
for (String a : Security.getAlgorithms("Mac")) {
if (a.startsWith("HMAC")) {
hmacs.add(a);
}
}
System.out.println("HMAC algorithms: " + hmacs);
// Generated keys have the size of the hash output by default
for (String alg : new String[] {"HmacSHA256", "HmacSHA512"}) {
SecretKey k = KeyGenerator.getInstance(alg).generateKey();
System.out.println(alg + ": generated key " + k.getEncoded().length * 8 + " bits, tag "
+ Mac.getInstance(alg).getMacLength() * 8 + " bits");
}
// A key stored in configuration as Base64 (here a fixed example value)
String fromConfig = "q83vASNFZ4mrze8BI0VniavN7wEjRWeJq83vASNFZ4k=";
SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(fromConfig),
"HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
// update() several times, then doFinal(); the Mac is ready for the next message
mac.update("part one, ".getBytes(StandardCharsets.UTF_8));
mac.update("part two".getBytes(StandardCharsets.UTF_8));
byte[] streamed = mac.doFinal();
byte[] oneShot = mac.doFinal("part one, part two".getBytes(StandardCharsets.UTF_8));
System.out.println("streamed equals one-shot, Mac reused after doFinal: "
+ Arrays.equals(streamed, oneShot));
// Truncating a tag is allowed (RFC 2104), at the cost of forgery resistance
byte[] truncated = Arrays.copyOf(oneShot, 16);
System.out.println("full tag: " + HexFormat.of().formatHex(oneShot));
System.out.println("128-bit tag: " + HexFormat.of().formatHex(truncated));
System.out.println("URL-safe Base64 of full tag: "
+ Base64.getUrlEncoder().withoutPadding().encodeToString(oneShot));
// An empty key is rejected; a Mac without init() cannot be used
try {
new SecretKeySpec(new byte[0], "HmacSHA256");
} catch (IllegalArgumentException e) {
System.out.println("empty key: " + e.getMessage());
}
try {
Mac.getInstance("HmacSHA256").doFinal(new byte[1]);
} catch (IllegalStateException e) {
System.out.println("no init(): " + e.getMessage());
}
}
}
Output:
HMAC algorithms: [HMACMD5, HMACPBESHA1, HMACPBESHA224, HMACPBESHA256, HMACPBESHA384, HMACPBESHA512, HMACPBESHA512/224, HMACPBESHA512/256, HMACSHA1, HMACSHA224, HMACSHA256, HMACSHA3-224, HMACSHA3-256, HMACSHA3-384, HMACSHA3-512, HMACSHA384, HMACSHA512, HMACSHA512/224, HMACSHA512/256]
HmacSHA256: generated key 256 bits, tag 256 bits
HmacSHA512: generated key 512 bits, tag 512 bits
streamed equals one-shot, Mac reused after doFinal: true
full tag: 376f2cc8c58856f55a762e52af073c4489b22cbe9209619d4703ea8575f30314
128-bit tag: 376f2cc8c58856f55a762e52af073c44
URL-safe Base64 of full tag: N28syMWIVvVadi5Srwc8RImyLL6SCWGdRwPqhXXzAxQ
empty key: Empty key
no init(): MAC not initialized
reports names in upper case; algorithm names are not case-sensitive. TheSecurity.getAlgorithms("Mac") entries derive their key from a password and are rarely what you want.HMACPBE... made a 256-bit key for HmacSHA256 and a 512-bit key for HmacSHA512, matching their tag sizes. Store such keys as Base64, as the configuration value here, and decode them into aKeyGenerator .SecretKeySpec- Calling
twice and thenupdate gave the same tag as onedoFinal() over the whole text, and thedoFinal was reusable straight away:Mac resets it but keeps the key.doFinal - A tag may be truncated, here to 128 bits, as some protocols do to save space; forging it is then a 2128 problem instead of 2256, still far out of reach. URL-safe Base64 without padding is the usual form in HTTP headers and JWTs.
- An empty key is rejected by
, and aSecretKeySpec used beforeMac throwsinit .IllegalStateException
Why the comparison must take constant time
A receiver that compares the expected tag with the received one byte by byte, stopping at the first difference, answers faster the earlier the difference is. An attacker who can time many requests can then find a valid tag one byte at a time. The program times a naive loop and MessageDigest.isEqual
import java.security.MessageDigest;
import java.util.Arrays;
public class TimingLeak {
// The naive comparison: returns at the first byte that differs
static boolean naiveEquals(byte[] a, byte[] b) {
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
interface Compare {
boolean test(byte[] a, byte[] b);
}
static long nanosPerCall(Compare c, byte[] a, byte[] b) {
long best = Long.MAX_VALUE;
int sink = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
for (int i = 0; i < 200000; i++) {
if (c.test(a, b)) {
sink++;
}
}
long t = System.nanoTime() - t0;
best = Math.min(best, t);
}
return sink == -1 ? 0 : best / 200000;
}
public static void main(String[] args) {
// Long arrays make the effect visible; with 32-byte tags it is smaller but real
byte[] secret = new byte[4096];
Arrays.fill(secret, (byte) 7);
byte[] wrongFirst = secret.clone();
wrongFirst[0] = 0;
byte[] wrongLast = secret.clone();
wrongLast[4095] = 0;
// Rounds alternate between the four cases, so none benefits from running later
String[] labels = {"naive loop, differs at byte 0: ",
"naive loop, differs at byte 4095:",
"MessageDigest.isEqual, byte 0: ", "MessageDigest.isEqual, byte 4095:"};
Compare naive = TimingLeak::naiveEquals;
Compare constant = MessageDigest::isEqual;
Compare[] how = {naive, naive, constant, constant};
byte[][] other = {wrongFirst, wrongLast, wrongFirst, wrongLast};
long[] best = {Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE};
for (int round = 0; round < 6; round++) {
for (int i = 0; i < 4; i++) {
long t = nanosPerCall(how[i], secret, other[i]);
if (round >= 1) {
best[i] = Math.min(best[i], t);
}
}
}
System.out.println("4,096-byte values, ns per comparison:");
for (int i = 0; i < 4; i++) {
System.out.printf(" %s %5d%n", labels[i], best[i]);
}
}
}
Output of the comparison timing run:
4,096-byte values, ns per comparison:
naive loop, differs at byte 0: 1
naive loop, differs at byte 4095: 797
MessageDigest.isEqual, byte 0: 3374
MessageDigest.isEqual, byte 4095: 3403
- The naive loop returned almost at once when byte 0 differed, and took hundreds of times longer when only the last byte did. The running time reveals where the first wrong byte is.
took about the same time in both cases, because it always looks at every byte. That is its documented purpose since Java 6u17, and it is the method to use for tags, tokens and password hashes.MessageDigest.isEqual- With 32-byte tags over a network the difference per request is tiny, but attacks that average many measurements have recovered such secrets in practice.
also stops early, so it is not a safe replacement.Arrays.equals
Signing webhooks and API requests
Payment providers and other APIs sign the webhooks they send with an HMAC, using a secret shared with the receiver. Signing the body alone has a weakness: someone who captures a genuine request can send it again later. The usual fix is to sign the timestamp together with the body and reject requests outside a time window.
The program signs timestamp.body
- the genuine one;
- one with a changed body;
- one with a changed timestamp;
- the genuine request replayed an hour later.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class WebhookSigning {
static final byte[] SHARED_SECRET = "demo-secret-from-config-not-source-code"
.getBytes(StandardCharsets.UTF_8);
static final Duration TOLERANCE = Duration.ofMinutes(5);
// Sign "timestamp.body" so an old signature cannot be reused with a new time
static String sign(long timestamp, String body) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SHARED_SECRET, "HmacSHA256"));
byte[] tag = mac.doFinal((timestamp + "." + body).getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(tag);
}
static String verify(long timestamp, String body, String signature, Instant now)
throws Exception {
if (Duration.between(Instant.ofEpochSecond(timestamp), now).abs()
.compareTo(TOLERANCE) > 0) {
return "rejected: timestamp outside 5 minutes (possible replay)";
}
byte[] expected = sign(timestamp, body).getBytes(StandardCharsets.US_ASCII);
byte[] actual = signature.getBytes(StandardCharsets.US_ASCII);
return MessageDigest.isEqual(expected, actual) ? "accepted" : "rejected: bad signature";
}
public static void main(String[] args) throws Exception {
Instant now = Instant.parse("2026-01-15T12:00:00Z");
long ts = now.getEpochSecond();
String body = "{\"event\":\"payment.succeeded\",\"amount\":1999}";
String sig = sign(ts, body);
System.out.println("header: X-Signature: t=" + ts + ", v1=" + sig);
System.out.println("genuine request: " + verify(ts, body, sig, now));
System.out.println("body changed: "
+ verify(ts, body.replace("1999", "9999"), sig, now));
System.out.println("timestamp changed: " + verify(ts + 60, body, sig, now));
System.out.println("same request 1 h later: "
+ verify(ts, body, sig, now.plus(Duration.ofHours(1))));
}
}
Output:
header: X-Signature: t=1768478400, v1=DQmQ3tZsjGO7XKE/uet+p3H2w3XCXDLWcdSppFB1J6k=
genuine request: accepted
body changed: rejected: bad signature
timestamp changed: rejected: bad signature
same request 1 h later: rejected: timestamp outside 5 minutes (possible replay)
Changing the body or the timestamp breaks the signature, because both are inside the signed text. The replayed request still has a valid signature but fails the 5-minute window. Verify the signature over the raw request body exactly as received; parsing and re-serializing the JSON first can change spacing or key order and break a genuine signature.
The secret is a constant here to keep the demo self-contained. In real code, load it from a secret store or environment variable, never from source code.
Deriving keys with HMAC: HKDF
HMAC is also the building block of HKDF (RFC 5869), the standard way to turn one secret, such as the result of a key exchange, into several independent keys. HKDF has two steps: extract computes PRK = HMAC(salt, secret)infoMac
import java.io.ByteArrayOutputStream;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
// HKDF (RFC 5869) built from HMAC-SHA256: one secret in, several independent keys out
public class Hkdf {
static byte[] hmac(byte[] key, byte[] data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data);
}
static byte[] extract(byte[] salt, byte[] inputKey) throws Exception {
return hmac(salt, inputKey); // PRK = HMAC(salt, IKM)
}
static byte[] expand(byte[] prk, byte[] info, int length) throws Exception {
ByteArrayOutputStream okm = new ByteArrayOutputStream();
byte[] t = new byte[0];
for (int i = 1; okm.size() < length; i++) { // T(i) = HMAC(PRK, T(i-1)|info|i)
byte[] block = new byte[t.length + info.length + 1];
System.arraycopy(t, 0, block, 0, t.length);
System.arraycopy(info, 0, block, t.length, info.length);
block[block.length - 1] = (byte) i;
t = hmac(prk, block);
okm.write(t);
}
byte[] out = new byte[length];
System.arraycopy(okm.toByteArray(), 0, out, 0, length);
return out;
}
public static void main(String[] args) throws Exception {
HexFormat hex = HexFormat.of();
// RFC 5869, test case 1
byte[] ikm = hex.parseHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
byte[] salt = hex.parseHex("000102030405060708090a0b0c");
byte[] info = hex.parseHex("f0f1f2f3f4f5f6f7f8f9");
String expected = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf"
+ "34007208d5b887185865";
byte[] okm = expand(extract(salt, ikm), info, 42);
System.out.println("OKM: " + hex.formatHex(okm));
System.out.println("matches RFC 5869 test case 1: " + hex.formatHex(okm).equals(expected));
// Different "info" labels give unrelated keys from the same secret
byte[] prk = extract(salt, ikm);
System.out.println("encryption key: " + hex.formatHex(expand(prk,
"enc".getBytes(java.nio.charset.StandardCharsets.UTF_8), 16)));
System.out.println("MAC key: " + hex.formatHex(expand(prk,
"mac".getBytes(java.nio.charset.StandardCharsets.UTF_8), 16)));
}
}
Output:
OKM: 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
matches RFC 5869 test case 1: true
encryption key: 82db9b38f2dcbf791c325f68d163fa6b
MAC key: 4e3cb41f6fb908cd0b5bb6927bf6b9be
- The 42 output bytes match the RFC exactly. Expand needed two HMAC blocks, since each gives 32 bytes, and kept the first 42.
- The labels "enc" and "mac" produced unrelated 16-byte keys from the same secret. Using one key for two purposes, such as encryption and authentication, is a classic design mistake that HKDF avoids cheaply.
- JDK 25 added a standard API for this,
with the algorithmjavax.crypto.KDF (JEP 510). On older JDKs, the dozen lines above are enough.HKDF-SHA256
HMAC algorithms in the JDK
| Name | Tag size | Notes |
|---|---|---|
HmacSHA256 | 32 bytes | The common default (JWT "HS256", AWS Signature V4) |
HmacSHA384HmacSHA512 | 48, 64 bytes | Larger margins; SHA-512 can be faster on 64-bit CPUs |
HmacSHA3-256 | 32 bytes | Based on SHA-3 |
HmacSHA1 | 20 bytes | Still unbroken as an HMAC, but only for legacy systems |
An HMAC does not hide the message; anyone can read it. For secrecy plus integrity, use authenticated encryption such as AES-GCM; see Mac
| Situation | Use |
|---|---|
| Integrity and origin between two parties sharing a key | HMAC-SHA256 with a random 256-bit key |
| Webhooks and signed API requests | HMAC over timestamp plus raw body, with a time window |
| Comparing tags or tokens | MessageDigest.isEqual |
| Several keys from one secret | HKDF, or javax.crypto.KDF |
| Anyone may verify, only one party may sign | A digital signature; see |
| Secrecy as well as integrity | AES-GCM; see |
| Plain checksums without a key |