Calculate HMAC-Sha256 with Java

Calculating a Hmac with the Java Cryptographic Architecture is only a few lines of code, despite a bit of complexity added from the API's design goal of being implementation independent and extensible.

This sample code shows how to calculate a Hmac-Sha256 from a message and a secret key (using java 8 or later).

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HMAC {
  static public byte[] calcHmacSha256(byte[] secretKey, byte[] message) {
    byte[] hmacSha256 = null;
    try {
      Mac mac = Mac.getInstance("HmacSHA256");
      SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "HmacSHA256");
      hmacSha256 = mac.doFinal(message);
    } catch (Exception e) {
      throw new RuntimeException("Failed to calculate hmac-sha256", e);
    return hmacSha256;

We can test the calcHmacSha256 method from a main class that prints the Hmac to console as a hex string.

import java.math.BigInteger;

public class Main {
  public static void main(String[] args) {
    try {
      byte[] hmacSha256 = HMAC.calcHmacSha256("secret123".getBytes("UTF-8"), "hello world".getBytes("UTF-8"));
System.out.println(String.format("Hex: %032x", new BigInteger(1, hmacSha256)));
} catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }

The Hmac-Sha256 for this particular message and secret key is:

Hex: 57938295649097379cddb382dd6c82d5e0460645a8fd01674a48a76de6142646

While a hex string representation is fine for transporting a Hmac in a service call or a link, a more efficient representation is base64. The following snippet uses java.util.Base64.

  String base64HmacSha256 = Base64.getEncoder().encodeToString(hmacSha256);
  System.out.println("Base64: " + base64HmacSha256);

As you can see the base64 string is shorter.

Base64: V5OClWSQlzec3bOC3WyC1eBGBkWo/QFnSkinbeYUJkY=