ML-DSA-65
The recommended general-purpose post-quantum signature (NIST Security Category 3): 1952-byte public key, 3309-byte signature.
Why it's safe
ML-DSA-65 is a common default for new post-quantum signing. Signing and verification are fast, often faster than RSA signing, but signatures are about 50 times larger than Ed25519's 64 bytes, so check message, token, certificate and database size limits.
- Used for
- Signature
- Family
- Lattice (Module-LWE / Module-SIS)
- Classical security
- 192 bits
- Against a quantum computer
- ~192 bits
- Standards
- FIPS 204, RFC 9881 (X.509), RFC 9964 (JOSE/COSE)
Migration guides
How to adopt ML-DSA-65. Pick your stack.
OpenSSL 3.5+ (libcrypto EVP) · cC/C++ with OpenSSL 3.5+: ML-KEM and ML-DSA through the EVP API and the command lineProduction-ready
Why
OpenSSL 3.5+ implements ML-KEM (FIPS 203), ML-DSA (FIPS 204) and SLH-DSA (FIPS 205) in its default provider, reachable through the same EVP APIs you use for RSA and EC. The EVP_PKEY_encapsulate/EVP_PKEY_decapsulate KEM API has existed since OpenSSL 3.0, so the code shape is familiar.
Steps
- Link against OpenSSL 3.5 or later and check the version at runtime.
- Generate keys with
EVP_PKEY_Q_keygen(NULL, NULL, "ML-KEM-768")/"ML-DSA-65". - Encapsulate/decapsulate with the EVP KEM API; sign with
EVP_PKEY_sign_message_init+EVP_PKEY_sign(orEVP_DigestSign*as for Ed25519). - Store keys as PKCS#8/SPKI PEM (
PEM_write_bio_PrivateKey,PEM_write_bio_PUBKEY).
Before
EVP_PKEY *rsa = EVP_RSA_gen(2048);
/* ... EVP_PKEY_encrypt with RSA-OAEP to wrap a data key ... */After: ML-KEM-768 encapsulation
#include <openssl/evp.h>
EVP_PKEY *kem = EVP_PKEY_Q_keygen(NULL, NULL, "ML-KEM-768");
/* Sender (with the recipient's public key) */
EVP_PKEY_CTX *ectx = EVP_PKEY_CTX_new_from_pkey(NULL, kem, NULL);
unsigned char *ct = NULL, *ss = NULL;
size_t ctlen = 0, sslen = 0;
EVP_PKEY_encapsulate_init(ectx, NULL);
EVP_PKEY_encapsulate(ectx, NULL, &ctlen, NULL, &sslen); /* sizes: 1088, 32 */
ct = OPENSSL_malloc(ctlen);
ss = OPENSSL_malloc(sslen);
EVP_PKEY_encapsulate(ectx, ct, &ctlen, ss, &sslen);
/* Recipient (with the private key) */
EVP_PKEY_CTX *dctx = EVP_PKEY_CTX_new_from_pkey(NULL, kem, NULL);
unsigned char ss2[32];
size_t ss2len = sizeof(ss2);
EVP_PKEY_decapsulate_init(dctx, NULL);
EVP_PKEY_decapsulate(dctx, ss2, &ss2len, ct, ctlen);
/* ss == ss2: feed into HKDF (EVP_KDF "HKDF") to derive an AES-256-GCM key */After: ML-DSA-65 signature
EVP_PKEY *key = EVP_PKEY_Q_keygen(NULL, NULL, "ML-DSA-65");
EVP_PKEY_CTX *sctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL);
EVP_SIGNATURE *alg = EVP_SIGNATURE_fetch(NULL, "ML-DSA-65", NULL);
size_t siglen = 0;
EVP_PKEY_sign_message_init(sctx, alg, NULL); /* params may carry a "context-string" */
EVP_PKEY_sign(sctx, NULL, &siglen, msg, msglen); /* 3309 */
unsigned char *sig = OPENSSL_malloc(siglen);
EVP_PKEY_sign(sctx, sig, &siglen, msg, msglen);
EVP_SIGNATURE_free(alg);Check every return value (<= 0 means failure) in real code; it is omitted above for brevity.
Command line
openssl genpkey -algorithm ML-DSA-65 -out mldsa.key
openssl pkey -in mldsa.key -pubout -out mldsa.pub
openssl pkeyutl -sign -rawin -inkey mldsa.key -in msg.txt -out msg.sig
openssl pkeyutl -verify -rawin -pubin -inkey mldsa.pub -in msg.txt -sigfile msg.sig
openssl genpkey -algorithm ML-KEM-768 -out kem.key
openssl pkey -in kem.key -pubout -out kem.pub
openssl pkeyutl -encap -pubin -inkey kem.pub -out ct.bin -secret ss1.bin
openssl pkeyutl -decap -inkey kem.key -in ct.bin -secret ss2.bin
cmp ss1.bin ss2.bin && echo same-secretGotchas
- Private key formats. OpenSSL can store ML-KEM/ML-DSA private keys as seed, expanded key, or both; provider parameters such as
ml-kem.retain_seedandml-kem.prefer_seedcontrol this. Other tools (Cloudflare uploads, some HSMs, other libraries) may require the seed-only form, so test interop. - Implicit rejection in ML-KEM: a bad ciphertext yields a random secret, not an error.
- Sizes: ML-KEM-768 ct 1,088 B / ek 1,184 B; ML-DSA-65 sig 3,309 B / pk 1,952 B.
- oqs-provider is no longer needed for these algorithms; loading both can cause name clashes. Remove it unless you need other algorithms.
- HSMs via PKCS#11 need vendor support for the new mechanisms; check before moving keys.
Verify
openssl list -kem-algorithms | grep -i ml-kem
openssl list -signature-algorithms | grep -i ml-dsaOpenSSL 3.5+ (certificates) · configPrivate PKI: issue ML-DSA certificates with OpenSSL 3.5+ (RFC 9881), and know where they workExperimental
Why
Certificates authenticate servers, clients, devices and code. A quantum computer could recover a CA's or server's private key from its RSA/ECDSA public key and impersonate it. RFC 9881 standardises ML-DSA keys and signatures in X.509, and OpenSSL 3.5+ can create such certificates. The public web is not there yet: publicly trusted CAs do not issue ML-DSA certificates and browsers are exploring other designs (for example Merkle Tree Certificates). Private PKI (service mesh, IoT, internal mTLS, code signing) is where you can start, especially for long-lived roots.
Steps
- Inventory certificates and their lifetimes:
npx -y pqe-cli scan .finds certificates and keys in repositories; also export from your CA and secret stores. - Start with a lab CA hierarchy using ML-DSA-87 (root) and ML-DSA-65 (intermediate / leaf), and test every relying party.
- Keep classical chains in parallel until all clients can validate ML-DSA (dual hierarchies, or separate endpoints).
- Plan HSM support for the root key before production.
Before
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.pem -days 3650 -subj "/CN=Example Root"After
# Root CA
openssl req -x509 -newkey ML-DSA-87 -nodes -keyout root.key -out root.pem \
-days 3650 -subj "/CN=Example PQ Root" \
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign"
# Leaf key + CSR, signed by the root
openssl req -new -newkey ML-DSA-65 -nodes -keyout leaf.key -out leaf.csr -subj "/CN=svc.internal"
openssl x509 -req -in leaf.csr -CA root.pem -CAkey root.key -days 90 -out leaf.pem \
-extfile <(printf "subjectAltName=DNS:svc.internal\nextendedKeyUsage=serverAuth")
openssl x509 -in leaf.pem -noout -text | grep "Signature Algorithm" # ML-DSA-87 (issuer's)
openssl verify -CAfile root.pem leaf.pemGotchas
- Client support is the bottleneck. TLS stacks, language runtimes, proxies, browsers and HSMs must all understand ML-DSA. Today that means OpenSSL 3.5+, BoringSSL/AWS-LC-based stacks, Go 1.27+ (
crypto/x509, TLS 1.3 signature schemes), pyca/cryptography 49+, .NET 10 (with OS support) and others; test each. - ML-DSA in TLS needs TLS 1.3.
- Size. Each ML-DSA-65 certificate carries a ~1.9 KB public key and a 3.3 KB signature; a three-certificate chain adds roughly 10-15 KB to every full handshake. Keep chains short.
- Composite / hybrid certificates (ML-DSA combined with RSA or ECDSA in one certificate) are being standardised in the IETF LAMPS working group; tooling support varies.
- Revocation and CT infrastructure (OCSP responders, CRL tooling, logs) must also handle the new algorithms.
Verify
openssl verify as above, then connect each real client (curl, your service mesh sidecar, your SDKs) to a test server presenting the ML-DSA chain.
.NET 10 System.Security.Cryptography · csharp.NET: ML-KEM and ML-DSA in .NET 10 (MLKem, MLDsa)Production-ready
Why
.NET 10 (LTS, November 2025) added post-quantum types to System.Security.Cryptography: MLKem (FIPS 203), MLDsa (FIPS 204), SlhDsa (FIPS 205) and CompositeMLDsa (IETF draft). They are thin wrappers over the operating system's cryptography: Windows CNG on recent Windows 11 / Windows Server builds, and OpenSSL 3.5 or newer on Linux. The Microsoft.Bcl.Cryptography package brings the same API surface to older target frameworks.
Status in .NET 10: MLKem and MLDsa are supported at the class level (a few members, such as some PKCS#8/SPKI import-export helpers and ML-DSA pre-hash signing, are still marked [Experimental]), while SlhDsa and CompositeMLDsa are [Experimental] (diagnostic SYSLIB5006).
Steps
- Target
net10.0(or referenceMicrosoft.Bcl.Cryptographyfor older targets). - Check
MLKem.IsSupported/MLDsa.IsSupportedat startup and log the result: support depends on the OS and its crypto library. - Replace RSA-OAEP/ECDH key wrapping with
MLKem, and RSA/ECDSA signatures withMLDsa, keeping algorithm identifiers next to stored data.
Before
using var rsa = RSA.Create(2048);
byte[] wrapped = rsa.Encrypt(dataKey, RSAEncryptionPadding.OaepSHA256);
using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
byte[] sig = ecdsa.SignData(data, HashAlgorithmName.SHA256);After
using System.Security.Cryptography;
if (!MLKem.IsSupported || !MLDsa.IsSupported)
throw new PlatformNotSupportedException("Needs Windows with PQC support or Linux with OpenSSL 3.5+");
// ML-KEM-768
using MLKem receiver = MLKem.GenerateKey(MLKemAlgorithm.MLKem768);
byte[] encapsulationKey = receiver.ExportEncapsulationKey(); // 1184 bytes, publish this
using MLKem sender = MLKem.ImportEncapsulationKey(MLKemAlgorithm.MLKem768, encapsulationKey);
sender.Encapsulate(out byte[] ciphertext, out byte[] senderSecret); // 1088-byte ciphertext, 32-byte secret
byte[] receiverSecret = receiver.Decapsulate(ciphertext);
// Derive the AES-256-GCM key: HKDF.DeriveKey(HashAlgorithmName.SHA256, receiverSecret, 32, info: "myapp/seal/v1"u8.ToArray())
// ML-DSA-65
using MLDsa signer = MLDsa.GenerateKey(MLDsaAlgorithm.MLDsa65);
byte[] signature = signer.SignData(data); // 3309 bytes
bool ok = signer.VerifyData(data, signature);
byte[] publicKey = signer.ExportMLDsaPublicKey(); // 1952 bytesGotchas
- Platform support varies. macOS is not supported in .NET 10; Linux needs OpenSSL 3.5+ (older LTS distributions ship 3.0); Windows needs a build with PQC in CNG. Always branch on
IsSupported. - TLS is separate.
SslStreamuses the OS TLS stack (SChannel on Windows, OpenSSL on Linux), so hybrid key exchange follows the OS and its configuration, not these classes. ML-DSA certificates in TLS need TLS 1.3 and support on both ends. - Experimental members raise SYSLIB5006 warnings; avoid depending on them in production code until they are stable.
- Dispose keys (
using) so native handles and key material are released. - Sizes: plan storage and message limits for 3.3 KB signatures and ~1.1 KB ciphertexts.
Verify
Console.WriteLine(senderSecret.AsSpan().SequenceEqual(receiverSecret)); // True
Console.WriteLine($"{ciphertext.Length} {signature.Length}"); // 1088 3309Go crypto/mlkem (1.24+), crypto/mldsa (1.27+) · goGo: application-level ML-KEM (crypto/mlkem) and ML-DSA (crypto/mldsa) in the standard libraryProduction-ready
Why
Go ships post-quantum primitives in the standard library: crypto/mlkem (ML-KEM-768 and ML-KEM-1024, FIPS 203) since Go 1.24, and crypto/mldsa (ML-DSA-44/65/87, FIPS 204) since Go 1.27, which also taught crypto/x509 and crypto/tls about ML-DSA. Go 1.24 also added crypto/hkdf, which you need to turn shared secrets into keys. Go 1.26 added crypto/hpke with post-quantum hybrid KEMs, which is the best choice if you need public-key encryption of messages.
Steps
- Upgrade the toolchain (
go 1.24for ML-KEM,go 1.27for ML-DSA ingo.mod). - Replace RSA-OAEP / ECDH key wrapping with ML-KEM (ideally hybrid with X25519, or use
crypto/hpke). - Replace ECDSA/Ed25519 signing with ML-DSA where verifiers can be upgraded; keep an algorithm identifier with every signature.
Before
priv, _ := ecdh.X25519().GenerateKey(rand.Reader)
peer, _ := ecdh.X25519().GenerateKey(rand.Reader)
shared, _ := priv.ECDH(peer.PublicKey()) // quantum-vulnerable
sk, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
sig, _ := ecdsa.SignASN1(rand.Reader, sk, digest[:])After: ML-KEM-768 key encapsulation
import (
"crypto/hkdf"
"crypto/mlkem"
"crypto/sha256"
)
// Receiver
dk, err := mlkem.GenerateKey768()
if err != nil { return err }
ekBytes := dk.EncapsulationKey().Bytes() // 1184 bytes, send to the sender
// Sender
ek, err := mlkem.NewEncapsulationKey768(ekBytes)
if err != nil { return err }
sharedKey, ciphertext := ek.Encapsulate() // 32-byte secret, 1088-byte ciphertext
// Receiver
recovered, err := dk.Decapsulate(ciphertext)
if err != nil { return err }
// Derive the actual AES-256-GCM key from the secret
aesKey, err := hkdf.Key(sha256.New, recovered, nil, "myapp/seal/v1", 32)
_ = sharedKeyAfter: ML-DSA-65 signatures (Go 1.27+)
import "crypto/mldsa"
sk, err := mldsa.GenerateKey(mldsa.MLDSA65())
if err != nil { return err }
pubBytes := sk.PublicKey().Bytes() // 1952 bytes
opts := &mldsa.Options{Context: "myapp/release/v1"}
sig, err := sk.Sign(nil, msg, opts) // 3309 bytes
if err != nil { return err }
pk, err := mldsa.NewPublicKey(mldsa.MLDSA65(), pubBytes)
if err != nil { return err }
if err := mldsa.Verify(pk, msg, sig, opts); err != nil { return err }Gotchas
- Store the seed.
dk.Bytes()returns the 64-byte seed form of an ML-KEM decapsulation key; recreate it withmlkem.NewDecapsulationKey768(seed). ML-DSAPrivateKey.Bytes()/mldsa.NewPrivateKey(params, seed)work the same way with a 32-byte seed. - Context strings must match between
SignandVerify. - Hybrid. Plain ML-KEM is standard-compliant, but for new protocols during the transition a hybrid (X25519 + ML-KEM, e.g. via
crypto/hpke) is the conservative choice. - FIPS module versions.
crypto/mldsais unavailable when Go is pinned to the FIPS 140-3 Go Cryptographic Module v1.0.0; it works with module v1.26.0 or later. - Sizes (ML-KEM-768 ciphertext 1,088 B; ML-DSA-65 signature 3,309 B) affect wire formats and storage.
- Older Go?
github.com/cloudflare/circlprovides ML-KEM and ML-DSA for toolchains before 1.24/1.27.
Verify
if !bytes.Equal(sharedKey, recovered) { log.Fatal("ML-KEM mismatch") }
fmt.Println(len(ciphertext), len(sig)) // 1088 3309JDK (java.security / javax.crypto), JDK 24+ · javaJava: ML-KEM and ML-DSA in the JDK (JEP 496 / JEP 497, JDK 24+, LTS in JDK 25)Production-ready
Why
Since JDK 24, the JDK's built-in providers implement ML-KEM (JEP 496, FIPS 203) through the javax.crypto.KEM API and ML-DSA (JEP 497, FIPS 204) through the familiar KeyPairGenerator / Signature APIs. JDK 25 is the first long-term-support release that includes them, so most teams can adopt them without third-party libraries.
Steps
- Run on JDK 25 (LTS) or later. On JDK 21 or older, use Bouncy Castle (see that guide).
- Replace RSA-OAEP key wrapping / ECDH with ML-KEM-768 via
KEM. - Replace
SHA256withECDSA/Ed25519/SHA256withRSAsignatures withML-DSAwhere verifiers can be upgraded. Keep an algorithm identifier next to stored signatures.
Before
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
Cipher oaep = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
oaep.init(Cipher.WRAP_MODE, kp.getPublic());
byte[] wrapped = oaep.wrap(dataKey);
Signature s = Signature.getInstance("SHA256withECDSA");After: ML-KEM-768
import java.security.*;
import java.security.spec.NamedParameterSpec;
import javax.crypto.KEM;
import javax.crypto.SecretKey;
KeyPairGenerator g = KeyPairGenerator.getInstance("ML-KEM");
g.initialize(NamedParameterSpec.ML_KEM_768);
KeyPair kp = g.generateKeyPair(); // or KeyPairGenerator.getInstance("ML-KEM-768")
KEM kem = KEM.getInstance("ML-KEM");
// Sender
KEM.Encapsulator enc = kem.newEncapsulator(kp.getPublic());
KEM.Encapsulated e = enc.encapsulate();
SecretKey senderKey = e.key(); // 32-byte shared secret
byte[] ciphertext = e.encapsulation(); // 1088 bytes, send to the receiver
// Receiver
KEM.Decapsulator dec = kem.newDecapsulator(kp.getPrivate());
SecretKey receiverKey = dec.decapsulate(ciphertext);
// Derive an AES-256-GCM key from the secret (for example with HKDF; JDK 25 adds javax.crypto.KDF).After: ML-DSA-65
KeyPairGenerator g = KeyPairGenerator.getInstance("ML-DSA-65");
KeyPair kp = g.generateKeyPair();
Signature signer = Signature.getInstance("ML-DSA");
signer.initSign(kp.getPrivate());
signer.update(message);
byte[] sig = signer.sign(); // 3309 bytes
Signature verifier = Signature.getInstance("ML-DSA");
verifier.initVerify(kp.getPublic());
verifier.update(message);
boolean ok = verifier.verify(sig);Gotchas
- TLS is separate. These APIs do not change JSSE. Hybrid post-quantum TLS arrived in JDK 27 (JEP 527); see the Java TLS guide.
- Keystores and HSMs. PKCS#12 keystores can hold the keys, but PKCS#11 HSMs need vendor support for ML-KEM/ML-DSA mechanisms. Check before moving production signing keys.
- Sizes. ML-KEM-768 ciphertext 1,088 B, public key 1,184 B; ML-DSA-65 signature 3,309 B, public key 1,952 B. Check
VARBINARYcolumns and message formats. - Encoded keys.
getEncoded()returns X.509 SubjectPublicKeyInfo / PKCS#8 encodings using the NIST OIDs; check interoperability with other stacks (OpenSSL 3.5+, Go, .NET). - Do not confuse with pre-standard Kyber/Dilithium classes from older Bouncy Castle versions.
Verify
assert java.util.Arrays.equals(senderKey.getEncoded(), receiverKey.getEncoded());
assert ciphertext.length == 1088 && sig.length == 3309;Bouncy Castle (bcprov) · javaJava on older JDKs: ML-KEM, ML-DSA and SLH-DSA with Bouncy Castle (1.79+)Production-ready
Why
If you are on JDK 21 or older, the JDK has no ML-KEM/ML-DSA. Bouncy Castle added the final FIPS 203/204/205 algorithms (ML-KEM, ML-DSA, SLH-DSA, including pre-hash variants) in 1.79 (October 2024) and has continued to add encodings, CMS and certificate support since. It plugs into the standard JCA APIs, so the code looks like the JDK 24+ code.
Steps
- Add
org.bouncycastle:bcprov-jdk18on(andbcpkix-jdk18onfor certificates/CMS) at a current version, at least 1.79. - Register the provider once at startup.
- Use the same
KeyPairGenerator,KEM/KeyGeneratorandSignaturepatterns as the JDK guide, naming theBCprovider.
Before
Signature s = Signature.getInstance("SHA256withECDSA");After
import java.security.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jcajce.spec.MLDSAParameterSpec;
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ML-DSA", "BC");
kpg.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom());
KeyPair kp = kpg.generateKeyPair();
Signature sig = Signature.getInstance("ML-DSA", "BC");
sig.initSign(kp.getPrivate());
sig.update(message);
byte[] signature = sig.sign();For ML-KEM, use KeyPairGenerator.getInstance("ML-KEM", "BC") with MLKEMParameterSpec.ml_kem_768, then wrap or derive keys via Bouncy Castle's KEM support (KeyGenerator with KEMGenerateSpec/KEMExtractSpec) or, on JDK 21+, the javax.crypto.KEM API if your BC version provides a KEM SPI. Check the BC documentation for the version you install, as these APIs have evolved.
Gotchas
- Old class names. Pre-1.79 BC exposed
Kyber/Dilithium(round 3), which are not compatible with ML-KEM/ML-DSA. Search forKyberParameterSpec,DilithiumParameterSpecand migrate. - FIPS. The general BC provider is not FIPS-validated; the separate BC-FJA (FIPS) distribution has its own release schedule for PQC.
- Sizes are the same as everywhere else (ML-DSA-65 signature 3,309 B).
- Keep provider choice in configuration so you can move to the JDK's built-in implementation when you upgrade to JDK 25+.
Verify
Signature v = Signature.getInstance("ML-DSA", "BC");
v.initVerify(kp.getPublic());
v.update(message);
System.out.println(v.verify(signature) + " " + signature.length); // true 3309JOSE / JWT libraries (e.g. jose) · javascriptJWT/JOSE: what the post-quantum state is, and how to get ready without breaking loginsExperimental
Why
JWTs signed with RS256/PS256 or ES256/EdDSA can be forged once a large quantum computer can recover the issuer's private key from its published JWKS. Tokens are short-lived, so this is not a harvest-now-decrypt-later problem: the deadline is "before such a machine exists", not today. But identity systems are slow to change, so preparation pays off.
State of standards (late 2026):
- RFC 9964 ("ML-DSA for JOSE and COSE", 2026) registers the JWS algorithms
ML-DSA-44,ML-DSA-65andML-DSA-87and a new JWK key typeAKP(Algorithm Key Pair). - Composite (hybrid) ML-DSA + ECDSA/EdDSA signatures for JOSE/COSE are still an IETF draft (draft-ietf-jose-pq-composite-sigs).
- Library support is emerging. For example, the
josenpm package supports the ML-DSA JWS identifiers since v6.1.0 where the JavaScript runtime's WebCrypto implements ML-DSA. Most identity providers, API gateways and OIDC client libraries do not yet issue or accept ML-DSA tokens.
Steps
- Inventory issuers and verifiers:
npx -y pqe-cli scan .flags RS*/ES*/HS* usage. List every service that validates your tokens. - Make algorithms configuration, not code. Verifiers should take an allow-list of algorithms and fetch keys from a JWKS by
kid. Never acceptalgblindly from the token header (RFC 8725). - Practise key rotation now (publish a new
kid, sign with it, retire the old one). The PQ migration is a rotation where the new key has a new algorithm. - First-party tokens: if the issuer and verifier are the same organisation and can share a secret,
HS256with a random 256-bit secret is already quantum-safe. - Pilot ML-DSA where both ends are yours: add
ML-DSA-65(orML-DSA-44if size matters) to verifier allow-lists, publish an AKP key in the JWKS, then switch signing. - Third-party IdPs (Auth0/Okta/Entra/Cognito/Keycloak...): track their roadmaps; keep your verifiers ready to accept new algorithms.
Before
import { SignJWT, jwtVerify, createRemoteJWKSet } from 'jose';
const token = await new SignJWT({ sub: 'user-1' })
.setProtectedHeader({ alg: 'RS256', kid: 'rsa-2024' })
.setExpirationTime('15m')
.sign(rsaPrivateKey);
const JWKS = createRemoteJWKSet(new URL('https://issuer.example/.well-known/jwks.json'));
await jwtVerify(token, JWKS); // accepts whatever alg the key allowsAfter (agile verifier; ML-DSA where supported)
import { SignJWT, jwtVerify, createRemoteJWKSet, generateKeyPair } from 'jose';
// Verifier: explicit allow-list that can grow without a code change
const ALLOWED = (process.env.JWT_ALGS ?? 'RS256,ML-DSA-65').split(',');
const JWKS = createRemoteJWKSet(new URL('https://issuer.example/.well-known/jwks.json'));
const { payload } = await jwtVerify(token, JWKS, { algorithms: ALLOWED, issuer: 'https://issuer.example' });
// Issuer (pilot): requires a jose version and runtime with ML-DSA support (e.g. recent Node 24+)
const { privateKey } = await generateKeyPair('ML-DSA-65');
const pqToken = await new SignJWT({ sub: 'user-1' })
.setProtectedHeader({ alg: 'ML-DSA-65', kid: 'mldsa-2026' })
.setExpirationTime('15m')
.sign(privateKey);Gotchas
- Size. An ML-DSA-65 signature is 3,309 bytes, about 4.4 KB once base64url-encoded, against 342 characters for RS256. Tokens in cookies (4 KB browser limit per cookie) or HTTP headers (proxies often cap total headers at 8-16 KB) may break. ML-DSA-44 is smaller (2,420-byte signatures) but still large; consider reference tokens or token exchange at the edge.
- JWKS size grows too: an ML-DSA-65 public key is 1,952 bytes.
- Do not invent algorithm names. Use the registered
ML-DSA-44/65/87identifiers from RFC 9964; pre-RFC drafts used other names and key types. - Encrypted JWTs (JWE) with
RSA-OAEPorECDH-ESkey management are a harvest-now-decrypt-later risk if tokens carry sensitive data and are stored; prefer not putting secrets in tokens, or plan PQ key management once standardised for JOSE. - HS256 pitfalls: weak or shared-everywhere secrets, and algorithm-confusion bugs; follow RFC 8725.
Verify
Decode a token header (echo $TOKEN | cut -d. -f1 | base64 -d) to see alg and kid, run your verifier tests with both the classical and the ML-DSA key in the JWKS, and measure the largest token size against your cookie and header limits.
node:crypto / @noble/post-quantum · javascriptNode.js: sign and verify with ML-DSA-65 (node:crypto on Node 24.6+, or @noble/post-quantum)Production-ready
Why
ECDSA, Ed25519 and RSA signatures will be forgeable once a large quantum computer exists. Signatures are not exposed to "harvest now, decrypt later", but anything that must stay trustworthy for years (software updates, firmware, documents, long-lived API keys, internal PKI) needs a post-quantum path. ML-DSA (FIPS 204) is the standard general-purpose replacement; ML-DSA-65 is the common default.
Node.js supports ML-DSA natively in node:crypto from 24.6.0 (key generation, crypto.sign, crypto.verify) when built with OpenSSL 3.5+, which all official Node 24 and 26 builds are. @noble/post-quantum works on any runtime, including Node 22 and browsers.
Steps
- Add an algorithm identifier to everything you sign (a header field, a key ID that maps to an algorithm), so verifiers know which algorithm to use. This is the crypto-agility step that makes later swaps cheap.
- Generate an ML-DSA-65 key pair and distribute the public key alongside (not instead of) the old one.
- Sign new artifacts with ML-DSA, or with both algorithms during the transition ("dual signing"); teach verifiers to accept either.
- Once all verifiers understand ML-DSA, stop issuing classical signatures.
Before
import { generateKeyPairSync, sign, verify } from 'node:crypto';
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
const sig = sign(null, data, privateKey); // 64 bytes
const ok = verify(null, data, publicKey, sig);After: node:crypto (Node 24.6+)
import { generateKeyPairSync, sign, verify } from 'node:crypto';
const { publicKey, privateKey } = generateKeyPairSync('ml-dsa-65');
const sig = sign(null, data, privateKey); // algorithm must be null/undefined: 3309 bytes
const ok = verify(null, data, publicKey, sig);
// Optional domain separation (FIPS 204 "context", up to 255 bytes; Node 24.8+):
const sig2 = sign(null, data, { key: privateKey, context: Buffer.from('myapp/release/v1') });
verify(null, data, { key: publicKey, context: Buffer.from('myapp/release/v1') }, sig2);
// Keys export as usual
const spkiPem = publicKey.export({ type: 'spki', format: 'pem' });After: @noble/post-quantum (any runtime)
import { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js';
const keys = ml_dsa65.keygen(); // publicKey 1952 B, secretKey 4032 B
const sig = ml_dsa65.sign(data, keys.secretKey); // 0.5.x argument order: (message, secretKey)
const ok = ml_dsa65.verify(sig, data, keys.publicKey);Gotchas
- Size. ML-DSA-65 signatures are 3,309 bytes and public keys 1,952 bytes, against 64 and 32 bytes for Ed25519 and 256 bytes for an RSA-2048 signature. Check HTTP header limits (many proxies cap headers at 8-16 KB), JWT/cookie sizes, database columns (
VARBINARY(256)will not do) and QR codes. - Need tiny signatures or extreme conservatism? FN-DSA (Falcon, FIPS 206) will give ~666-byte signatures but is not final yet. SLH-DSA (FIPS 205) relies only on hashes but signatures are 7.8-50 KB.
- Context strings must match on both sides, or verification fails.
- Pre-hash variants (HashML-DSA) are different algorithms with different signatures; use plain ML-DSA unless a protocol requires otherwise.
- HSM/KMS support for ML-DSA is arriving but uneven; check your provider before moving signing keys.
- Verifiers first. Roll out verification support everywhere before switching signers, otherwise old clients reject new artifacts.
Verify
import assert from 'node:assert';
assert.equal(sig.length, 3309);
assert.ok(verify(null, data, publicKey, sig));
assert.ok(!verify(null, Buffer.from('tampered'), publicKey, sig));any (design pattern) · typescriptCrypto-agility: put cryptography behind an interface so the post-quantum swap is a config changeProduction-ready
Why
Most of the cost of a cryptographic migration is not the new algorithm, it is finding and changing every place that hard-codes the old one: RSA.generate(2048) in five services, signatures stored without saying which algorithm made them, database columns sized for 256-byte signatures. Crypto-agility means you can change algorithms through configuration and a rollout, not a rewrite. NIST's guidance on the post-quantum transition (NIST IR 8547, and its crypto-agility work in CSWP 39) treats it as a core requirement because more transitions will follow.
The pattern
- One module owns cryptography. Application code calls
seal(),open(),sign(),verify(), never a library primitive directly. - Every output is self-describing. Ciphertexts, signatures and keys carry an algorithm identifier (and key ID) in a versioned envelope.
- Verifiers/decryptors accept a set; producers use one. Readers support old and new algorithms during the transition; writers switch by configuration.
- Keys are looked up by ID from a key store or KMS, so rotating keys and algorithms is the same operation.
- Sizes are not assumed. Storage and protocols allow kilobyte-sized keys, ciphertexts and signatures.
Before
import { sign as edSign, createPrivateKey } from 'node:crypto';
// Algorithm and key format hard-coded at every call site; signature stored bare.
const sig = edSign(null, payload, createPrivateKey(process.env.SIGNING_KEY!));
await db.insert({ payload, sig: sig.toString('base64') });After
// crypto/signer.ts: the only file that knows algorithms.
import { sign, verify, KeyObject } from 'node:crypto';
export type SigAlg = 'Ed25519' | 'ML-DSA-65';
export interface SignedEnvelope { v: 1; alg: SigAlg; kid: string; sig: string } // base64
interface KeyRecord { kid: string; alg: SigAlg; privateKey?: KeyObject; publicKey: KeyObject }
export class Signer {
constructor(
private readonly keys: Map<string, KeyRecord>,
private readonly activeKid: string, // from configuration
private readonly acceptAlgs: Set<SigAlg>, // from configuration
) {}
sign(data: Buffer): SignedEnvelope {
const k = this.keys.get(this.activeKid)!;
// Ed25519 and ML-DSA both take a null digest in node:crypto (ML-DSA: Node 24.6+)
return { v: 1, alg: k.alg, kid: k.kid, sig: sign(null, data, k.privateKey!).toString('base64') };
}
verify(data: Buffer, env: SignedEnvelope): boolean {
if (!this.acceptAlgs.has(env.alg)) return false;
const k = this.keys.get(env.kid);
if (!k || k.alg !== env.alg) return false; // never trust alg without the key's own record
return verify(null, data, k.publicKey, Buffer.from(env.sig, 'base64'));
}
}
// Call sites never mention an algorithm:
const env = signer.sign(payload);
await db.insert({ payload, signature: JSON.stringify(env) }); // TEXT/JSONB column, not VARCHAR(100)Migration then becomes: deploy verifiers with acceptAlgs = {Ed25519, ML-DSA-65} → add an ML-DSA key → switch activeKid → re-sign or expire old data → drop Ed25519 from acceptAlgs.
Gotchas
- Do not let the message choose the algorithm. The verifier must check that the key ID's registered algorithm matches the envelope (JWT "alg confusion" bugs come from skipping this).
- Downgrade protection. Once everything supports the new algorithm, remove the old one from the accept list; otherwise attackers who can forge the old one still win.
- Hybrid/dual signatures (both classical and PQ) fit the same envelope:
alg: 'Ed25519+ML-DSA-65'with two signatures, verified with AND semantics. - Inventory first. You can't wrap what you haven't found:
npx -y pqe-cli scan . --cbom -o cbom.jsonproduces a CycloneDX cryptography bill of materials to track progress. - Sizes: ML-DSA-65 signatures are 3,309 bytes; ML-KEM-768 ciphertexts 1,088 bytes. Use TEXT/BLOB/JSONB columns, and test message-size limits (queues, headers, cookies, MTU-sensitive UDP protocols).
Verify
Write a test that signs with one algorithm and verifies after flipping activeKid, and a test that an envelope claiming an algorithm not registered for its kid is rejected. Re-run npx -y pqe-cli scan . and confirm crypto primitives appear only in the crypto module.
any (OpenSSL, node:crypto, cryptography, JCA, Go) · otherRSA keys under 2048 bits (and DSA, small DH groups): replace them nowProduction-ready
Why
RSA-1024 gives about 80 bits of security and NIST disallowed it for signatures and key establishment back in 2013. 512-bit keys are factored routinely; 1024-bit keys are assumed breakable by well-resourced attackers. DSA is no longer approved for signing in FIPS 186-5, and Diffie-Hellman groups under 2048 bits are weak (Logjam). These are classical failures: fix them now, without waiting for post-quantum tooling.
Where to go:
- Key exchange / encryption: hybrid X25519MLKEM768 in TLS, ML-KEM-768 at the application level.
- Signatures: ML-DSA-65 where your stack supports it.
- If PQ isn't available yet in a given system: RSA-3072 (128-bit classical) or ECDSA P-256 / Ed25519 as a stopgap, accepting a second migration later.
Before
openssl genrsa -out key.pem 1024
ssh-keygen -t rsa -b 1024
ssh-keygen -t dsacrypto.generateKeyPairSync('rsa', { modulusLength: 1024 });rsa.generate_private_key(public_exponent=65537, key_size=1024)After
# Post-quantum where supported (OpenSSL 3.5+)
openssl genpkey -algorithm ML-DSA-65 -out sign.key
openssl genpkey -algorithm ML-KEM-768 -out kem.key
# Classical stopgap
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out key.pem
ssh-keygen -t ed25519crypto.generateKeyPairSync('ml-dsa-65'); // Node 24.6+
crypto.generateKeyPairSync('rsa', { modulusLength: 3072 }); // stopgapfrom cryptography.hazmat.primitives.asymmetric.mldsa import MLDSA65PrivateKey
MLDSA65PrivateKey.generate() # cryptography 48+Gotchas
- Find them all: keys in repositories, HSMs, certificates (
openssl x509 -noout -text | grep "Public-Key"), SSHauthorized_keys, and embedded devices.npx -y pqe-cli scan .reports small RSA keys in code and PEM files. - Rotate, don't just regenerate: issue new keys, distribute public keys, re-sign/re-encrypt what depends on the old ones, then revoke.
- Data encrypted under small RSA keys should be treated as potentially exposed; re-encrypt and consider whether it was already captured.
- Legacy peers that only speak RSA-1024 or DSA are themselves a risk; isolate or replace them.
Verify
openssl pkey -in key.pem -noout -text | head -1 shows the algorithm and size; rerun npx -y pqe-cli scan . to confirm no rsa-1024/dsa findings remain.
cryptography (pyca) · pythonPython: sign and verify with ML-DSA-65 in pyca/cryptography (48+)Production-ready
Why
RSA, ECDSA and Ed25519 signatures become forgeable once a large quantum computer exists. ML-DSA (FIPS 204) is the standard replacement. pyca/cryptography added an ML-DSA module in 47.0.0 (AWS-LC/BoringSSL) and OpenSSL 3.5+ backend support in 48.0.0; 49.0.0 added X.509 certificate/CSR/CRL signing with ML-DSA keys, and 50.0.0 lets the X.509 verification APIs accept ML-DSA-44/65/87 (RFC 9881).
Steps
pip install -U "cryptography>=48"(49+ if you need ML-DSA certificates).- Put an algorithm identifier next to every stored signature so verifiers can support both old and new algorithms during the transition.
- Generate an ML-DSA-65 key, distribute the public key, and dual-sign (classical + ML-DSA) until all verifiers are upgraded.
Before
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
key = Ed25519PrivateKey.generate()
sig = key.sign(b"release-1.2.3.tar.gz digest") # 64 bytes
key.public_key().verify(sig, b"release-1.2.3.tar.gz digest")After
from cryptography.hazmat.primitives.asymmetric.mldsa import MLDSA65PrivateKey, MLDSA65PublicKey
from cryptography.hazmat.primitives import serialization
key = MLDSA65PrivateKey.generate()
msg = b"release-1.2.3.tar.gz digest"
sig = key.sign(msg, context=b"myapp/release/v1") # 3309 bytes; context is optional
pub = key.public_key()
pub.verify(sig, msg, context=b"myapp/release/v1") # raises InvalidSignature on failure
# Distribute / store
pub_raw = pub.public_bytes_raw() # 1952 bytes
pub_pem = pub.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
seed = key.private_bytes_raw() # 32-byte seed; protect it like any private key
same_key = MLDSA65PrivateKey.from_seed_bytes(seed)Gotchas
- Sizes. Signature 3,309 bytes, public key 1,952 bytes. Check column types, message limits and anything that embeds signatures in URLs or headers.
- Context must match between signer and verifier.
- Seed-only private keys.
private_bytes*returns the seed form; some other tools expect the expanded key. Test interoperability with whatever else reads your keys (HSMs, OpenSSL, Go, Java). - Backend. A
cryptographylinked against an older system OpenSSL raisesUnsupportedAlgorithm. - Large messages. For huge files, sign a SHA-512 digest with a clear domain label, or use the external-mu API (
sign_mu,MLDSAMuHasher, 49+/50+) if you need streaming.
Verify
from cryptography.exceptions import InvalidSignature
try:
pub.verify(sig, b"tampered", context=b"myapp/release/v1")
raise SystemExit("should not verify")
except InvalidSignature:
print("ok", len(sig)) # ok 3309liboqs-python (Open Quantum Safe) · pythonPython: prototype post-quantum algorithms with liboqs-pythonExperimental
Why
liboqs-python wraps liboqs from the Open Quantum Safe project. It exposes many algorithms (ML-KEM, ML-DSA, SLH-DSA, Falcon, HQC, Classic McEliece, ...) behind one API, which makes it useful for experiments, benchmarks and interoperability tests. The OQS project itself describes liboqs as intended for research and prototyping, not production. For production Python code prefer pyca/cryptography 48+ (ML-KEM, ML-DSA).
Steps
- Install liboqs (the C library) and then
pip install liboqs-python, following the project's README; the wrapper needs a matching liboqs shared library. - List what your build supports:
oqs.get_enabled_kem_mechanisms(),oqs.get_enabled_sig_mechanisms(). - Use the FIPS names (
"ML-KEM-768","ML-DSA-65"), not the pre-standard"Kyber768"/"Dilithium3".
Before
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
a, b = X25519PrivateKey.generate(), X25519PrivateKey.generate()
shared = a.exchange(b.public_key())After
import oqs
# Key encapsulation
with oqs.KeyEncapsulation("ML-KEM-768") as receiver, oqs.KeyEncapsulation("ML-KEM-768") as sender:
public_key = receiver.generate_keypair()
ciphertext, ss_sender = sender.encap_secret(public_key)
ss_receiver = receiver.decap_secret(ciphertext)
assert ss_sender == ss_receiver
# Signatures
message = b"hello"
with oqs.Signature("ML-DSA-65") as signer, oqs.Signature("ML-DSA-65") as verifier:
signer_public_key = signer.generate_keypair()
signature = signer.sign(message)
assert verifier.verify(message, signature, signer_public_key)Gotchas
- Not for production according to its maintainers; no FIPS validation.
- Algorithm availability depends on build flags; check the enabled lists rather than assuming.
- Secret key export:
export_secret_key()returns raw bytes that you must protect yourself. - Use it to test sizes and speed, then move the real implementation to a maintained library.
Verify
import oqs
print("ML-KEM-768" in oqs.get_enabled_kem_mechanisms(), "ML-DSA-65" in oqs.get_enabled_sig_mechanisms())