Key derivation with HKDF

suggest change

A key exchange or key encapsulation gives you one shared secret. A real protocol usually needs several keys: one to encrypt, one to authenticate, sometimes one per direction, plus nonces. You shouldn't use the raw shared secret for any of them. Instead you feed it to a key derivation function (KDF), which turns it into as many independent keys as you need.

HKDF (HMAC-based Extract-and-Expand Key Derivation Function, RFC 5869) is the standard KDF for this. TLS 1.3, HPKE, Signal, WireGuard-style protocols and the JDK's own DHKEM all use it.

Java has a dedicated API for it:

Release What happened
Java 21 javax.crypto.KEM, the key encapsulation API (JEP 452), with DHKEM
Java 24 javax.crypto.KDF as a preview API (JEP 478); ML-KEM (JEP 496)
Java 25 KDF and HKDFParameterSpec are final (JEP 510), no flags needed

This article covers:

All examples are single files you can run with java Example.java on JDK 25. Outputs come from Temurin 25.0.4.1. Anything involving random keys prints different bytes on every run.

Related articles: Password hashing for PBKDF2 and Argon2, Application security for the bigger picture, and An example using a hybrid cryptosystem consisting of OAEP and GCM for the older RSA way of sharing a symmetric key.

Extract, then expand

HKDF has two steps, both built on HMAC:

  1. Extract: PRK = HMAC-Hash(salt, IKM). It takes input keying material (IKM) that has enough entropy but may not be uniformly random (a Diffie-Hellman result, for example) and condenses it into a pseudorandom key (PRK) of exactly one hash length.
  2. Expand: OKM = T(1) || T(2) || ..., where T(i) = HMAC-Hash(PRK, T(i-1) || info || i). It stretches the PRK into as many bytes of output keying material (OKM) as you ask for. Different info values give unrelated outputs.

The inputs:

Input What it is Notes
IKM the secret you start from a shared secret, a master key, a KEM output
salt optional, non-secret randomness if missing, HKDF uses a hash-length block of zeros
info optional context string binds the output to a purpose: "myapp v1 encryption"
length number of output bytes 1 to 255 × hash length (8160 bytes for SHA-256)

In Java, you get an HKDF with KDF.getInstance and describe the operation with an HKDFParameterSpec. There are three kinds of spec, one for each way of calling HKDF:

Spec Built with Result
Extract ofExtract().addIKM(..).addSalt(..).extractOnly() the PRK
Expand expandOnly(prk, info, length) OKM from an existing PRK
ExtractThenExpand ofExtract().addIKM(..).addSalt(..).thenExpand(info, length) OKM in one call

Then you call either deriveKey(algorithm, spec), which returns a SecretKey, or deriveData(spec), which returns a byte[].

This program runs all three on the inputs of RFC 5869 test case 1 (Appendix A.1):

import java.util.HexFormat;
import javax.crypto.KDF;
import javax.crypto.SecretKey;
import javax.crypto.spec.HKDFParameterSpec;

public class Rfc5869 {
    public static void main(String[] args) throws Exception {
        HexFormat hex = HexFormat.of();
        // RFC 5869, Appendix A.1 (test case 1)
        byte[] ikm  = hex.parseHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
        byte[] salt = hex.parseHex("000102030405060708090a0b0c");
        byte[] info = hex.parseHex("f0f1f2f3f4f5f6f7f8f9");
        int length = 42;

        KDF hkdf = KDF.getInstance("HKDF-SHA256");

        // 1. Extract only: IKM + salt -> pseudorandom key (PRK)
        SecretKey prk = hkdf.deriveKey("Generic",
                HKDFParameterSpec.ofExtract().addIKM(ikm).addSalt(salt).extractOnly());
        System.out.println("PRK = " + hex.formatHex(prk.getEncoded()));

        // 2. Expand only: PRK + info -> output keying material (OKM)
        byte[] okm1 = hkdf.deriveData(HKDFParameterSpec.expandOnly(prk, info, length));
        System.out.println("OKM = " + hex.formatHex(okm1));

        // 3. Both steps in one call
        byte[] okm2 = hkdf.deriveData(
                HKDFParameterSpec.ofExtract().addIKM(ikm).addSalt(salt).thenExpand(info, length));
        System.out.println("same: " + java.util.Arrays.equals(okm1, okm2));
        System.out.println(hkdf.getAlgorithm() + " from " + hkdf.getProviderName());
    }
}
PRK = 077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5
OKM = 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
same: true
HKDF-SHA256 from SunJCE

Both the PRK and the OKM are exactly the values given in the RFC.

The JDK's SunJCE provider implements HKDF-SHA256, HKDF-SHA384 and HKDF-SHA512. There is no HKDF-SHA1, so RFC test cases 4 to 7, which use SHA-1, can't be run.

The longer test case 2 (80-byte IKM, salt and info, 82 bytes of output) also matches:

import java.util.HexFormat;
import javax.crypto.KDF;
import javax.crypto.spec.HKDFParameterSpec;

public class Tc2 {
    public static void main(String[] args) throws Exception {
        byte[] ikm = new byte[80], salt = new byte[80], info = new byte[80];
        for (int i = 0; i < 80; i++) {
            ikm[i] = (byte) i;            // 0x00..0x4f
            salt[i] = (byte) (0x60 + i);  // 0x60..0xaf
            info[i] = (byte) (0xb0 + i);  // 0xb0..0xff
        }
        byte[] expected = HexFormat.of().parseHex(
                "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c"
              + "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71"
              + "cc30c58179ec3e87c14c01d5c1f3434f1d87");
        byte[] okm = KDF.getInstance("HKDF-SHA256").deriveData(
                HKDFParameterSpec.ofExtract().addIKM(ikm).addSalt(salt).thenExpand(info, 82));
        System.out.println("RFC 5869 A.2 matches: " + java.security.MessageDigest.isEqual(okm, expected));
    }
}
RFC 5869 A.2 matches: true

Salt, info and multiple inputs

Test case 3 has no salt and no info. It also shows how the builder treats missing and split inputs:

import java.util.HexFormat;
import javax.crypto.KDF;
import javax.crypto.spec.HKDFParameterSpec;

public class NoSalt {
    public static void main(String[] args) throws Exception {
        HexFormat hex = HexFormat.of();
        KDF hkdf = KDF.getInstance("HKDF-SHA256");
        byte[] ikm = hex.parseHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");

        // RFC 5869, Appendix A.3: no salt, no info
        byte[] a = hkdf.deriveData(HKDFParameterSpec.ofExtract()
                .addIKM(ikm).thenExpand(null, 42));
        // An explicit salt of 32 zero bytes is the same thing
        byte[] b = hkdf.deriveData(HKDFParameterSpec.ofExtract()
                .addIKM(ikm).addSalt(new byte[32]).thenExpand(new byte[0], 42));
        // IKM added in two pieces is concatenated
        byte[] c = hkdf.deriveData(HKDFParameterSpec.ofExtract()
                .addIKM(hex.parseHex("0b0b0b0b0b0b0b0b0b0b0b"))
                .addIKM(hex.parseHex("0b0b0b0b0b0b0b0b0b0b0b"))
                .thenExpand(null, 42));

        System.out.println(hex.formatHex(a));
        System.out.println(hex.formatHex(b));
        System.out.println(hex.formatHex(c));
    }
}
8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8
8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8
8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8

All three equal the RFC's OKM for test case 3. What this shows:

A random salt makes the extract step stronger, but it has to reach the other side, so protocols often use something both sides already have (a handshake transcript hash, or nothing). The salt doesn't need to be secret. The info is where context belongs: the protocol name, a version, the purpose of the key, and identifiers such as the parties' public keys.

Deriving several keys from one secret

The most common use of HKDF: extract once, then expand once per purpose with a distinct info label. Each output is independent; knowing the MAC key tells you nothing about the encryption key.

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HexFormat;
import javax.crypto.KDF;
import javax.crypto.SecretKey;
import javax.crypto.spec.HKDFParameterSpec;

public class SessionKeys {
    record Keys(SecretKey encryption, SecretKey mac, byte[] nonceBase) {}

    static Keys derive(byte[] masterSecret, byte[] salt) throws Exception {
        KDF hkdf = KDF.getInstance("HKDF-SHA256");

        // Extract once: the PRK is a uniformly random 32-byte key
        SecretKey prk = hkdf.deriveKey("Generic",
                HKDFParameterSpec.ofExtract().addIKM(masterSecret).addSalt(salt).extractOnly());

        // Expand many times, with a different label ("info") for each purpose
        SecretKey enc = hkdf.deriveKey("AES",
                HKDFParameterSpec.expandOnly(prk, label("myapp v1 encryption"), 32));
        SecretKey mac = hkdf.deriveKey("HmacSHA256",
                HKDFParameterSpec.expandOnly(prk, label("myapp v1 mac"), 32));
        byte[] nonceBase = hkdf.deriveData(
                HKDFParameterSpec.expandOnly(prk, label("myapp v1 nonce"), 12));
        return new Keys(enc, mac, nonceBase);
    }

    static byte[] label(String s) {
        return s.getBytes(StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        HexFormat hex = HexFormat.of();
        byte[] master = new byte[32];
        byte[] salt = new byte[32];
        SecureRandom rnd = new SecureRandom();
        rnd.nextBytes(master);
        rnd.nextBytes(salt);

        Keys k = derive(master, salt);
        System.out.println("enc   " + k.encryption().getAlgorithm() + " " + hex.formatHex(k.encryption().getEncoded()));
        System.out.println("mac   " + k.mac().getAlgorithm() + " " + hex.formatHex(k.mac().getEncoded()));
        System.out.println("nonce " + hex.formatHex(k.nonceBase()));

        // Same inputs always give the same keys
        Keys again = derive(master, salt);
        System.out.println("deterministic: " + k.encryption().equals(again.encryption()));
    }
}
enc   AES dbe35af713397c8ea1bb42ec6d798beee90be4588ee25aa5b26a31248c83461b
mac   HmacSHA256 c37c57afb58561f86dabfa538dc240e573550edc9f118f65588bc963d62f65ef
nonce 76b0c42459670b44db8ab9f5
deterministic: true

Notes:

After a key agreement: X25519

KeyAgreement.generateSecret() returns the raw Diffie-Hellman result. For X25519 that's 32 bytes, but they aren't uniformly random, and RFC 7748 recommends deriving the symmetric key with a KDF that takes the shared secret and both public keys. HKDF is the usual choice:

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.HexFormat;
import javax.crypto.Cipher;
import javax.crypto.KDF;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.HKDFParameterSpec;

public class X25519Hkdf {
    // Both sides call this with their own private key and the peer's public key
    static SecretKey sessionKey(PrivateKey mine, PublicKey peer,
                                PublicKey client, PublicKey server) throws Exception {
        KeyAgreement ka = KeyAgreement.getInstance("X25519");
        ka.init(mine);
        ka.doPhase(peer, true);
        byte[] shared = ka.generateSecret();   // 32 bytes, NOT a uniformly random key

        // Bind the key to this exchange: info = label || client pub || server pub
        ByteArrayOutputStream info = new ByteArrayOutputStream();
        info.writeBytes("demo-protocol v1 session key".getBytes(StandardCharsets.UTF_8));
        info.writeBytes(client.getEncoded());
        info.writeBytes(server.getEncoded());

        KDF hkdf = KDF.getInstance("HKDF-SHA256");
        return hkdf.deriveKey("AES", HKDFParameterSpec.ofExtract()
                .addIKM(shared)
                .thenExpand(info.toByteArray(), 32));
    }

    public static void main(String[] args) throws Exception {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("X25519");
        KeyPair client = kpg.generateKeyPair();
        KeyPair server = kpg.generateKeyPair();

        SecretKey clientKey = sessionKey(client.getPrivate(), server.getPublic(),
                client.getPublic(), server.getPublic());
        SecretKey serverKey = sessionKey(server.getPrivate(), client.getPublic(),
                client.getPublic(), server.getPublic());
        System.out.println("keys match: " + clientKey.equals(serverKey));

        // Client encrypts with AES-GCM, server decrypts
        byte[] iv = new byte[12];
        new SecureRandom().nextBytes(iv);
        Cipher enc = Cipher.getInstance("AES/GCM/NoPadding");
        enc.init(Cipher.ENCRYPT_MODE, clientKey, new GCMParameterSpec(128, iv));
        byte[] ct = enc.doFinal("hello over X25519 + HKDF".getBytes(StandardCharsets.UTF_8));
        System.out.println("ciphertext: " + HexFormat.of().formatHex(ct));

        Cipher dec = Cipher.getInstance("AES/GCM/NoPadding");
        dec.init(Cipher.DECRYPT_MODE, serverKey, new GCMParameterSpec(128, iv));
        System.out.println("decrypted: " + new String(dec.doFinal(ct), StandardCharsets.UTF_8));
    }
}
keys match: true
ciphertext: fa9192772229208dee703c408377a5ddfcfac8f2bb4cdf3b20286946e10d5a3e70b7a2d463ba7441
decrypted: hello over X25519 + HKDF

Putting both public keys into info ties the session key to this particular exchange. Both sides must build info from the same bytes in the same order, which is why the client's key always goes first, regardless of who is computing.

This is an unauthenticated exchange: it protects against eavesdroppers, not against a man in the middle. A real protocol also signs the public keys or checks them against a certificate (see Compute and Verify Digital Signatures). Prefer TLS over a homemade protocol whenever you can.

After a key encapsulation: the KEM API

With a KEM (key encapsulation mechanism), the sender takes the receiver's public key and gets back two things: a shared secret and an encapsulation to send to the receiver. The receiver decapsulates it with the private key to get the same secret. Java 21 added javax.crypto.KEM with DHKEM (X25519, X448 and the NIST curves, as in RFC 9180); Java 24 added ML-KEM, the post-quantum KEM from FIPS 203.

A KEM gives you one 32-byte secret. If you need more than one key, run it through HKDF:

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.HexFormat;
import javax.crypto.KDF;
import javax.crypto.KEM;
import javax.crypto.SecretKey;
import javax.crypto.spec.HKDFParameterSpec;

public class KemHkdf {
    static final byte[] ENC_INFO = "file-encryption v1 key".getBytes(StandardCharsets.UTF_8);
    static final byte[] MAC_INFO = "file-encryption v1 mac".getBytes(StandardCharsets.UTF_8);

    public static void main(String[] args) throws Exception {
        HexFormat hex = HexFormat.of();
        for (String alg : new String[] {"X25519", "ML-KEM-768"}) {
            String kemAlg = alg.startsWith("ML-KEM") ? "ML-KEM" : "DHKEM";

            // Receiver: long-term key pair
            KeyPair receiver = KeyPairGenerator.getInstance(alg).generateKeyPair();

            // Sender: knows only the public key
            KEM.Encapsulator e = KEM.getInstance(kemAlg).newEncapsulator(receiver.getPublic());
            KEM.Encapsulated sent = e.encapsulate();
            SecretKey senderSecret = sent.key();
            byte[] encapsulation = sent.encapsulation();   // send this to the receiver

            // Receiver: recovers the same shared secret
            KEM.Decapsulator d = KEM.getInstance(kemAlg).newDecapsulator(receiver.getPrivate());
            SecretKey receiverSecret = d.decapsulate(encapsulation);

            // Both sides: one KEM secret -> separate keys for separate jobs
            KDF hkdf = KDF.getInstance("HKDF-SHA256");
            SecretKey prk = hkdf.deriveKey("Generic", HKDFParameterSpec.ofExtract()
                    .addIKM(receiverSecret).extractOnly());
            SecretKey encKey = hkdf.deriveKey("AES", HKDFParameterSpec.expandOnly(prk, ENC_INFO, 32));
            SecretKey macKey = hkdf.deriveKey("HmacSHA256", HKDFParameterSpec.expandOnly(prk, MAC_INFO, 32));

            System.out.printf("%s via %s: secret %d bytes (%s), encapsulation %d bytes, secrets match: %b%n",
                    alg, kemAlg, senderSecret.getEncoded().length, senderSecret.getAlgorithm(),
                    encapsulation.length, senderSecret.equals(receiverSecret));
            System.out.println("  enc key " + hex.formatHex(encKey.getEncoded()).substring(0, 16) + "...");
            System.out.println("  mac key " + hex.formatHex(macKey.getEncoded()).substring(0, 16) + "...");
        }
    }
}
X25519 via DHKEM: secret 32 bytes (Generic), encapsulation 32 bytes, secrets match: true
  enc key 7571172ffe02bfe7...
  mac key d7e18ec84acdeb49...
ML-KEM-768 via ML-KEM: secret 32 bytes (Generic), encapsulation 1088 bytes, secrets match: true
  enc key 55861f8682f90408...
  mac key a6e10208c9a127da...

The code is the same for both algorithms; only the key pair and the KEM name change. DHKEM already runs HKDF internally (RFC 9180 defines it that way), so its secret is uniformly random, and so is ML-KEM's. The HKDF step here isn't about cleaning up the secret, but about getting two separate keys out of one, each bound to its purpose.

Compared with the RSA-OAEP approach in the hybrid cryptosystem example, a KEM never lets you choose the secret, which removes a whole class of padding and key-generation mistakes.

Hybrid post-quantum: combining two secrets

Until ML-KEM has a longer track record, the common recommendation is a hybrid: do a classical exchange and a post-quantum one, and derive the key from both. An attacker then has to break both. Because addIKM concatenates, HKDF combines them in one call:

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import javax.crypto.KDF;
import javax.crypto.KEM;
import javax.crypto.SecretKey;
import javax.crypto.spec.HKDFParameterSpec;

public class Hybrid {
    public static void main(String[] args) throws Exception {
        KeyPair classic = KeyPairGenerator.getInstance("X25519").generateKeyPair();
        KeyPair pq = KeyPairGenerator.getInstance("ML-KEM-768").generateKeyPair();

        // Sender: one encapsulation per algorithm
        KEM.Encapsulated c = KEM.getInstance("DHKEM").newEncapsulator(classic.getPublic()).encapsulate();
        KEM.Encapsulated q = KEM.getInstance("ML-KEM").newEncapsulator(pq.getPublic()).encapsulate();

        byte[] info = "hybrid-demo v1".getBytes(StandardCharsets.UTF_8);
        SecretKey senderKey = KDF.getInstance("HKDF-SHA256").deriveKey("AES",
                HKDFParameterSpec.ofExtract()
                        .addIKM(q.key())        // IKM = ML-KEM secret || X25519 secret
                        .addIKM(c.key())
                        .thenExpand(info, 32));

        // Receiver: decapsulate both, combine in the same order
        SecretKey ss1 = KEM.getInstance("ML-KEM").newDecapsulator(pq.getPrivate()).decapsulate(q.encapsulation());
        SecretKey ss2 = KEM.getInstance("DHKEM").newDecapsulator(classic.getPrivate()).decapsulate(c.encapsulation());
        SecretKey receiverKey = KDF.getInstance("HKDF-SHA256").deriveKey("AES",
                HKDFParameterSpec.ofExtract().addIKM(ss1).addIKM(ss2).thenExpand(info, 32));

        System.out.println("hybrid keys match: " + senderKey.equals(receiverKey));
    }
}
hybrid keys match: true

This is a sketch of the idea. Standardized hybrids such as X25519MLKEM768 in TLS also feed the encapsulations and public keys into the derivation; if you need interoperability, follow the exact construction of the spec you're implementing.

HKDF is not for passwords

HKDF assumes its input already has plenty of entropy: a 32-byte random secret, a DH result. It's fast on purpose. A password has little entropy, and the only defense is making each guess expensive, which HKDF doesn't do. This program compares it with PBKDF2 at OWASP's recommended 600,000 iterations:

import java.nio.charset.StandardCharsets;
import javax.crypto.KDF;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.HKDFParameterSpec;
import javax.crypto.spec.PBEKeySpec;

public class NotForPasswords {
    public static void main(String[] args) throws Exception {
        byte[] salt = new byte[16];
        KDF hkdf = KDF.getInstance("HKDF-SHA256");
        SecretKeyFactory pbkdf2 = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

        for (int round = 0; round < 2; round++) {   // first round warms up the JIT
            int n = 200_000;
            long t0 = System.nanoTime();
            for (int i = 0; i < n; i++) {
                byte[] guess = ("password" + i).getBytes(StandardCharsets.UTF_8);
                hkdf.deriveData(HKDFParameterSpec.ofExtract()
                        .addIKM(guess).addSalt(salt).thenExpand(null, 32));
            }
            double hkdfPerSec = n / ((System.nanoTime() - t0) / 1e9);

            int m = 5;
            t0 = System.nanoTime();
            for (int i = 0; i < m; i++) {
                pbkdf2.generateSecret(new PBEKeySpec(("password" + i).toCharArray(), salt, 600_000, 256));
            }
            double pbkdf2PerSec = m / ((System.nanoTime() - t0) / 1e9);

            if (round == 1) {
                System.out.printf("HKDF-SHA256:          %,12.0f guesses/s%n", hkdfPerSec);
                System.out.printf("PBKDF2 (600k rounds): %,12.1f guesses/s%n", pbkdf2PerSec);
            }
        }
    }
}
HKDF-SHA256:               290,238 guesses/s
PBKDF2 (600k rounds):          3.4 guesses/s

That's one core in Java, so the gap is roughly 85,000×; a GPU widens it further. To turn a password into a key, use a password-based KDF: PBKDF2 from the JDK, or better, Argon2id or scrypt from a library. See Password hashing. It's fine to run a password-derived key through HKDF afterwards to split it into several keys, since by then the expensive step is done.

Limits and errors

import javax.crypto.KDF;
import javax.crypto.spec.HKDFParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Limits {
    interface Action { void run() throws Exception; }

    static void attempt(String what, Action a) {
        try {
            a.run();
            System.out.println(what + ": ok");
        } catch (Exception e) {
            System.out.println(what + ": " + e.getClass().getSimpleName() + ": " + e.getMessage());
            if (e.getCause() != null) {
                System.out.println("    cause: " + e.getCause().getMessage());
            }
        }
    }

    public static void main(String[] args) throws Exception {
        KDF hkdf = KDF.getInstance("HKDF-SHA256");
        byte[] ikm = new byte[32];

        // at most 255 * 32 = 8160 bytes for SHA-256
        attempt("8160 bytes", () -> hkdf.deriveData(
                HKDFParameterSpec.ofExtract().addIKM(ikm).thenExpand(null, 8160)));
        attempt("8161 bytes", () -> hkdf.deriveData(
                HKDFParameterSpec.ofExtract().addIKM(ikm).thenExpand(null, 8161)));
        attempt("0 bytes", () -> hkdf.deriveData(
                HKDFParameterSpec.ofExtract().addIKM(ikm).thenExpand(null, 0)));
        // a PRK must be at least as long as the hash output
        attempt("16-byte PRK", () -> hkdf.deriveData(HKDFParameterSpec.expandOnly(
                new SecretKeySpec(new byte[16], "Generic"), null, 32)));
        attempt("HKDF-SHA1", () -> KDF.getInstance("HKDF-SHA1"));
    }
}
8160 bytes: ok
8161 bytes: InvalidAlgorithmParameterException: The specified SunJCE provider does not support this input
    cause: Requested length exceeds maximum allowed length
0 bytes: IllegalArgumentException: length must be > 0
16-byte PRK: InvalidAlgorithmParameterException: The specified SunJCE provider does not support this input
    cause: an HKDF Expand could not be initialized with the given keying material
HKDF-SHA1: NoSuchAlgorithmException: No available provider supports the specified algorithm

The top-level message is generic because KDF picks a provider lazily, on the first derive call, and tries each provider that supports the algorithm; the real reason is in getCause(). A zero length is rejected while the spec is built, before any provider gets involved.

The output limit is 255 × hash length: 8160 bytes for SHA-256, 12240 for SHA-384 and 16320 for SHA-512. If you need more than that, you probably want a stream cipher keyed from HKDF output, not more HKDF output.

Before Java 25: HKDF with Mac

On JDK 17 to 23 there's no KDF class, and on JDK 24 it's a preview API that needs --enable-preview. HKDF is short enough to write with Mac:

import java.io.ByteArrayOutputStream;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

// HKDF-SHA256 for JDK 17-24, using only Mac
public class HkdfMac {
    static byte[] extract(byte[] salt, byte[] ikm) throws Exception {
        if (salt == null || salt.length == 0) salt = new byte[32];
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(salt, "HmacSHA256"));
        return mac.doFinal(ikm);
    }

    static byte[] expand(byte[] prk, byte[] info, int length) throws Exception {
        if (length < 1 || length > 255 * 32) throw new IllegalArgumentException("bad length");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(prk, "HmacSHA256"));
        ByteArrayOutputStream okm = new ByteArrayOutputStream(length);
        byte[] t = new byte[0];
        for (int i = 1; okm.size() < length; i++) {
            mac.update(t);                       // T(i) = HMAC(PRK, T(i-1) || info || i)
            if (info != null) mac.update(info);
            mac.update((byte) i);
            t = mac.doFinal();
            okm.write(t, 0, Math.min(t.length, length - okm.size()));
        }
        return okm.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        HexFormat hex = HexFormat.of();
        byte[] prk = extract(hex.parseHex("000102030405060708090a0b0c"),
                hex.parseHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"));
        byte[] okm = expand(prk, hex.parseHex("f0f1f2f3f4f5f6f7f8f9"), 42);
        System.out.println(hex.formatHex(okm));
    }
}
3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865

The output matches RFC 5869 test case 1, and the program compiles with --release 17. Bouncy Castle's HKDFBytesGenerator is another option. Once you're on Java 25, switch to KDF: it's the same algorithm, but the provider can be swapped (for example for a FIPS or hardware-backed one) without code changes.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents