Skip to content
Already broken todayrsa-1024

RSA with keys under 2048 bits

RSA with a 1024-bit (or smaller) modulus, which is too weak even against ordinary computers.

Used for
Public-key encryption
Family
RSA (integer factorisation)
Classical security
80 bits
Against a quantum computer
Broken
Standards
NIST SP 800-131A Rev. 2, NIST SP 800-57 Part 1 Rev. 5
Read the guideHow public-key cryptography works

Migration guides

Concrete code changes to move off RSA with keys under 2048 bits. 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

  1. Link against OpenSSL 3.5 or later and check the version at runtime.
  2. Generate keys with EVP_PKEY_Q_keygen(NULL, NULL, "ML-KEM-768") / "ML-DSA-65".
  3. Encapsulate/decapsulate with the EVP KEM API; sign with EVP_PKEY_sign_message_init + EVP_PKEY_sign (or EVP_DigestSign* as for Ed25519).
  4. Store keys as PKCS#8/SPKI PEM (PEM_write_bio_PrivateKey, PEM_write_bio_PUBKEY).

Before

c
EVP_PKEY *rsa = EVP_RSA_gen(2048);
/* ... EVP_PKEY_encrypt with RSA-OAEP to wrap a data key ... */

After: ML-KEM-768 encapsulation

c
#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

c
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

bash
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-secret

Gotchas

  • 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_seed and ml-kem.prefer_seed control 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

bash
openssl list -kem-algorithms | grep -i ml-kem
openssl list -signature-algorithms | grep -i ml-dsa
.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

  1. Target net10.0 (or reference Microsoft.Bcl.Cryptography for older targets).
  2. Check MLKem.IsSupported / MLDsa.IsSupported at startup and log the result: support depends on the OS and its crypto library.
  3. Replace RSA-OAEP/ECDH key wrapping with MLKem, and RSA/ECDSA signatures with MLDsa, keeping algorithm identifiers next to stored data.

Before

csharp
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

csharp
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 bytes

Gotchas

  • 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. SslStream uses 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

csharp
Console.WriteLine(senderSecret.AsSpan().SequenceEqual(receiverSecret)); // True
Console.WriteLine($"{ciphertext.Length} {signature.Length}");          // 1088 3309
Go 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

  1. Upgrade the toolchain (go 1.24 for ML-KEM, go 1.27 for ML-DSA in go.mod).
  2. Replace RSA-OAEP / ECDH key wrapping with ML-KEM (ideally hybrid with X25519, or use crypto/hpke).
  3. Replace ECDSA/Ed25519 signing with ML-DSA where verifiers can be upgraded; keep an algorithm identifier with every signature.

Before

go
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

go
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)
_ = sharedKey

After: ML-DSA-65 signatures (Go 1.27+)

go
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 with mlkem.NewDecapsulationKey768(seed). ML-DSA PrivateKey.Bytes() / mldsa.NewPrivateKey(params, seed) work the same way with a 32-byte seed.
  • Context strings must match between Sign and Verify.
  • 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/mldsa is 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/circl provides ML-KEM and ML-DSA for toolchains before 1.24/1.27.

Verify

go
if !bytes.Equal(sharedKey, recovered) { log.Fatal("ML-KEM mismatch") }
fmt.Println(len(ciphertext), len(sig)) // 1088 3309
JDK (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

  1. Run on JDK 25 (LTS) or later. On JDK 21 or older, use Bouncy Castle (see that guide).
  2. Replace RSA-OAEP key wrapping / ECDH with ML-KEM-768 via KEM.
  3. Replace SHA256withECDSA / Ed25519 / SHA256withRSA signatures with ML-DSA where verifiers can be upgraded. Keep an algorithm identifier next to stored signatures.

Before

java
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

java
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

java
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 VARBINARY columns 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

java
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

  1. Add org.bouncycastle:bcprov-jdk18on (and bcpkix-jdk18on for certificates/CMS) at a current version, at least 1.79.
  2. Register the provider once at startup.
  3. Use the same KeyPairGenerator, KEM/KeyGenerator and Signature patterns as the JDK guide, naming the BC provider.

Before

java
Signature s = Signature.getInstance("SHA256withECDSA");

After

java
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 for KyberParameterSpec, DilithiumParameterSpec and 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

java
Signature v = Signature.getInstance("ML-DSA", "BC");
v.initVerify(kp.getPublic());
v.update(message);
System.out.println(v.verify(signature) + " " + signature.length); // true 3309
node:crypto · javascriptNode.js: replace RSA/ECDH key wrapping with ML-KEM-768 using node:crypto (Node 24.7+)Production-ready

Why

If your application encrypts data to someone's public key (RSA-OAEP key wrapping, ECIES, "sealed boxes", ECDH followed by AES), anyone who stores the ciphertext can decrypt it once a large quantum computer exists. ML-KEM (FIPS 203) is the standard replacement: it is a key encapsulation mechanism. Instead of encrypting your data key with the public key, you ask ML-KEM for a fresh 32-byte shared secret plus a ciphertext that only the private-key holder can open. You then derive a symmetric key from that secret and encrypt the data with AES-256-GCM.

Node.js has native, OpenSSL-backed ML-KEM in node:crypto: key generation since 24.7.0, plus crypto.encapsulate() / crypto.decapsulate() added in 24.7.0. It requires a Node built with OpenSSL 3.5 or later (all official Node 24 and 26 builds). Node 22 does not have these APIs; use the @noble/post-quantum guide there.

Steps

  1. Require Node 24.7+ (check node -v) and OpenSSL 3.5+ (process.versions.openssl).
  2. Generate an ML-KEM-768 key pair for each recipient; publish the public key (SPKI DER or PEM).
  3. Sender: encapsulate(publicKey) gives { sharedKey, ciphertext }. Derive an AES key from sharedKey with HKDF and encrypt the payload with AES-256-GCM. Send ciphertext, the IV, the GCM tag and the encrypted payload.
  4. Recipient: decapsulate(privateKey, ciphertext) gives the same sharedKey; derive the same AES key and decrypt.
  5. During the transition, consider a hybrid: also run X25519 and feed both secrets into HKDF (see the @noble/post-quantum guide for a worked example), so security never drops below today's.

Before (RSA-OAEP key wrapping)

js
import { generateKeyPairSync, publicEncrypt, privateDecrypt, randomBytes, constants } from 'node:crypto';

const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const dataKey = randomBytes(32);
const wrapped = publicEncrypt({ key: publicKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, dataKey);
const unwrapped = privateDecrypt({ key: privateKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, wrapped);

After (ML-KEM-768 + HKDF + AES-256-GCM)

js
import {
  generateKeyPairSync, encapsulate, decapsulate, hkdfSync,
  createCipheriv, createDecipheriv, randomBytes,
} from 'node:crypto';

// Recipient, once: generate and publish the public key.
const { publicKey, privateKey } = generateKeyPairSync('ml-kem-768');
const publicPem = publicKey.export({ type: 'spki', format: 'pem' });

// Sender
function seal(recipientPublicKey, plaintext, aad = Buffer.alloc(0)) {
  const { sharedKey, ciphertext: kemCt } = encapsulate(recipientPublicKey);
  const key = Buffer.from(hkdfSync('sha256', sharedKey, Buffer.alloc(0), 'myapp/seal/v1', 32));
  const iv = randomBytes(12);
  const c = createCipheriv('aes-256-gcm', key, iv);
  c.setAAD(aad);
  const body = Buffer.concat([c.update(plaintext), c.final()]);
  return { kemCt, iv, tag: c.getAuthTag(), body };
}

// Recipient
function open(privateKey, { kemCt, iv, tag, body }, aad = Buffer.alloc(0)) {
  const sharedKey = decapsulate(privateKey, kemCt);
  const key = Buffer.from(hkdfSync('sha256', sharedKey, Buffer.alloc(0), 'myapp/seal/v1', 32));
  const d = createDecipheriv('aes-256-gcm', key, iv);
  d.setAAD(aad);
  d.setAuthTag(tag);
  return Buffer.concat([d.update(body), d.final()]);
}

Gotchas

  • Sizes. ML-KEM-768 encapsulation (public) key: 1,184 bytes. Ciphertext: 1,088 bytes (versus 256 for RSA-2048 OAEP). Shared secret: 32 bytes. Check database columns, message size limits, QR codes and URL parameters.
  • A KEM is not "encrypt with the public key". You cannot choose the secret; you get one. Wrap your existing data keys by encrypting them with the KEM-derived key if you need to keep them.
  • Decapsulation never throws on a wrong ciphertext. ML-KEM uses implicit rejection: a tampered or mismatched ciphertext yields a random-looking secret, so the failure shows up as an AES-GCM authentication error. That is by design.
  • Bind context. Put a protocol label (and ideally the recipient key ID) in the HKDF info or the AES-GCM AAD so ciphertexts cannot be replayed into another context.
  • Private key storage. privateKey.export({ type: 'pkcs8', format: 'pem' }) works. Node 26.0+ also supports a 64-byte raw-seed export and writes seed-only PKCS#8 by default when a seed is available; Node 24 does not have raw-seed. Most HSMs and cloud KMSs are still adding ML-KEM; check before designing around them.
  • Runtime mismatch. Code that must also run on Node 22, Deno, Bun or browsers should use @noble/post-quantum or WebCrypto where available.

Verify

js
import assert from 'node:assert';
const msg = Buffer.from('hello');
assert.deepEqual(open(privateKey, seal(publicKey, msg)), msg);
console.log(encapsulate(publicKey).ciphertext.length); // 1088

Run npx -y pqe-cli scan . afterwards: remaining publicEncrypt/RSA-OAEP call sites are listed as findings.

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

  1. 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.
  2. Generate an ML-DSA-65 key pair and distribute the public key alongside (not instead of) the old one.
  3. Sign new artifacts with ML-DSA, or with both algorithms during the transition ("dual signing"); teach verifiers to accept either.
  4. Once all verifiers understand ML-DSA, stop issuing classical signatures.

Before

js
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+)

js
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)

js
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

js
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 (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

bash
openssl genrsa -out key.pem 1024
ssh-keygen -t rsa -b 1024
ssh-keygen -t dsa
js
crypto.generateKeyPairSync('rsa', { modulusLength: 1024 });
python
rsa.generate_private_key(public_exponent=65537, key_size=1024)

After

bash
# 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 ed25519
js
crypto.generateKeyPairSync('ml-dsa-65');                         // Node 24.6+
crypto.generateKeyPairSync('rsa', { modulusLength: 3072 });      // stopgap
python
from 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"), SSH authorized_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: replace RSA-OAEP / ECDH key wrapping with ML-KEM-768 in pyca/cryptography (48+)Production-ready

Why

Data encrypted to an RSA or elliptic-curve public key can be stored now and decrypted once a large quantum computer exists. ML-KEM (FIPS 203) replaces that step. cryptography (pyca) added an ML-KEM module in 47.0.0 (AWS-LC and BoringSSL backends) and extended it to the regular OpenSSL backend (OpenSSL 3.5.0 or later) in 48.0.0. The PyPI wheels bundle a recent OpenSSL, so pip install "cryptography>=48" gives you ML-KEM-768 and ML-KEM-1024 on Linux, macOS and Windows.

Steps

  1. pip install -U "cryptography>=48" and pin it.
  2. Recipient: MLKEM768PrivateKey.generate(); publish public_key().public_bytes_raw() (1,184 bytes) or the SPKI encoding.
  3. Sender: shared_secret, ciphertext = public_key.encapsulate(); derive an AES key with HKDF; encrypt with AES-256-GCM.
  4. Recipient: private_key.decapsulate(ciphertext) gives the same secret.
  5. For a hybrid (recommended during the transition), also do an X25519 exchange and feed both secrets into HKDF, as below.

Before

python
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
import os

priv = rsa.generate_private_key(public_exponent=65537, key_size=2048)
data_key = os.urandom(32)
oaep = padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
wrapped = priv.public_key().encrypt(data_key, oaep)
assert priv.decrypt(wrapped, oaep) == data_key

After (hybrid ML-KEM-768 + X25519 → HKDF → AES-256-GCM)

python
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

# Recipient key pairs (store the private keys like any other secret)
pq_priv = MLKEM768PrivateKey.generate()
ec_priv = X25519PrivateKey.generate()
pq_pub, ec_pub = pq_priv.public_key(), ec_priv.public_key()

def derive(ss_pq: bytes, ss_ec: bytes, transcript: bytes) -> bytes:
    return HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
                info=b"myapp/hybrid-seal/v1" + transcript).derive(ss_pq + ss_ec)

def seal(plaintext: bytes, aad: bytes = b"") -> dict:
    ss_pq, kem_ct = pq_pub.encapsulate()                     # (shared_secret, ciphertext)
    eph = X25519PrivateKey.generate()
    eph_pub = eph.public_key().public_bytes_raw()
    ss_ec = eph.exchange(ec_pub)
    key = derive(ss_pq, ss_ec, eph_pub + kem_ct)
    nonce = os.urandom(12)
    return {"kem_ct": kem_ct, "eph_pub": eph_pub, "nonce": nonce,
            "body": AESGCM(key).encrypt(nonce, plaintext, aad)}

def open_(msg: dict, aad: bytes = b"") -> bytes:
    ss_pq = pq_priv.decapsulate(msg["kem_ct"])
    ss_ec = ec_priv.exchange(X25519PublicKey.from_public_bytes(msg["eph_pub"]))
    key = derive(ss_pq, ss_ec, msg["eph_pub"] + msg["kem_ct"])
    return AESGCM(key).decrypt(msg["nonce"], msg["body"], aad)

assert open_(seal(b"hello")) == b"hello"

Gotchas

  • Return order. encapsulate() returns (shared_secret, ciphertext); mixing them up gives silently wrong keys.
  • Implicit rejection. decapsulate() does not raise on a tampered ciphertext; you find out when AES-GCM raises InvalidTag.
  • Sizes. ML-KEM-768 ciphertext 1,088 bytes, public key 1,184 bytes; ML-KEM-1024: 1,568 and 1,568. Private keys serialise as a 64-byte seed (private_bytes_raw()).
  • Backend support. If your cryptography is built against a system OpenSSL older than 3.5 (some distro packages), generate() raises UnsupportedAlgorithm. Check in CI.
  • Hazmat. These are low-level primitives; the HKDF info label and transcript binding above matter. Prefer a reviewed higher-level protocol (HPKE, TLS) when one fits.
  • No ML-KEM-512 class in this module; use 768 (recommended) or 1024 (CNSA 2.0).

Verify

python
from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey
k = MLKEM768PrivateKey.generate()
ss, ct = k.public_key().encapsulate()
assert k.decapsulate(ct) == ss and len(ct) == 1088
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

  1. pip install -U "cryptography>=48" (49+ if you need ML-DSA certificates).
  2. Put an algorithm identifier next to every stored signature so verifiers can support both old and new algorithms during the transition.
  3. Generate an ML-DSA-65 key, distribute the public key, and dual-sign (classical + ML-DSA) until all verifiers are upgraded.

Before

python
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

python
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 cryptography linked against an older system OpenSSL raises UnsupportedAlgorithm.
  • 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

python
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 3309
aws-lc-rs (kem) / RustCrypto ml-kem · rustRust: application-level ML-KEM-768 with aws-lc-rs or the RustCrypto ml-kem crateProduction-ready

Why

To replace ECDH- or RSA-based key wrapping in your own protocol, use ML-KEM (FIPS 203). Two common choices:

  • aws-lc-rs (aws_lc_rs::kem): bindings to AWS-LC, which also has a FIPS-validated mode. Recommended for production.
  • ml-kem (RustCrypto): pure Rust, no_std-friendly. Its README warns it has never been independently audited; fine for many uses, but weigh that for high-assurance code.

Steps

  1. Add the crate, generate a decapsulation key, publish the encapsulation key bytes (1,184 bytes for ML-KEM-768).
  2. Sender encapsulates to get (ciphertext, shared_secret); receiver decapsulates.
  3. Feed the secret (optionally together with an X25519 secret for a hybrid) into HKDF and encrypt with AES-256-GCM or ChaCha20-Poly1305.

Before

rust
use x25519_dalek::{EphemeralSecret, PublicKey};
let secret = EphemeralSecret::random();
let shared = secret.diffie_hellman(&peer_public); // quantum-vulnerable

After: aws-lc-rs

rust
use aws_lc_rs::kem::{Ciphertext, DecapsulationKey, EncapsulationKey, ML_KEM_768};

// Receiver
let dk = DecapsulationKey::generate(&ML_KEM_768)?;
let ek_bytes = dk.encapsulation_key()?.key_bytes()?; // send ek_bytes.as_ref() (1184 bytes)

// Sender
let ek = EncapsulationKey::new(&ML_KEM_768, ek_bytes.as_ref())?;
let (ciphertext, sender_secret) = ek.encapsulate()?;

// Receiver
let receiver_secret = dk.decapsulate(Ciphertext::from(ciphertext.as_ref()))?;
assert_eq!(sender_secret.as_ref(), receiver_secret.as_ref());

After: RustCrypto ml-kem (0.3.x, getrandom feature enabled)

rust
use ml_kem::{MlKem768, kem::{Decapsulate, Encapsulate, Kem}};

let (dk, ek) = MlKem768::generate_keypair();
let (ct, k_send) = ek.encapsulate();
let k_recv = dk.decapsulate(&ct);
assert_eq!(k_send, k_recv);

Gotchas

  • API churn. The RustCrypto ml-kem API changed between 0.2 and 0.3; copy examples from the docs of the exact version you depend on.
  • Implicit rejection: decapsulating a wrong ciphertext returns a pseudo-random secret, not an error. Authenticate the payload with an AEAD.
  • Do not use the raw secret directly as a long-term key; run it through HKDF with a protocol label.
  • Hybrid with X25519 is recommended during the transition (combine both secrets in HKDF, binding the ciphertext and public keys).

Verify

Unit-test a round trip and assert sizes: ciphertext 1,088 bytes, encapsulation key 1,184 bytes, secret 32 bytes.