Skip to content

ML-KEM

Header: #include <cryptopp/mlkem.h> | Namespace: CryptoPP
Since: cryptopp-modern 2026.3.0
Thread Safety: Encapsulator/Decapsulator instances are not thread-safe; use one per thread. Treat key objects as immutable after load; do not mutate a key while it is in use by other threads.

ML-KEM (Module-Lattice-Based Key-Encapsulation Mechanism) is the NIST post-quantum key-encapsulation standard, FIPS 203, derived from CRYSTALS-Kyber. Two parties use it to establish a shared secret key, and it is designed to resist attack by quantum computers as well as conventional ones.

Key Features

  • Post-quantum - Security rests on the Module Learning With Errors problem
  • IND-CCA2 - Designed for security against adaptive chosen-ciphertext attack
  • Implicit rejection - An invalid ciphertext yields a pseudorandom shared secret instead of an error
  • 3 parameter sets - NIST security categories 1, 3 and 5

Parameter Sets

Parameter SetSecurity CategoryPublic KeySecret KeyCiphertextShared Secret
ML-KEM-5121800 bytes1632 bytes768 bytes32 bytes
ML-KEM-76831184 bytes2400 bytes1088 bytes32 bytes
ML-KEM-102451568 bytes3168 bytes1568 bytes32 bytes

A NIST security category compares the cost of breaking the scheme with the cost of a key search on a block cipher: category 1 with AES-128, category 3 with AES-192 and category 5 with AES-256. FIPS 203 recommends ML-KEM-768 as the default parameter set. ML-KEM-512 has smaller keys and ciphertexts at category 1; ML-KEM-1024 is the category 5 set.


Quick Example

#include <cryptopp/mlkem.h>
#include <cryptopp/osrng.h>
#include <cryptopp/secblock.h>
#include <cstring>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // === Recipient generates key pair ===
    MLKEMDecapsulator<MLKEM_768> recipient(rng);

    // Extract public key to share with sender
    const auto& rkey = recipient.GetKey();
    SecByteBlock publicKey(rkey.GetPublicKeySize());
    std::memcpy(publicKey.begin(), rkey.GetPublicKeyBytePtr(), publicKey.size());

    // === Sender encapsulates with recipient's public key ===
    MLKEMEncapsulator<MLKEM_768> sender(publicKey.begin(), publicKey.size());

    SecByteBlock ciphertext(sender.CiphertextLength());
    SecByteBlock senderSecret(sender.SharedSecretLength());
    sender.Encapsulate(rng, ciphertext.begin(), senderSecret.begin());

    // === Recipient decapsulates to get shared secret ===
    SecByteBlock recipientSecret(recipient.SharedSecretLength());
    // Note: Decapsulate() always returns true due to implicit rejection
    (void)recipient.Decapsulate(ciphertext.begin(), recipientSecret.begin());

    // Both parties now have the same shared secret
    bool same = (senderSecret == recipientSecret);
    std::cout << "Shared secrets match: " << (same ? "YES" : "NO") << "\n";

    return same ? 0 : 1;
}

Usage Guidelines

Do:

  • Use ML-KEM-768 unless you have a reason to choose another parameter set
  • Pass the shared secret through a KDF, with protocol-specific context, to derive session keys
  • Keep private keys in SecByteBlock
  • Authenticate the exchange; ML-KEM by itself does not identify the other party
  • Consider X-Wing to combine ML-KEM-768 with X25519

Avoid:

  • Choosing ML-KEM-512 only to save bytes when category 1 does not meet your requirements
  • Treating a successful Decapsulate() call as proof that the ciphertext was valid

When to Use ML-KEM

Use ML-KEM when:

  • You need post-quantum key establishment
  • A protocol or policy specifies FIPS 203
  • You are building the post-quantum half of your own hybrid design

X-Wing is preferable when you want a ready-made hybrid: its shared secret stays secure if either X25519 or ML-KEM-768 remains unbroken. Note that TLS 1.3 hybrid key exchange uses its own combination of X25519 and ML-KEM-768, not X-Wing, so check what your peer implements.

If your threat model excludes quantum adversaries, X25519 has much smaller keys and messages.


Class: MLKEMEncapsulator

Encapsulate (generate shared secret and ciphertext) using recipient’s public key.

Template Parameter

template <class PARAMS>
struct MLKEMEncapsulator;

PARAMS is one of: MLKEM_512, MLKEM_768, MLKEM_1024

Constants

CRYPTOPP_CONSTANT(PUBLIC_KEYLENGTH = PARAMS::PUBLIC_KEY_SIZE);
CRYPTOPP_CONSTANT(CIPHERTEXT_LENGTH = PARAMS::CIPHERTEXT_SIZE);
CRYPTOPP_CONSTANT(SHARED_SECRET_LENGTH = PARAMS::SHARED_SECRET_SIZE);

Constructors

Default Constructor

MLKEMEncapsulator();

Create an encapsulator with no key. Set the public key before calling Encapsulate().

Constructor with Public Key

MLKEMEncapsulator(const byte* publicKey, size_t publicKeyLen);

Create an encapsulator from recipient’s public key.

Parameters:

  • publicKey - Pointer to public key bytes
  • publicKeyLen - Length of public key. A length that does not match the parameter set throws InvalidKeyLength.

Example:

// Receive public key from recipient
SecByteBlock publicKey = /* received from recipient */;
MLKEMEncapsulator<MLKEM_768> encapsulator(publicKey.begin(), publicKey.size());

Methods

Encapsulate

void Encapsulate(RandomNumberGenerator& rng,
                 byte* ciphertext,
                 byte* sharedSecret) const;

Generate a random shared secret and encapsulate it for the recipient. Before encapsulating, the function runs the encapsulation-key check that FIPS 203 section 7.2 requires and throws InvalidArgument if the key fails it.

Parameters:

  • rng - Random number generator
  • ciphertext - Output buffer for ciphertext (CiphertextLength() bytes)
  • sharedSecret - Output buffer for shared secret (SharedSecretLength() bytes)

Example:

SecByteBlock ciphertext(encapsulator.CiphertextLength());
SecByteBlock sharedSecret(encapsulator.SharedSecretLength());
encapsulator.Encapsulate(rng, ciphertext.begin(), sharedSecret.begin());
// Send ciphertext to recipient

AccessPublicKey / GetPublicKey

MLKEMPublicKey<PARAMS>& AccessPublicKey();
const MLKEMPublicKey<PARAMS>& GetPublicKey() const;

Access the public key for setting or retrieving.

CiphertextLength / SharedSecretLength

size_t CiphertextLength() const;   // Returns CIPHERTEXT_LENGTH
size_t SharedSecretLength() const; // Returns 32

AlgorithmName

std::string AlgorithmName() const;

Get the algorithm name (e.g., “ML-KEM-768”). Useful for logging and runtime identification.


Class: MLKEMDecapsulator

Generate key pairs and decapsulate (recover shared secret from ciphertext).

Template Parameter

template <class PARAMS>
struct MLKEMDecapsulator;

PARAMS is one of: MLKEM_512, MLKEM_768, MLKEM_1024

Constants

CRYPTOPP_CONSTANT(SECRET_KEYLENGTH = PARAMS::SECRET_KEY_SIZE);
CRYPTOPP_CONSTANT(PUBLIC_KEYLENGTH = PARAMS::PUBLIC_KEY_SIZE);
CRYPTOPP_CONSTANT(CIPHERTEXT_LENGTH = PARAMS::CIPHERTEXT_SIZE);
CRYPTOPP_CONSTANT(SHARED_SECRET_LENGTH = PARAMS::SHARED_SECRET_SIZE);

Constructors

Default Constructor

MLKEMDecapsulator();

Create a decapsulator with no key. Generate or load a key before calling Decapsulate().

Constructor with RNG (Generate New Key Pair)

MLKEMDecapsulator(RandomNumberGenerator& rng);

Generate a new key pair.

Example:

AutoSeededRandomPool rng;
MLKEMDecapsulator<MLKEM_768> decapsulator(rng);
// Share public key with senders

Constructor with Private Key

MLKEMDecapsulator(const byte* privateKey, size_t privateKeyLen);

Load an existing private key.

Example:

// Load stored private key
SecByteBlock storedKey = /* loaded from storage */;
MLKEMDecapsulator<MLKEM_768> decapsulator(storedKey.begin(), storedKey.size());

Methods

Decapsulate

bool Decapsulate(const byte* ciphertext, byte* sharedSecret) const;

Recover the shared secret from a ciphertext.

Parameters:

  • ciphertext - Ciphertext from encapsulator, exactly CiphertextLength() bytes. The function takes no length and reads that many bytes, so check the length of a received ciphertext first
  • sharedSecret - Output buffer for shared secret (SharedSecretLength() bytes)

Returns: true (always returns true for ML-KEM due to implicit rejection)

Details: ML-KEM uses implicit rejection: if the ciphertext is not one that encapsulation could have produced for this key, the function writes a pseudorandom value derived from the private key and the ciphertext instead of reporting an error. The sender and recipient then hold different secrets, and the mismatch shows up when the derived keys are first used. The sharedSecret buffer is always written.

Important: The return value carries no information; it is always true. Detect a bad ciphertext through the protocol, for example a failed AEAD tag or key-confirmation message under the derived keys.

Example:

// ciphertext arrived from the sender: check its length before use
if (ciphertext.size() != decapsulator.CiphertextLength())
    throw std::runtime_error("ML-KEM: wrong ciphertext length");

SecByteBlock sharedSecret(decapsulator.SharedSecretLength());
// Proceed with the shared secret; a bad ciphertext gives a secret the sender does not have
(void)decapsulator.Decapsulate(ciphertext.begin(), sharedSecret.begin());
// Use sharedSecret with a KDF

AccessPrivateKey / GetPrivateKey / GetKey

MLKEMPrivateKey<PARAMS>& AccessPrivateKey();
const MLKEMPrivateKey<PARAMS>& GetPrivateKey() const;
const MLKEMPrivateKey<PARAMS>& GetKey() const;

Access the private key.

AlgorithmName

std::string AlgorithmName() const;

Get the algorithm name (e.g., “ML-KEM-768”).


Class: MLKEMPrivateKey

Holds the secret key material for decapsulation.

Methods

GetAlgorithmID

OID GetAlgorithmID() const;

Get the algorithm OID for this key type. Used in ASN.1/DER encoding.

GenerateRandom

void GenerateRandom(RandomNumberGenerator& rng, const NameValuePairs& params);

Generate a new random key pair.

Example:

MLKEMPrivateKey<MLKEM_768> privateKey;
privateKey.GenerateRandom(rng, g_nullNameValuePairs);

GetPublicKeyBytePtr / GetPublicKeySize

const byte* GetPublicKeyBytePtr() const;
size_t GetPublicKeySize() const;

Get the embedded public key.

Example:

SecByteBlock publicKey(privateKey.GetPublicKeySize());
std::memcpy(publicKey.begin(), privateKey.GetPublicKeyBytePtr(), publicKey.size());

GetPrivateKeyBytePtr / GetPrivateKeySize

const byte* GetPrivateKeyBytePtr() const;
size_t GetPrivateKeySize() const;

Get the private key bytes.

Save / Load

void Save(BufferedTransformation& bt) const;
void Load(BufferedTransformation& bt);

Serialize/deserialize in ASN.1 DER format.


Class: MLKEMPublicKey

Holds the public key material for encapsulation.

Methods

SetPublicKey

void SetPublicKey(const byte* key, size_t len);

Set the public key bytes.

GetPublicKeyBytePtr / GetPublicKeySize

const byte* GetPublicKeyBytePtr() const;
size_t GetPublicKeySize() const;

Get the public key bytes.

Save / Load

void Save(BufferedTransformation& bt) const;
void Load(BufferedTransformation& bt);

Serialize/deserialize in ASN.1 DER format.


Key Serialization

Requires: #include <cryptopp/files.h> for file I/O examples.

Saving Keys (Raw Bytes)

MLKEMDecapsulator<MLKEM_768> decapsulator(rng);
const auto& privKey = decapsulator.GetKey();

// Save private key
SecByteBlock privateKeyBytes(privKey.GetPrivateKeySize());
std::memcpy(privateKeyBytes.begin(),
            privKey.GetPrivateKeyBytePtr(),
            privateKeyBytes.size());

// Save public key
SecByteBlock publicKeyBytes(privKey.GetPublicKeySize());
std::memcpy(publicKeyBytes.begin(),
            privKey.GetPublicKeyBytePtr(),
            publicKeyBytes.size());

Loading Keys (Raw Bytes)

// Load private key for decapsulation
MLKEMDecapsulator<MLKEM_768> decapsulator(
    privateKeyBytes.begin(), privateKeyBytes.size());

// Load public key for encapsulation
MLKEMEncapsulator<MLKEM_768> encapsulator(
    publicKeyBytes.begin(), publicKeyBytes.size());

Saving Keys (ASN.1 DER)

// Save private key to file
FileSink privFile("mlkem_private.der");
decapsulator.GetKey().Save(privFile);

// Save public key to file
FileSink pubFile("mlkem_public.der");
MLKEMPublicKey<MLKEM_768> pubKey;
pubKey.SetPublicKey(decapsulator.GetKey().GetPublicKeyBytePtr(),
                    decapsulator.GetKey().GetPublicKeySize());
pubKey.Save(pubFile);

Loading Keys (ASN.1 DER)

// Load private key from file
FileSource privFile("mlkem_private.der", true);
MLKEMDecapsulator<MLKEM_768> decapsulator;
decapsulator.AccessPrivateKey().Load(privFile);

// Load public key from file
FileSource pubFile("mlkem_public.der", true);
MLKEMEncapsulator<MLKEM_768> encapsulator;
encapsulator.AccessPublicKey().Load(pubFile);

Loading Keys from a std::string (in-memory)

Watch the StringSource overload. StringSource(der.c_str(), der.size()) compiles to StringSource(const char*, bool, ...). The size becomes a bool and the c-string is truncated at the first zero byte, silently corrupting binary DER. Use one of the forms below instead.
std::string der;
// populate der via Save(), file read, base64 decode, etc.

// std::string overload
MLKEMPublicKey<MLKEM_768> pubKey;
StringSource pubSource(der, true);
pubKey.Load(pubSource);

// byte-pointer + length overload
StringSource pubSource2(reinterpret_cast<const byte*>(der.data()), der.size(), true);
pubKey.Load(pubSource2);

Same applies to MLKEMPrivateKey. Any binary payload through StringSource needs one of these forms; it isn’t ML-KEM specific.


Using with a KDF

Derive keys from the shared secret using a KDF with context:

#include <cryptopp/mlkem.h>
#include <cryptopp/hkdf.h>
#include <cryptopp/sha3.h>
#include <cryptopp/osrng.h>
#include <cryptopp/secblock.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Recipient key pair; sender encapsulates to its public key
    MLKEMDecapsulator<MLKEM_768> recipient(rng);
    MLKEMEncapsulator<MLKEM_768> sender(recipient.GetKey().GetPublicKeyBytePtr(),
                                        recipient.GetKey().GetPublicKeySize());

    SecByteBlock ciphertext(sender.CiphertextLength());
    SecByteBlock senderSecret(sender.SharedSecretLength());
    sender.Encapsulate(rng, ciphertext.begin(), senderSecret.begin());

    SecByteBlock recipientSecret(recipient.SharedSecretLength());
    (void)recipient.Decapsulate(ciphertext.begin(), recipientSecret.begin());

    // Each side derives a 32-byte key. The info string names the
    // application and the key's purpose.
    const byte info[] = "example v1 session key";
    SecByteBlock senderKey(32), recipientKey(32);
    HKDF<SHA3_256> hkdf;
    hkdf.DeriveKey(senderKey.begin(), senderKey.size(),
                   senderSecret.begin(), senderSecret.size(),
                   NULLPTR, 0, info, sizeof(info) - 1);
    hkdf.DeriveKey(recipientKey.begin(), recipientKey.size(),
                   recipientSecret.begin(), recipientSecret.size(),
                   NULLPTR, 0, info, sizeof(info) - 1);

    bool same = (senderKey == recipientKey);
    std::cout << "Derived keys match: " << (same ? "YES" : "NO") << "\n";

    return same ? 0 : 1;
}

cryptest b measures ML-KEM on your own hardware.


Security Considerations

  1. Shared Secret Usage - Prefer feeding the shared secret into a KDF with context to derive exactly the keys you need. FIPS 203 permits direct use as a symmetric key; a KDF with context also binds the keys to your protocol.

  2. Implicit Rejection - ML-KEM returns a pseudorandom shared secret on an invalid ciphertext instead of failing. This is part of its chosen-ciphertext security: the recipient’s behaviour does not tell an attacker whether a crafted ciphertext was accepted.

  3. Private Key Storage - Keep private key bytes in SecByteBlock, which wipes its memory on destruction.

  4. Forward Secrecy - Generate a fresh key pair for each session and discard the private key afterwards.

  5. Hybrid Mode - For defence in depth, combine ML-KEM with classical key exchange using X-Wing.

  6. Authentication - A KEM gives confidentiality only. Use signatures or another authenticated protocol to know who holds the other key.


Object Identifiers (OIDs)

Library-provided OIDs for ASN.1/DER encoding:

Parameter SetOIDAccessor
ML-KEM-5122.16.840.1.101.3.4.4.1ASN1::id_ml_kem_512()
ML-KEM-7682.16.840.1.101.3.4.4.2ASN1::id_ml_kem_768()
ML-KEM-10242.16.840.1.101.3.4.4.3ASN1::id_ml_kem_1024()

Usage:

// Get OID from key object
OID oid = privateKey.GetAlgorithmID();

// Get OID statically from parameter set
OID staticOid = MLKEM_768::StaticAlgorithmOID();

// Compare OIDs
if (oid == ASN1::id_ml_kem_768()) {
    // ML-KEM-768 key
}

Exceptions

  • InvalidKeyLength - A key passed to a constructor, SetPublicKey() or SetPrivateKey() has the wrong length for the parameter set
  • InvalidArgument - The public key fails the FIPS 203 encapsulation-key check in Encapsulate(), or Save() was called on a key object that holds no key material
  • BERDecodeErr - Load() was given a malformed encoding

Specification Compliance

This implementation follows NIST FIPS 203 (August 2024):

  • Key Generation: ML-KEM.KeyGen (Algorithm 19, over ML-KEM.KeyGen_internal, Algorithm 16)
  • Encapsulation: ML-KEM.Encaps (Algorithm 20, over Algorithm 17)
  • Decapsulation: ML-KEM.Decaps (Algorithm 21, over Algorithm 18), with implicit rejection
  • Hash Functions: SHA3-256, SHA3-512, SHAKE128 and SHAKE256

FIPS 203 section 7.3 requires three checks on the inputs to decapsulation, and Decapsulate() does not make two of them. The ciphertext length check is the caller’s, because the function takes no length. The hash check on the decapsulation key is not performed: raw private-key import with SetPrivateKey() checks the length only, and DER Load() also checks the encoding and the algorithm identifier.

The library’s test suite runs NIST ACVP test vectors for key generation, encapsulation and decapsulation.


See Also

  • X-Wing - Hybrid KEM (X25519 + ML-KEM-768)
  • ML-DSA - Post-quantum signatures
  • PQC Overview - Algorithm comparison and guidance

References

  1. FIPS 203: Module-Lattice-Based Key-Encapsulation Mechanism Standard
  2. CRYSTALS-Kyber: Algorithm Specifications and Supporting Documentation (version 3.02)