What does javax.crypto.Mac compute, how does HMAC differ from a plain digest and a Signature, and how do you verify a tag safely?
answer
- a hash with a key in it
- getInstance, init, update, doFinal
- shared secret versus key pair
- Mac offers no verify method
- isEqual, computed tag first
basics
~10 sjavax.crypto.Mac computes a fixed-length tag from a message and a shared secret key. A digest uses no key, and a Signature uses a key pair. Verify by recomputing the tag and comparing with MessageDigest.isEqual.
solid answer
~40 s`javax.crypto.Mac` computes a message authentication code: `Mac.getInstance("HmacSHA256")`, `init` with a secret key, `update`, then `doFinal` returns the tag. HMAC builds that tag from a hash function plus the key, so without the key nobody can produce a valid one, whereas a plain `MessageDigest` has no key and anyone who changes the data can recompute its hash. A `Signature` signs with a private key and verifies with a public one, so verifiers cannot forge and third parties can check; with HMAC both sides hold the same key, so either could have written the tag. `Mac` has no verify method: recompute the tag over the exact bytes received and compare with `MessageDigest.isEqual`, because `Arrays.equals` stops at the first difference and its timing can reveal how close a forged tag is.
code
java · 18 linesimport java.security.GeneralSecurityException;
import java.security.MessageDigest;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
final class Tags {
private static final String ALGORITHM = "HmacSHA256";
static byte[] tag(byte[] key, byte[] message) throws GeneralSecurityException {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(key, ALGORITHM));
return mac.doFinal(message);
}
static boolean verify(byte[] key, byte[] message, byte[] received) throws GeneralSecurityException {
return MessageDigest.isEqual(tag(key, message), received);
}
}go deeper
Recall that Mac takes a secret key and a digest does not. Know the calls getInstance, init, update and doFinal, and that HmacSHA256 is the usual algorithm name.
Explain why a keyed tag stops tampering when a plain hash cannot, how doFinal resets while keeping the key, and why the comparison goes through MessageDigest.isEqual.
Show the production traps: verifying raw bytes before parsing, rejecting replays with a timestamp or nonce, separate keys per purpose, and one Mac per thread.
Weigh shared-secret simplicity and speed against signatures: every HMAC verifier can also forge, and rotating a key touches every holder, which matters more as consumers multiply.
## What a MAC is A **message authentication code (MAC)** is a short, fixed-length value computed from a message and a secret key. In Java, `javax.crypto.Mac` is the engine class for it, and its Javadoc describes a MAC as a way to check the integrity of information sent over or stored in an unreliable medium, based on a secret key. A valid tag tells the receiver two things: the bytes have not changed, and whoever produced them held the key. It hides nothing, since the message stays readable. The lifecycle runs in this order: 1. `Mac.getInstance("HmacSHA256")` selects the algorithm. Every Java platform implementation must support `HmacSHA1` and `HmacSHA256`. 2. `init(Key)` supplies the secret, commonly `new SecretKeySpec(keyBytes, "HmacSHA256")`. Calling `update` or `doFinal` before this throws `IllegalStateException`. 3. `update(...)` feeds bytes and can be called any number of times. 4. `doFinal()` returns the tag and resets the object to its state after `init`, so the key stays in place for the next message. Using another key takes another `init`. `getMacLength()` reports the tag size, which is 32 bytes for `HmacSHA256`. ## How HMAC is built **HMAC**, specified in RFC 2104, builds a MAC from a cryptographic hash function and a shared secret. The JDK's `SunJCE` provider implements it in the package-private class `HmacCore`, which wraps a `MessageDigest`: - A key longer than the hash's block size is hashed first, and a shorter one is padded with zeros. - The key is XORed with two constants to give an inner pad and an outer pad. - The tag is `H(outerPad || H(innerPad || message))`, two passes of the hash. The two passes matter. A hand-rolled `SHA-256(key || message)` is weaker, because a SHA-256 output is the hash's final internal state: someone who sees it can keep hashing and produce a valid value for a longer message without knowing the key. This attack is called **length extension**, and HMAC's outer hash closes it. ## Digest, MAC or Signature | Property | `MessageDigest` | `Mac` (HMAC) | `Signature` | |---|---|---|---| | Key | None | One shared secret | Private to sign, public to verify | | Who can produce a valid value | Anyone | Any key holder | Only the private-key holder | | Who can verify | Anyone | Any key holder | Anyone with the public key | | Stops someone able to rewrite the data | No | Yes, without the key | Yes, without the private key | | Evidence for a third party | No | No | Yes | | What verifying looks like | Recompute and compare | Recompute and compare | `verify(byte[])` returns a boolean | That table suggests the choice: - Use a plain digest when the hash reaches the reader over a channel an attacker cannot alter, such as a checksum published separately from a download. - Use HMAC when both ends are yours and can share a secret, such as webhook payloads, signed cookies and internal tokens. - Use a signature when verifiers must not be able to create valid values, or when someone outside the two parties needs to check the result. Driving that engine is covered with the Signature API. ## Verifying a tag safely `Mac` has no verify method, so verification is code you write: - **Recompute over the exact bytes received.** Verify before parsing or acting on them, because parsing and re-serialising JSON, for instance, can change the bytes. - **Compare with `MessageDigest.isEqual(expected, received)`.** Its implementation note says that, unless the second argument is null or empty, the calculation time depends only on the length of the first argument, not on the second's length or on either array's contents. Put the tag you computed first, since its length is fixed and not chosen by the sender. This is a note about the JDK's implementation rather than part of the method's specified contract. - **Avoid `Arrays.equals`, and `String.equals` on hex or Base64 text.** Neither promises timing independent of the contents, and both stop once they see a difference, so response timing can reveal how much of a forged tag was right. - **Decode first.** Turn the received text into bytes, and treat malformed input as a failed check. - **Fail the same way every time.** Return one generic failure, with no hint about what differed. - **Cover the context.** A tag says a key holder produced these bytes, not when or for whom, so put a timestamp or nonce inside the tagged data and reject replays. Give each purpose its own key. ## Operating it A `Mac` carries running state between `update` and `doFinal`, and the JDK's HMAC implementation does no locking, so give each thread its own instance. For key material, `KeyGenerator.getInstance("HmacSHA256")` produces a 256-bit key by default in the JDK's provider. Because every verifier also holds the power to create tags, adding a verifier means handing out the secret and rotating the key touches every holder, a common reason a growing system moves to signatures.
- Why pass the tag you computed as the first argument to MessageDigest.isEqual rather than the received one?The implementation note says all bytes of `digesta` are examined and, unless `digestb` is null or empty, the time depends only on `digesta`'s length. Putting your computed tag first means that length is fixed by the algorithm, so the sender's input cannot change it. A null or empty second argument returns early, which reveals only that the tag was missing.
- Can one Mac instance handle many messages, and can threads share it?Sequentially, yes: `doFinal` resets the object to its state after `init` and keeps the key, `reset` discards a partial message, and only a different key needs another `init`. Across threads, no: it holds running state between `update` and `doFinal`, and the JDK's HMAC code does no locking. Give each thread its own instance.
- When would you replace an HMAC with a Signature?When verifiers must not be able to create valid values, as with one issuer and many consumers, or when an outside party needs evidence of who signed. The price is slower public-key operations and managing a key pair; the gain is that no verifier ever holds the secret.
Two business partners share one special stamp whose imprint changes with the letter's exact wording. A matching imprint shows that one of the partners stamped this very text, but not which one, and an outsider cannot tell them apart.
- A SHA-256 digest alone proves nobody tampered with a message sent over an open channel.
- HMAC encrypts the message, so its contents are hidden from anyone without the key.
- An HMAC tag proves to a third party exactly which of the two key holders wrote the message.
- Arrays.equals is safe for tags because a tag looks random, so its timing cannot help an attacker.
- Comparing the tags as hex strings with String.equals removes the timing problem.
- HMAC is simply SHA-256 applied to the key followed by the message.
- javax.crypto.Mac
- Java 1.4
- MessageDigest.isEqual
- Java 1.1
context
- Mac (Java SE 27 & JDK 27)docs.oracle.com
- MessageDigest (Java SE 27 & JDK 27)docs.oracle.com
- Signature (Java SE 27 & JDK 27)docs.oracle.com