How to generate HMAC-SHA256 in Java

Compute an HMAC-SHA256 message authentication code in Java for webhook signatures, API request signing, and understanding HS256 JWT internals. Use the browser HMAC Generator to compare digests while debugging, then implement javax.crypto.Mac HmacSHA256 with a strong shared secret and constant-time comparison on verify.

Last updated August 26, 2026

Steps

  1. 1

    Open the HMAC Generator, enter a test message and secret, and select SHA-256.

  2. 2

    Copy the hex digest — computation is client-side for safe local debugging.

  3. 3

    In Java, compute the same digest with javax.crypto.Mac HmacSHA256 and confirm it matches the tool.

  4. 4

    When verifying untrusted digests, use a constant-time compare (never == on hex strings alone).

  5. 5

    For production secrets, generate entropy with the JWT Secret Generator and store it outside source control.

Code Example

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

Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] raw = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
String digest = HexFormat.of().formatHex(raw);

// Compare digests in constant time when verifying webhooks.
Open HMAC Generator

Other languages

Related Articles

Frequently Asked Questions

What is HMAC-SHA256 used for?

HMAC authenticates a message with a shared secret. Common uses include webhook verification, API request signing, and the MAC step inside HS256 JWTs.

How do I verify an HMAC in Java?

Recompute the digest with javax.crypto.Mac HmacSHA256 over the exact same bytes the sender signed, then compare with a timing-safe equality helper. Mismatched encoding (hex vs Base64) is a frequent bug.

Is HMAC the same as hashing a password?

No. HMAC is fast and keyed. Password storage needs a slow KDF such as bcrypt, scrypt, or Argon2.

Is the browser HMAC Generator safe?

Yes for debugging — digests are computed locally. Do not paste live production secrets into shared or untrusted browsers.