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.
Code
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
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.TOTP URI Builder & Code GeneratorBuild valid otpauth://totp QR provisioning URIs and compute RFC 6238 HMAC-SHA1, SHA-256, or SHA-512 verification codes locally using Web Crypto.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.