HMAC SHA-256 Sign And Verify

Sign a payload with the JCA Mac under HmacSHA256 and verify by recomputing the tag through HexFormat; any changed byte flips the tag and fails the comparison.

JavaSecurity Boundaries

Code

snippet
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class PayloadSigner {

    public static void main(String[] args) throws Exception {
        // Hard-coded key for demonstration only; real systems inject it from a secret manager or env
        byte[] key = "rotate-me-quarterly-demo-key".getBytes(StandardCharsets.UTF_8);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));

        String payload = "order=1001&amount=42";
        String signature = HexFormat.of().formatHex(
                mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
        System.out.println("signature: " + signature);

        // After doFinal the Mac resets to its init state: the same key can compute another tag right away
        String replay = HexFormat.of().formatHex(
                mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
        System.out.println("verify ok: " + replay.equals(signature));

        // Change one character of the payload and the tag no longer matches
        String tampered = HexFormat.of().formatHex(
                mac.doFinal("order=1001&amount=43".getBytes(StandardCharsets.UTF_8)));
        System.out.println("tamper detected: " + !tampered.equals(signature));
    }
}

How it works

The working surface is the class PayloadSigner — everything else is wiring.

Using it

The demo output is labeled (signature:, verify ok:, tamper detected:), so every printed line maps back to its originating operation.

Key statements

byte[] key = "rotate-me-quarterly-demo-key".getBytes(StandardCharsets.UTF_8);
mac.init(new SecretKeySpec(key, "HmacSHA256"));
Mac mac = Mac.getInstance("HmacSHA256");

Interactive Tools for This Topic

FAQ

What does HMAC SHA-256 Sign And Verify print when run?
The script runs standalone; its 3 labeled outputs include `signature:`, `verify ok:`, `tamper detected:`.