Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Mac: authenticating messages with HMAC

The javax.crypto.Mac class computes a message authentication code using a secret key. Learn how to select HmacSHA256, initialize it with a key, and finish the computation with doFinal.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
byte[] tag = mac.doFinal(messageBytes);

Mac in javax.crypto computes a message authentication code (MAC). It supports checking data integrity using a shared secret key; it does not encrypt the message. HMAC is a MAC construction based on a cryptographic hash function.

Mac.getInstance("HmacSHA256") selects an algorithm implementation from cryptographic providers. Mac.init(key) initializes the object with a key. Mac.doFinal(messageBytes) processes the bytes and returns the tag; alternatively, supply chunks through update, then call doFinal().

After completion, doFinal restores the initialized state, retaining the key for the next message. A different key requires another init. Missing initialization causes IllegalStateException; an unsuitable key can cause InvalidKeyException, and an unavailable algorithm causes NoSuchAlgorithmException.

The example uses a public, short key solely for a repeatable test. Do not use it in production: supply an appropriately generated and protected secret key. The documentation scope is Java SE 21; the production runtime has not been attested.

Examples

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

public class MacExample {
    public static void main(String[] args) throws Exception {
        // Public test key only; never use it in production.
        byte[] keyBytes = "key".getBytes(StandardCharsets.UTF_8);
        byte[] message = "The quick brown fox jumps over the lazy dog"
                .getBytes(StandardCharsets.UTF_8);

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(keyBytes, "HmacSHA256"));
        byte[] tag = mac.doFinal(message);
        System.out.println(HexFormat.of().formatHex(tag));
    }
}

Result

f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources