← Back to section · Tutorials & Labs
Hands-On: ML-KEM-768 Encapsulation with Rust's ml-kem Crate
Run a complete ML-KEM-768 key generation, encapsulation and decapsulation with RustCrypto's ml-kem crate, check the sizes against FIPS 203, and learn what to watch for in no_std environments.
What This Article Does
The previous article surveyed the RustCrypto landscape. This one gets hands-on: using the ml-kem crate from the KEMs repository, we run a complete ML-KEM-768 key encapsulation locally — generate a key pair, encapsulate to obtain a ciphertext and a shared secret, decapsulate to recover the shared secret, and verify both sides agree. ml-kem is a pure-Rust implementation of FIPS 203 with no C library dependency, so the build experience is that of an ordinary Rust project.
One caveat up front: the code below follows the crate’s trait structure, and minor details such as the import path of the randomness source type may differ slightly between minor versions. When you try it, cross-check the documentation and examples for the exact version on docs.rs.
Setup: Add the Dependencies
Add to Cargo.toml:
[dependencies]
ml-kem = "0.2"
kem = "0.2"
rand_core = { version = "0.6", features = ["getrandom"] }
ml-kem provides the algorithm implementation; kem is RustCrypto’s trait-layer crate, and the encapsulation and decapsulation methods come from its Encapsulate and Decapsulate traits. Parameter sets are distinguished by type: MlKem512, MlKem768, and MlKem1024 correspond to the three FIPS 203 parameter sets. Making the parameter set a type has a real benefit: mistakes such as decapsulating a 1024 ciphertext with a 768 key are caught by the type system at compile time rather than surfacing at runtime.
The Core Flow: Encapsulation in Three Steps
use kem::{Decapsulate, Encapsulate};
use ml_kem::{KemCore, MlKem768};
use rand_core::OsRng;
fn main() {
// Step 1: generate a key pair (decapsulation key dk, encapsulation key ek)
let (dk, ek) = MlKem768::generate(&mut OsRng);
// Step 2: encapsulate — obtain the ciphertext and the shared secret
let (ct, ss_send) = ek.encapsulate(&mut OsRng).unwrap();
// Step 3: decapsulate — recover the shared secret from the ciphertext with dk
let ss_recv = dk.decapsulate(&ct).unwrap();
assert_eq!(ss_send, ss_recv);
println!("shared secrets match, length {} bytes", ss_send.len());
}
Step by step. MlKem768::generate comes from the KemCore trait and produces the key pair in one call; note that it needs a randomness source, because key generation itself consumes randomness. encapsulate also needs a randomness source: ML-KEM’s encapsulation samples fresh one-time randomness internally, which is why the caller never has to manage a nonce manually. decapsulate needs no randomness; it is a deterministic computation that takes the private key and ciphertext and outputs the shared secret. Finally, an assertion verifies that both secrets match — in a real protocol, this comparison should be constant-time (see the subtle article in this subcategory); the tutorial asserts directly for clarity.
One more key point: ML-KEM decapsulation has implicit rejection semantics. If a ciphertext is tampered with, decapsulate does not return an error; it returns a pseudorandom secret unrelated to the original, and the handshake then fails naturally at the key-confirmation step. Flip one byte of the ciphertext in the code above and run it again: what you observe is an assertion failure, not a program error — exactly the expected implicit-rejection behavior.
Checking Sizes: Reconciling with FIPS 203
The most common trap in tutorial code is “it ran, but with the wrong parameter set.” After running, print and verify the lengths. The standard figures for ML-KEM-768 are: encapsulation public key 1184 bytes, decapsulation private key 2400 bytes, ciphertext 1088 bytes, shared secret 32 bytes. These numbers come from the FIPS 203 parameter table and are the baseline cited repeatedly across this site. If your printed public key is 800 bytes, you actually used ML-KEM-512 — the code did not error, but the security level quietly changed by a full grade.
On serialization: key and ciphertext objects provide methods to export themselves as byte arrays, and importing validates lengths strictly. Before writing keys to disk or sending them over the network, return to the zeroize article in this subcategory: responsibility for erasing private keys in memory does not disappear just because the API is type-safe.
Using It in no_std and Embedded Environments
The ml-kem crate itself is designed to be no_std friendly: the core operations use fixed-size arrays and do not depend on heap allocation from the standard library, which lets it fit into microcontrollers and trusted execution environments. But two things are the caller’s responsibility. First, the randomness source: generate and encapsulate accept any object implementing RngCore. On the desktop we use OsRng; on embedded hardware you must wire up the chip’s true random number generator or a correctly seeded deterministic random bit generator — randomness quality directly determines key security, and this is the one place the whole system cannot afford compromise. Second, feature flags: some of the crate’s conveniences, such as obtaining randomness from the operating system, are feature-gated. Trimming features yields a smaller binary and a smaller dependency surface, and is worth reviewing item by item before deployment.
Common Problems and Troubleshooting
A few issues that commonly arise on a first attempt, collected in one place. First, mismatched versions. ml-kem has version relationships with the kem and rand_core crates it depends on; if compilation fails with trait-not-implemented errors, first check whether you hand-pinned incompatible major versions — letting a consistent release set resolve usually fixes it. Second, the randomness source type does not line up. The import path and feature switches for OsRng differ across rand_core versions; when you hit an error, consult the examples matching your exact version on docs.rs rather than copying snippets from other versions. Third, using encapsulation as encryption. ML-KEM only produces a shared secret; it encrypts no data. To encrypt a message, derive a symmetric key from the shared secret via HKDF and hand it to an AEAD algorithm such as AES-GCM — the standard KEM/DEM composition; ml-kem’s job ends at delivering the shared secret. Fourth, cross-implementation incompatibility. If encapsulation with ml-kem fails to decapsulate with liboqs, first confirm both sides use the same parameter set and standard version: finalized FIPS 203 implementations interoperate with each other, but not with pre-standard Kyber draft implementations — that is a versioning issue, not a code bug.
Two Exercises to Consolidate
After the minimal loop runs, two small exercises are worth doing. The first is a cross-parameter-set comparison: swap MlKem768 for MlKem512 and MlKem1024, print the public-key and ciphertext lengths for all three grades side by side, and verify by hand that sizes grow with the security grade exactly as the FIPS 203 parameter table says — only the type name changes, not one other line of code, which also demonstrates the value of type-parameterized design. The second is failure injection: XOR one byte of the ciphertext with a nonzero value before decapsulation, confirm the program takes the assertion-failure path (implicit rejection) rather than an error return, and then read this behavior against the padding-oracle history of classical RSA decryption, where padding errors were reported explicitly. You will understand why implicit rejection is the standard design for post-quantum KEMs. Neither exercise takes more than ten lines of code, but both turn this article’s knowledge points into muscle memory.
Summary and Next Steps
This article ran the minimal loop: key generation, encapsulation, decapsulation, and size reconciliation. A real system also needs a protocol layer that feeds the shared secret into a derivation process such as HKDF and integrates encapsulation into TLS or a custom handshake protocol. For a contrasting technical route, read the pqcrypto and liboqs articles in this subcategory: the same FIPS 203, but binding-based implementations involve entirely different trade-offs in build, audit, and deployment than the pure-Rust route.
Tags: RustML-KEMRustCryptoHands-On