00:00

Key Derivation Function API in Java 25

Last updated: · Standard (Java 25)

A key derivation function (KDF) turns secret input, such as a shared secret from a key exchange, into one or more strong keys. Java 25 (JEP 510) added the standard javax.crypto.KDF API with an HKDF implementation, after a preview in Java 24.

This tutorial shows how to configure HKDF, how to verify it against the official test vector, and how to derive an AES key after a key agreement.

1. Why Was a KDF API Needed?

Protocols such as TLS 1.3 and Hybrid Public Key Encryption, and quantum-resistant schemes, derive keys with KDFs. Before Java 25 there was no standard API for this, so developers wrote HKDF on top of Mac or used third-party libraries. A shared API lets security providers supply implementations and keeps application code independent of them.

2. Syntax

Syntax.java
KDF hkdf = KDF.getInstance("HKDF-SHA256");
AlgorithmParameterSpec params = HKDFParameterSpec.ofExtract()
        .addIKM(inputKeyMaterial)      // secret input
        .addSalt(salt)                 // optional, recommended
        .thenExpand(info, 32);         // context info and output length

byte[] bytes   = hkdf.deriveData(params);          // raw bytes
SecretKey key  = hkdf.deriveKey("AES", params);    // ready-to-use key

Available algorithms include HKDF-SHA256, HKDF-SHA384 and HKDF-SHA512.

3. Practical Examples

Example 1: Matching the RFC 5869 test vector

Using the official inputs from RFC 5869 test case 1 proves the implementation produces exactly the expected output keying material.

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

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

        KDF hkdf = KDF.getInstance("HKDF-SHA256");
        HKDFParameterSpec params = HKDFParameterSpec.ofExtract()
                .addIKM(ikm)
                .addSalt(salt)
                .thenExpand(info, 42);              // 42 bytes of output keying material

        byte[] okm = hkdf.deriveData(params);
        String expected = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865";
        System.out.println("Algorithm : " + hkdf.getAlgorithm());
        System.out.println("OKM       : " + hex.formatHex(okm));
        System.out.println("Matches RFC 5869: " + hex.formatHex(okm).equals(expected));
    }
}
Output
Algorithm : HKDF-SHA256
OKM       : 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
Matches RFC 5869: true

Example 2: Key agreement followed by HKDF

Alice and Bob agree on a shared secret with X25519, each derive the same AES-256 key with HKDF, and Bob decrypts Alice's message.

DeriveAesKey.java
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
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 DeriveAesKey {
    public static void main(String[] args) throws Exception {
        // 1. Two parties agree on a shared secret with X25519
        KeyPair alice = KeyPairGenerator.getInstance("X25519").generateKeyPair();
        KeyPair bob = KeyPairGenerator.getInstance("X25519").generateKeyPair();
        byte[] sharedA = agree(alice, bob);
        byte[] sharedB = agree(bob, alice);

        // 2. Each side derives the same AES key from the shared secret with HKDF
        SecretKey keyA = derive(sharedA);
        SecretKey keyB = derive(sharedB);
        System.out.println("Derived key: " + keyA.getAlgorithm() + ", " + keyA.getEncoded().length * 8 + " bits");

        // 3. Alice encrypts, Bob decrypts with his own derived key
        byte[] iv = new byte[12];                       // fixed IV only for this demo; never reuse in real code
        Cipher enc = Cipher.getInstance("AES/GCM/NoPadding");
        enc.init(Cipher.ENCRYPT_MODE, keyA, new GCMParameterSpec(128, iv));
        byte[] ciphertext = enc.doFinal("Transfer 5000 to account 42".getBytes(StandardCharsets.UTF_8));

        Cipher dec = Cipher.getInstance("AES/GCM/NoPadding");
        dec.init(Cipher.DECRYPT_MODE, keyB, new GCMParameterSpec(128, iv));
        System.out.println("Bob reads  : " + new String(dec.doFinal(ciphertext), StandardCharsets.UTF_8));
    }

    static byte[] agree(KeyPair own, KeyPair other) throws Exception {
        KeyAgreement ka = KeyAgreement.getInstance("X25519");
        ka.init(own.getPrivate());
        ka.doPhase(other.getPublic(), true);
        return ka.generateSecret();
    }

    static SecretKey derive(byte[] shared) throws Exception {
        KDF hkdf = KDF.getInstance("HKDF-SHA256");
        return hkdf.deriveKey("AES", HKDFParameterSpec.ofExtract()
                .addIKM(shared)
                .addSalt("chat-app-v1".getBytes(StandardCharsets.UTF_8))
                .thenExpand("message-key".getBytes(StandardCharsets.UTF_8), 32));
    }
}
Output
Derived key: AES, 256 bits
Bob reads  : Transfer 5000 to account 42

4. Extract and Expand

HKDF extract-then-expand HKDF first extracts a fixed-length pseudorandom key from the input keying material and salt, then expands it with context information into as many output bytes as required. input keying material e.g. X25519 secret extract HMAC(salt, IKM) = PRK expand PRK + info -> length output bytes or SecretKey
Figure 1: Different info strings derive independent keys from the same secret.

5. Important Points and Best Practices

  • Never use a raw shared secret directly as an encryption key; derive keys with a KDF.
  • Use a different info value for each purpose, for example one key for encryption and one for authentication.
  • HKDF is not a password hashing function; use a slow algorithm such as PBKDF2 for passwords.
  • The fixed IV in Example 2 is only for a deterministic demo; real AES-GCM code must use a unique IV for every message.

6. Summary

  • Java 25 (JEP 510) added the standard javax.crypto.KDF API.
  • HKDF is configured with HKDFParameterSpec: extract, then expand.
  • deriveData returns bytes; deriveKey returns a SecretKey.
  • KDFs turn shared secrets into purpose-specific keys.

Related Tutorials

7. References