Post-quantum cryptography
suggest changeRSA, Diffie-Hellman and elliptic-curve cryptography (ECDH, ECDSA, Ed25519) all rely on problems that a large enough quantum computer could solve with Shor's algorithm. No such machine exists yet, but encrypted traffic recorded today can be stored and decrypted later ("harvest now, decrypt later"). That makes key exchange the urgent part. Signatures are less urgent, because a forged signature only matters while the key is still trusted, but certificates and firmware signing keys live for years.
In 2024 NIST published the first post-quantum standards, and Java 24 shipped two of them as final APIs, with no flags or extra libraries:
| Standard | Algorithm | What it replaces | JDK | Java API |
|---|---|---|---|---|
| FIPS 203 | ML-KEM (Kyber) | RSA key transport, ECDH | 24 (JEP 496) | KeyPairGenerator, KEM, KeyFactory |
| FIPS 204 | ML-DSA (Dilithium) | RSA, ECDSA, EdDSA signatures | 24 (JEP 497) | KeyPairGenerator, Signature, KeyFactory |
Both plug into the existing JCA classes, so code that already uses KeyPairGenerator and Signature (see Generate Public Private Key Pairs and Compute and Verify Digital Signatures) mostly changes an algorithm name. The new things to learn are the KEM API (Java 21) and much larger keys and signatures.
This article covers:
- what the JDK provides
- ML-KEM key encapsulation and encrypting a message with it
- ML-DSA signatures
- parameter sets, and sizes and speed compared with RSA and EC
- storing keys,
keytool, and PEM files with the previewPEMEncoder/PEMDecoder - hybrid schemes and the state of TLS
All examples are single files that run with java Example.java on JDK 24 or later. The output shown comes from JDK 25 (Temurin 25.0.4.1). Keys, signatures and timings will differ on your machine.
What's in the JDK
The algorithms are registered under a family name (ML-KEM, ML-DSA) and one name per parameter set:
import java.security.*;
public class Algos {
public static void main(String[] args) {
for (Provider p : Security.getProviders()) {
for (Provider.Service s : p.getServices()) {
String a = s.getAlgorithm();
if (a.startsWith("ML-") || a.startsWith("SLH") || a.contains("HSS") || a.contains("MLKEM"))
System.out.printf("%-10s %-18s %s%n", p.getName(), s.getType(), a);
}
}
}
}
SUN KeyFactory HSS/LMS
SUN KeyFactory ML-DSA-65
SUN Signature ML-DSA-65
SUN KeyFactory ML-DSA-44
SUN KeyFactory ML-DSA-87
SUN Signature ML-DSA-87
SUN KeyPairGenerator ML-DSA-87
SUN KeyFactory ML-DSA
SUN Signature ML-DSA-44
SUN KeyPairGenerator ML-DSA-65
SUN KeyPairGenerator ML-DSA-44
SUN Signature HSS/LMS
SUN KeyPairGenerator ML-DSA
SUN Signature ML-DSA
SunJCE KeyPairGenerator ML-KEM-1024
SunJCE KeyPairGenerator ML-KEM-512
SunJCE KeyPairGenerator ML-KEM-768
SunJCE KeyFactory ML-KEM-512
SunJCE KeyFactory ML-KEM-1024
SunJCE KeyFactory ML-KEM-768
SunJCE KEM ML-KEM-1024
SunJCE KEM ML-KEM-768
SunJCE KEM ML-KEM-512
SunJCE KeyFactory ML-KEM
SunJCE KEM ML-KEM
SunJCE KeyPairGenerator ML-KEM
HSS/LMS is a hash-based signature scheme (RFC 8554) that is also quantum-resistant. The JDK can only verify HSS/LMS signatures (there is no KeyPairGenerator for it); it exists for checking firmware and code signed elsewhere. SLH-DSA (FIPS 205, SPHINCS+) is not in the JDK; Bouncy Castle has it, together with ML-KEM and ML-DSA for older JDKs.
ML-KEM: key encapsulation
ML-KEM is not an encryption algorithm and not a Diffie-Hellman style key agreement. It is a key encapsulation mechanism (KEM):
- The receiver generates a key pair and publishes the public key.
- The sender calls encapsulate with that public key and gets two things: a random 32-byte shared secret, and a ciphertext (the encapsulation) to send to the receiver.
- The receiver calls decapsulate on the ciphertext with the private key and gets the same secret.
The sender never chooses the secret; the algorithm generates it. Java 21 added javax.crypto.KEM for this (with DHKEM as the first algorithm), and ML-KEM uses the same API:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.NamedParameterSpec;
import java.util.Arrays;
import java.util.HexFormat;
import javax.crypto.KEM;
import javax.crypto.SecretKey;
public class MlKemBasics {
public static void main(String[] args) throws Exception {
// Receiver: generate a key pair and publish the public key
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM");
KeyPair receiver = kpg.generateKeyPair();
System.out.println("public key: " + receiver.getPublic().getAlgorithm()
+ ", " + receiver.getPublic().getEncoded().length + " bytes encoded");
System.out.println("params: " + ((NamedParameterSpec) receiver.getPublic().getParams()).getName());
// Sender: encapsulate a fresh secret using the receiver's public key
KEM kem = KEM.getInstance("ML-KEM");
KEM.Encapsulator enc = kem.newEncapsulator(receiver.getPublic());
KEM.Encapsulated encapsulated = enc.encapsulate();
SecretKey senderKey = encapsulated.key();
byte[] ciphertext = encapsulated.encapsulation();
System.out.println("ciphertext: " + ciphertext.length + " bytes (enc.encapsulationSize() = "
+ enc.encapsulationSize() + ")");
System.out.println("shared key: " + senderKey.getAlgorithm() + ", "
+ senderKey.getEncoded().length + " bytes");
// Receiver: recover the same secret from the ciphertext
KEM.Decapsulator dec = kem.newDecapsulator(receiver.getPrivate());
SecretKey receiverKey = dec.decapsulate(ciphertext);
System.out.println("keys match: " + Arrays.equals(senderKey.getEncoded(), receiverKey.getEncoded()));
System.out.println("secret: " + HexFormat.of().formatHex(senderKey.getEncoded()).substring(0, 16) + "...");
}
}
public key: ML-KEM, 1206 bytes encoded
params: ML-KEM-768
ciphertext: 1088 bytes (enc.encapsulationSize() = 1088)
shared key: Generic, 32 bytes
keys match: true
secret: 4ec86dda0782f0f7...
Things to note:
getInstance("ML-KEM")withoutinitializegives ML-KEM-768, the set most protocols use.- Since Java 22,
PublicKeyandPrivateKeyextendAsymmetricKey, sogetParams()works without a cast to a key-specific interface. For ML-KEM and ML-DSA it returns aNamedParameterSpec. - The shared secret is a
SecretKeywith algorithm"Generic". Use it as input to a key derivation function, or ask theKEMAPI for a key of a specific algorithm, as shown next. - A new
EncapsulatorandDecapsulatoris cheap to create; they are not thread-safe, so create one per use or per thread.
Encrypting a message with ML-KEM and AES-GCM
To send data, combine the KEM with a symmetric cipher. encapsulate(from, to, algorithm) returns a slice of the secret as a key of the given algorithm, so the 32-byte secret can become an AES-256 key directly. The message format here is encapsulation || IV || AES-GCM output:
import java.nio.ByteBuffer;
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 javax.crypto.Cipher;
import javax.crypto.KEM;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
public class SealMessage {
static final int IV_LEN = 12;
// Output: KEM ciphertext || IV || AES-GCM ciphertext+tag
static byte[] seal(PublicKey recipient, byte[] plaintext) throws Exception {
KEM.Encapsulator enc = KEM.getInstance("ML-KEM").newEncapsulator(recipient);
// Ask for the whole 32-byte secret as an AES key
KEM.Encapsulated e = enc.encapsulate(0, 32, "AES");
byte[] iv = new byte[IV_LEN];
new SecureRandom().nextBytes(iv);
Cipher aes = Cipher.getInstance("AES/GCM/NoPadding");
aes.init(Cipher.ENCRYPT_MODE, e.key(), new GCMParameterSpec(128, iv));
byte[] body = aes.doFinal(plaintext);
return ByteBuffer.allocate(e.encapsulation().length + IV_LEN + body.length)
.put(e.encapsulation()).put(iv).put(body).array();
}
static byte[] open(PrivateKey key, byte[] message) throws Exception {
KEM.Decapsulator dec = KEM.getInstance("ML-KEM").newDecapsulator(key);
ByteBuffer buf = ByteBuffer.wrap(message);
byte[] encapsulation = new byte[dec.encapsulationSize()];
byte[] iv = new byte[IV_LEN];
buf.get(encapsulation).get(iv);
byte[] body = new byte[buf.remaining()];
buf.get(body);
SecretKey aesKey = dec.decapsulate(encapsulation, 0, 32, "AES");
Cipher aes = Cipher.getInstance("AES/GCM/NoPadding");
aes.init(Cipher.DECRYPT_MODE, aesKey, new GCMParameterSpec(128, iv));
return aes.doFinal(body);
}
public static void main(String[] args) throws Exception {
KeyPair alice = KeyPairGenerator.getInstance("ML-KEM-768").generateKeyPair();
byte[] sealed = seal(alice.getPublic(), "Meet at noon".getBytes(StandardCharsets.UTF_8));
System.out.println("sealed size: " + sealed.length + " bytes");
System.out.println("opened: " + new String(open(alice.getPrivate(), sealed), StandardCharsets.UTF_8));
// Flip one bit in the KEM ciphertext
sealed[10] ^= 1;
try {
open(alice.getPrivate(), sealed);
} catch (Exception ex) {
System.out.println("tampered: " + ex.getClass().getName());
}
}
}
sealed size: 1128 bytes
opened: Meet at noon
tampered: javax.crypto.AEADBadTagException
This is the post-quantum replacement for the RSA-OAEP + AES pattern in An example using a hybrid cryptosystem consisting of OAEP and GCM. The overhead is 1088 bytes for ML-KEM-768 instead of 384 bytes for RSA-3072, but there is no padding scheme to get wrong.
Using the raw secret as an AES key is fine for a single key. When you need several keys (one per direction, or an encryption key and a MAC key), or want to bind the key to a context string, run the secret through HKDF; see Key derivation with HKDF, which has a section on HKDF after ML-KEM.
Bad ciphertexts don't throw
The tampered message above fails at the AES-GCM step, not at decapsulation. That's by design: ML-KEM uses implicit rejection. A modified ciphertext of the right length decapsulates without error to a pseudo-random secret that has nothing to do with the sender's, which avoids leaking information through error messages or timing. Only a ciphertext of the wrong length is rejected:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Arrays;
import javax.crypto.KEM;
import javax.crypto.SecretKey;
public class Rejection {
public static void main(String[] args) throws Exception {
KeyPair kp = KeyPairGenerator.getInstance("ML-KEM-768").generateKeyPair();
KEM kem = KEM.getInstance("ML-KEM");
KEM.Encapsulated e = kem.newEncapsulator(kp.getPublic()).encapsulate();
byte[] bad = e.encapsulation().clone();
bad[0] ^= 1;
SecretKey k = kem.newDecapsulator(kp.getPrivate()).decapsulate(bad);
System.out.println("no exception, got " + k.getEncoded().length + "-byte key");
System.out.println("same as sender's: " + Arrays.equals(k.getEncoded(), e.key().getEncoded()));
try {
kem.newDecapsulator(kp.getPrivate()).decapsulate(Arrays.copyOf(bad, 1000));
} catch (Exception ex) {
System.out.println(ex.getClass().getName() + ": " + ex.getMessage());
}
}
}
no exception, got 32-byte key
same as sender's: false
javax.crypto.DecapsulateException: Invalid key encapsulation message length
So never treat "decapsulation succeeded" as proof that the message is genuine. Always follow the KEM with authenticated encryption (AES-GCM, ChaCha20-Poly1305) or a MAC, which will detect the wrong key.
ML-KEM parameter sets
FIPS 203 defines three parameter sets. Pick one with initialize(NamedParameterSpec) or by putting the name in getInstance:
import java.security.AsymmetricKey;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.NamedParameterSpec;
import javax.crypto.KEM;
public class MlKemSets {
public static void main(String[] args) throws Exception {
System.out.println("set pub priv ciphertext secret");
for (NamedParameterSpec spec : new NamedParameterSpec[] {
NamedParameterSpec.ML_KEM_512,
NamedParameterSpec.ML_KEM_768,
NamedParameterSpec.ML_KEM_1024 }) {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-KEM");
kpg.initialize(spec);
KeyPair kp = kpg.generateKeyPair();
KEM.Encapsulated e = KEM.getInstance("ML-KEM")
.newEncapsulator(kp.getPublic()).encapsulate();
String name = ((NamedParameterSpec) ((AsymmetricKey) kp.getPublic()).getParams()).getName();
System.out.printf("%-11s %5d %5d %11d %7d%n", name,
kp.getPublic().getEncoded().length,
kp.getPrivate().getEncoded().length,
e.encapsulation().length,
e.key().getEncoded().length);
}
// The default when you don't call initialize()
KeyPair def = KeyPairGenerator.getInstance("ML-KEM").generateKeyPair();
System.out.println("default: " + ((NamedParameterSpec) ((AsymmetricKey) def.getPublic()).getParams()).getName());
// Naming the set in getInstance() works too
KeyPair k1024 = KeyPairGenerator.getInstance("ML-KEM-1024").generateKeyPair();
System.out.println("ML-KEM-1024 via name: " + k1024.getPublic().getAlgorithm());
try {
KEM.getInstance("ML-KEM-512").newEncapsulator(k1024.getPublic());
} catch (Exception ex) {
System.out.println(ex.getClass().getSimpleName() + ": " + ex.getMessage());
}
}
}
set pub priv ciphertext secret
ML-KEM-512 822 86 768 32
ML-KEM-768 1206 86 1088 32
ML-KEM-1024 1590 86 1568 32
default: ML-KEM-768
ML-KEM-1024 via name: ML-KEM
InvalidKeyException: Unsupported parameter set name: ML-KEM-1024
A KEM obtained with a specific set name only accepts keys of that set; the family name ML-KEM accepts all three. The algorithm name of a key is always the family name; the set is in getParams().
| Set | NIST security category | Roughly as hard as | Use |
|---|---|---|---|
| ML-KEM-512 | 1 | AES-128 | Constrained environments |
| ML-KEM-768 | 3 | AES-192 | Default; used in TLS hybrids |
| ML-KEM-1024 | 5 | AES-256 | Required by NSA's CNSA 2.0 for national security systems |
The encoded sizes include a small header: the X.509 SubjectPublicKeyInfo adds 22 bytes to the raw 800/1184/1568-byte public keys. The 86-byte private keys are explained in the section on storing keys below.
ML-DSA: signatures
ML-DSA works like any other Signature algorithm:
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.util.Arrays;
public class MlDsaSign {
public static void main(String[] args) throws Exception {
KeyPair kp = KeyPairGenerator.getInstance("ML-DSA").generateKeyPair();
byte[] doc = "Release 1.4.2, sha256=9f86d081...".getBytes(StandardCharsets.UTF_8);
Signature signer = Signature.getInstance("ML-DSA");
signer.initSign(kp.getPrivate());
signer.update(doc);
byte[] sig = signer.sign();
System.out.println("algorithm: " + signer.getAlgorithm());
System.out.println("signature: " + sig.length + " bytes");
Signature verifier = Signature.getInstance("ML-DSA");
verifier.initVerify(kp.getPublic());
verifier.update(doc);
System.out.println("valid: " + verifier.verify(sig));
doc[0] = 'r';
verifier.initVerify(kp.getPublic());
verifier.update(doc);
System.out.println("tampered: " + verifier.verify(sig));
// Signing the same data twice gives different signatures
signer.initSign(kp.getPrivate());
signer.update(doc);
byte[] s1 = signer.sign();
signer.update(doc);
byte[] s2 = signer.sign();
System.out.println("same sig twice: " + Arrays.equals(s1, s2));
}
}
algorithm: ML-DSA
signature: 3309 bytes
valid: true
tampered: false
same sig twice: false
The default parameter set is ML-DSA-65. As with ML-KEM, KeyPairGenerator.getInstance("ML-DSA-44") (or initialize(NamedParameterSpec.ML_DSA_44)) selects another set, and Signature.getInstance("ML-DSA") accepts keys of any set.
Differences from SHA256withRSA or SHA256withECDSA:
- There is no hash in the name. ML-DSA hashes the message internally with SHAKE256; you pass the whole message to
update. - Signatures are randomized ("hedged"): signing the same message twice gives different signatures. Both verify. Don't compare signatures byte for byte, and don't use them as cache keys or identifiers.
- The JDK implements "pure" ML-DSA with an empty context string. It has no public API for FIPS 204's optional context string, and doesn't provide the pre-hash variant HashML-DSA. If a protocol you implement needs either, you need another provider such as Bouncy Castle.
Sizes and speed compared with RSA and EC
The cost of post-quantum signatures is size. This program signs a 1 KB message with each algorithm and measures rough throughput on one thread:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.spec.ECGenParameterSpec;
public class SigSizes {
record Alg(String keyAlg, Object init, String sigAlg) {}
public static void main(String[] args) throws Exception {
Alg[] algs = {
new Alg("RSA", 3072, "SHA256withRSA"),
new Alg("EC", new ECGenParameterSpec("secp256r1"), "SHA256withECDSA"),
new Alg("Ed25519", null, "Ed25519"),
new Alg("ML-DSA-44", null, "ML-DSA"),
new Alg("ML-DSA-65", null, "ML-DSA"),
new Alg("ML-DSA-87", null, "ML-DSA"),
};
byte[] msg = new byte[1024];
System.out.println("key pub key signature sign/s verify/s");
for (Alg a : algs) {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(a.keyAlg());
if (a.init() instanceof Integer bits) kpg.initialize(bits);
else if (a.init() instanceof ECGenParameterSpec spec) kpg.initialize(spec);
KeyPair kp = kpg.generateKeyPair();
Signature s = Signature.getInstance(a.sigAlg());
byte[] sig = null;
for (int i = 0; i < 1000; i++) { s.initSign(kp.getPrivate()); s.update(msg); sig = s.sign(); } // warm up
long t0 = System.nanoTime();
int n = 1000;
for (int i = 0; i < n; i++) { s.initSign(kp.getPrivate()); s.update(msg); sig = s.sign(); }
double signPerSec = n / ((System.nanoTime() - t0) / 1e9);
Signature v = Signature.getInstance(a.sigAlg());
for (int i = 0; i < 1000; i++) { v.initVerify(kp.getPublic()); v.update(msg); v.verify(sig); }
t0 = System.nanoTime();
for (int i = 0; i < n; i++) { v.initVerify(kp.getPublic()); v.update(msg); v.verify(sig); }
double verifyPerSec = n / ((System.nanoTime() - t0) / 1e9);
String name = a.keyAlg().equals("RSA") ? "RSA-3072" : a.keyAlg().equals("EC") ? "ECDSA P-256" : a.keyAlg();
System.out.printf("%-12s %7d %10d %8.0f %9.0f%n", name,
kp.getPublic().getEncoded().length, sig.length, signPerSec, verifyPerSec);
}
}
}
key pub key signature sign/s verify/s
RSA-3072 422 384 145 8376
ECDSA P-256 91 71 2177 658
Ed25519 44 64 688 812
ML-DSA-44 1334 2420 1095 4219
ML-DSA-65 1974 3309 905 2977
ML-DSA-87 2614 4627 776 1876
Treat the timings as a rough guide (this is not a JMH benchmark, see Simple JMH example for doing it properly), but the pattern is consistent: ML-DSA is fast to sign and verify, faster than RSA signing by a wide margin, while its public keys and signatures are several times larger than RSA-3072 ones and 15 to 70 times larger than EC ones.
| Public key | Ciphertext / signature | Security category | |
|---|---|---|---|
| X25519 (DHKEM) | 44 | 32 | classical only |
| RSA-3072 (OAEP) | 422 | 384 | classical only |
| ML-KEM-768 | 1206 | 1088 | 3 |
| Ed25519 | 44 | 64 | classical only |
| ML-DSA-44 | 1334 | 2420 | 2 |
| ML-DSA-65 | 1974 | 3309 | 3 |
| ML-DSA-87 | 2614 | 4627 | 5 |
(Sizes in bytes; public keys as X.509-encoded by the JDK.)
Practical consequences:
- Certificates and chains grow by several kilobytes. A TLS handshake with an ML-DSA chain may no longer fit in the first few TCP packets.
- Tokens: a JWT signed with ML-DSA-65 has a signature of about 4400 characters in base64url, larger than many HTTP header limits allow for cookies. ML-DSA for JOSE is still an IETF draft, so mainstream JWT libraries (see JWT) don't support it yet.
- Database columns sized for an RSA signature (
VARBINARY(512)) are too small.
Storing keys
ML-KEM and ML-DSA keys use the usual encodings: X.509 SubjectPublicKeyInfo for public keys and PKCS#8 for private keys, so getEncoded() and KeyFactory work as they do for RSA:
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class KeyStorage {
public static void main(String[] args) throws Exception {
KeyPair kp = KeyPairGenerator.getInstance("ML-DSA-65").generateKeyPair();
System.out.println("public: " + kp.getPublic().getFormat() + ", " + kp.getPublic().getEncoded().length + " bytes");
System.out.println("private: " + kp.getPrivate().getFormat() + ", " + kp.getPrivate().getEncoded().length + " bytes");
Files.write(Path.of("mldsa.pub"), kp.getPublic().getEncoded());
Files.write(Path.of("mldsa.key"), kp.getPrivate().getEncoded());
// Load them back. The generic "ML-DSA" KeyFactory reads all three parameter sets.
KeyFactory kf = KeyFactory.getInstance("ML-DSA");
PublicKey pub = kf.generatePublic(new X509EncodedKeySpec(Files.readAllBytes(Path.of("mldsa.pub"))));
PrivateKey priv = kf.generatePrivate(new PKCS8EncodedKeySpec(Files.readAllBytes(Path.of("mldsa.key"))));
System.out.println("loaded: " + pub.getAlgorithm() + " " + ((java.security.spec.NamedParameterSpec) pub.getParams()).getName());
Signature s = Signature.getInstance("ML-DSA");
s.initSign(priv);
s.update("hello".getBytes());
byte[] sig = s.sign();
s.initVerify(pub);
s.update("hello".getBytes());
System.out.println("round trip verifies: " + s.verify(sig));
}
}
public: X.509, 1974 bytes
private: PKCS#8, 54 bytes
loaded: ML-DSA ML-DSA-65
round trip verifies: true
The private key is tiny because by default the JDK stores only the seed (32 bytes for ML-DSA, 64 bytes for ML-KEM) from which the full private key is expanded. RFC 9881 (ML-DSA) and RFC 9935 (ML-KEM) allow three PKCS#8 formats: seed, expanded key, or both. The JDK reads all three. To make newly generated keys use another format (for a tool that can't handle seeds), set the security or system property jdk.mldsa.pkcs8.encoding or jdk.mlkem.pkcs8.encoding to expandedKey or both; the defaults are documented in conf/security/java.security. Keys from a store that only has the expanded form can't be converted back to a seed.
keytool
keytool generates ML-DSA keys and self-signed certificates in a PKCS#12 keystore:
$ keytool -genkeypair -alias signer -keyalg ML-DSA-65 -dname "CN=Release Signer" \
-keystore ks.p12 -storepass changeit
Generating ML-DSA-65 key pair and self-signed certificate (ML-DSA-65) with a validity of 90 days
for: CN=Release Signer
An ML-KEM key can't sign its own certificate, so keytool needs a signing key with -signer:
$ keytool -genkeypair -alias kem -keyalg ML-KEM-768 -dname "CN=kem" -signer signer \
-keystore ks.p12 -storepass changeit
Generating ML-KEM-768 key pair and a certificate (ML-DSA-65) issued by <signer> with a validity of 90 days
for: CN=kem
Without -signer it fails with Cannot derive signature algorithm from ML-KEM. jarsigner in JDK 25 can't sign with ML-DSA yet (Cannot extract digest algorithm from ML-DSA).
PEM files (preview)
Exchanging keys with OpenSSL and other tools usually means PEM text. Java 25 has a preview API for it, java.security.PEMEncoder and PEMDecoder (JEP 470; second preview in JDK 26 as JEP 524, so details may change). It works with any key type, including ML-KEM and ML-DSA:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PEMDecoder;
import java.security.PEMEncoder;
import java.security.PrivateKey;
import java.security.PublicKey;
public class PemKeys {
public static void main(String[] args) throws Exception {
KeyPair kp = KeyPairGenerator.getInstance("ML-DSA-44").generateKeyPair();
PEMEncoder pe = PEMEncoder.of();
String privPem = pe.encodeToString(kp.getPrivate());
String pubPem = pe.encodeToString(kp.getPublic());
System.out.println(privPem);
System.out.println(pubPem.lines().limit(2).toList() + " ... "
+ pubPem.lines().count() + " lines");
PEMDecoder pd = PEMDecoder.of();
PrivateKey priv = pd.decode(privPem, PrivateKey.class);
PublicKey pub = pd.decode(pubPem, PublicKey.class);
System.out.println("decoded: " + priv.getAlgorithm() + " / " + pub.getAlgorithm()
+ ", equal: " + pub.equals(kp.getPublic()));
// Encrypted private key (PKCS#8 EncryptedPrivateKeyInfo)
char[] password = "correct horse".toCharArray();
String enc = PEMEncoder.of().withEncryption(password).encodeToString(kp.getPrivate());
System.out.println(enc.lines().findFirst().orElseThrow());
PrivateKey back = PEMDecoder.of().withDecryption(password).decode(enc, PrivateKey.class);
System.out.println("decrypted equal: " + back.equals(kp.getPrivate()));
}
}
Run it with java --enable-preview PemKeys.java (or compile with javac --enable-preview --release 25):
-----BEGIN PRIVATE KEY-----
MDQCAQAwCwYJYIZIAWUDBAMRBCKAICRQ2ytlx7vKXuy3XnugDl7qg63hIHUOJfDe
Svbt7gOs
-----END PRIVATE KEY-----
[-----BEGIN PUBLIC KEY-----, MIIFMjALBglghkgBZQMEAxEDggUhABmsEQD9b2zVkipcVTW5VYRICy42vJ9FSSk6] ... 30 lines
decoded: ML-DSA / ML-DSA, equal: true
-----BEGIN ENCRYPTED PRIVATE KEY-----
decrypted equal: true
The seed-only private key fits in two lines of base64. OpenSSL 3.5 and later read and write the same formats. On JDK 24, or without preview features, do it by hand: Base64-encode getEncoded() with Base64.getMimeEncoder(64, "\n".getBytes()) and add the BEGIN/END lines.
Hybrids and TLS
ML-KEM and ML-DSA are new, and an implementation bug or a cryptanalytic surprise is more likely than with X25519 or ECDSA. The usual recommendation for key exchange is therefore a hybrid: do a classical X25519 exchange and an ML-KEM encapsulation, and derive the session key from both secrets, so that an attacker has to break both. With the JDK APIs this is two KEM calls (DHKEM and ML-KEM) whose secrets go into one HKDF; Key derivation with HKDF has a complete example. For interoperability, follow the exact construction of the protocol you implement instead of inventing your own.
In TLS, the hybrid group X25519MLKEM768 is already the default in current browsers, OpenSSL 3.5 and many CDNs. The JDK's TLS implementation in JDK 25 doesn't support it yet: the default named groups are all classical, and naming the hybrid group is silently ignored:
import java.util.Arrays;
import javax.net.ssl.SSLContext;
public class Tls {
public static void main(String[] args) throws Exception {
System.out.println(Arrays.toString(
SSLContext.getDefault().getDefaultSSLParameters().getNamedGroups()));
}
}
$ java Tls.java
[x25519, secp256r1, secp384r1, secp521r1, x448, ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192]
$ java -Djdk.tls.namedGroups=X25519MLKEM768,x25519 Tls.java
[x25519]
Hybrid ML-KEM key exchange for TLS 1.3 is proposed in JEP 527 for a later release. Until then, Java clients and servers that need post-quantum TLS can use a provider such as Bouncy Castle's JSSE, or terminate TLS in a proxy or load balancer that supports X25519MLKEM768. ML-DSA certificates in TLS are further away still; browsers and public CAs don't use them yet.
Where to start
- Inventory where you use RSA, ECDH and ECDSA, and how long the protected data must stay secret.
- Key exchange and encryption first (harvest now, decrypt later): ML-KEM-768 through the
KEMAPI, preferably as a hybrid with X25519. - Signatures second, starting with long-lived keys (firmware, code signing, root CAs), and budget for the size increase.
- Keep algorithm names configurable and data formats versioned, so you can change parameter sets or algorithms later ("crypto agility").
Summary
- Java 24 added ML-KEM (FIPS 203) and ML-DSA (FIPS 204) as final APIs in the standard providers; no flags or libraries are needed.
- ML-KEM is used through
javax.crypto.KEM: the sender encapsulates against a public key and gets a 32-byte secret plus a ciphertext; the receiver decapsulates. Default set ML-KEM-768 (1088-byte ciphertext). - Bad ML-KEM ciphertexts don't throw; they yield a wrong key. Always follow with authenticated encryption, and use HKDF to derive several keys.
- ML-DSA is used through
Signature.getInstance("ML-DSA"). Default set ML-DSA-65 (3309-byte signatures, 1952-byte raw public keys). Signatures are randomized; signing and verifying are fast. - Keys use X.509 and PKCS#8 encodings; private keys are stored as seeds by default.
keytoolgenerates both key types;jarsignerand the JDK's TLS don't support them yet in JDK 25. PEMEncoder/PEMDecoderare a preview in Java 25 (--enable-preview).- Prefer hybrid classical + post-quantum key exchange while the new algorithms mature.