Skip to main content

kyberlib/
lib.rs

1// Copyright © 2024 kyberlib. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! # `kyberlib` — FIPS 203 ML-KEM in Rust
5//!
6//! Audit-friendly, `no_std`-compatible implementation of **FIPS 203
7//! ML-KEM** (the standardised CRYSTALS-Kyber post-quantum key
8//! encapsulation mechanism, finalised August 2024). 180/180 ACVP
9//! conformance against the NIST test corpus (60 vectors each for
10//! ML-KEM-512, -768 and -1024).
11//!
12//! [![kyberlib logo](https://cloudcdn.pro/kyberlib/v1/logos/kyberlib.svg)](https://kyberlib.com)
13//!
14//! ## At a glance
15//!
16//! - **Three parameter sets**: [`MlKem512`], [`MlKem768`] (default),
17//!   [`MlKem1024`] — covering NIST security categories 1, 3, 5.
18//! - **Two APIs**: the v0.0.7 *typed-state* API ([`KemCore`] trait +
19//!   typed wrappers) and the legacy free-function API
20//!   ([`keypair`] / [`encapsulate`] / [`decapsulate`]).
21//! - **Constant-time**: KyberSlash audit clean (ADR 0003); secrets
22//!   carry [`zeroize::Zeroize`]; `dudect` regression gate in
23//!   `scripts/dudect.sh`.
24//! - **`no_std`**: optional `std` feature. Default features pull in
25//!   `std` for ergonomic error types.
26//! - **No `unsafe`** in the safe core. The optional `avx2` / `nasm`
27//!   backends scope `unsafe` to the SIMD module only.
28//!
29//! ## Quick start (typed API — recommended)
30//!
31//! ```
32//! # fn main() -> Result<(), kyberlib::KyberLibError> {
33//! use kyberlib::{KemCore, MlKem768};
34//!
35//! let mut rng = rand::thread_rng();
36//!
37//! // Bob generates a (decap, encap) keypair.
38//! let (bob_dk, bob_ek) = MlKem768::generate(&mut rng)?;
39//!
40//! // Alice encapsulates a shared secret against Bob's encap key.
41//! let (ciphertext, ss_alice) = bob_ek.encapsulate(&mut rng)?;
42//!
43//! // Bob decapsulates with his decap key (implicit rejection per
44//! // FIPS 203 §6.3 — never panics, never branches on validity).
45//! let ss_bob = bob_dk.decapsulate(&ciphertext);
46//!
47//! assert_eq!(ss_alice, ss_bob);
48//! # Ok(()) }
49//! ```
50//!
51//! ## Quick start (legacy free-function API)
52//!
53//! ```
54//! # fn main() -> Result<(), kyberlib::KyberLibError> {
55//! use kyberlib::{keypair, encapsulate, decapsulate};
56//!
57//! let mut rng = rand::thread_rng();
58//! let bob = keypair(&mut rng)?;
59//! let (ct, ss_a) = encapsulate(&bob.public, &mut rng)?;
60//! let ss_b = decapsulate(&ct, &bob.secret)?;
61//! assert_eq!(ss_a, ss_b);
62//! # Ok(()) }
63//! ```
64//!
65//! ## Cargo features
66//!
67//! | Feature | Default | Description |
68//! |---|---|---|
69//! | `std` | ✅ | Enables the `std` library — required for `std::error::Error` on [`KyberLibError`]. Disable for `no_std` targets. |
70//! | `kyber768` | ✅ | NIST security category 3 (≈ AES-192). Default. |
71//! | `kyber512` |  | NIST security category 1 (≈ AES-128). Mutually exclusive with `kyber768`/`kyber1024`. |
72//! | `kyber1024` |  | NIST security category 5 (≈ AES-256). Required by CNSA 2.0 for NSS by 2027-01-01. Mutually exclusive with `kyber768`/`kyber512`. |
73//! | `90s` |  | "Kyber-90s" variant — SHA-2 / AES-CTR instead of SHAKE. Removed in FIPS 203 but retained for pre-spec compatibility. |
74//! | `90s-fixslice` |  | `90s` with a bitsliced AES implementation (`aes` + `ctr` crates). |
75//! | `avx2` |  | AVX2-accelerated backend (x86_64 only). Compile-errors on other arches. |
76//! | `nasm` |  | AVX2 via NASM assembler (instead of GAS). Requires NASM installed. Implies `avx2`. |
77//! | `hazmat` |  | Re-exports the IND-CPA primitives (no Fujisaki–Okamoto transform). Advanced use only; the resulting construction is NOT IND-CCA secure. |
78//!
79//! ## Architecture
80//!
81//! See [`api`] for the legacy free-function surface, [`ml_kem`] for
82//! the v0.0.7 typed-state API, `hazmat::kex` (feature `hazmat`) for the
83//! Uake/Ake key exchanges, and [`error`] for the [`KyberLibError`] enum.
84//!
85//! ## Errors
86//!
87//! All fallible public functions return [`KyberLibError`]. Variants:
88//!
89//! - [`KyberLibError::InvalidInput`] — input slice length mismatch.
90//!   Typical cause: two peers using different security levels.
91//! - [`KyberLibError::InvalidKey`] — imported keypair fails the
92//!   encap/decap self-test (the public and secret halves don't
93//!   belong together).
94//! - [`KyberLibError::InvalidLength`] — buffer length below the
95//!   required copy length.
96//! - [`KyberLibError::Decapsulation`] — ciphertext failed to
97//!   authenticate. *Not* normally returned: the FIPS 203 implicit-
98//!   rejection construction returns a pseudorandom shared secret on
99//!   invalid input instead.
100//! - [`KyberLibError::RandomBytesGeneration`] — external RNG failed
101//!   (e.g. hardware RNG fault).
102//!
103//! ## Macros (legacy compatibility surface)
104//!
105//! See [`macros`] for the `kyberlib_*` macro family that wraps the
106//! free-function API for terser call sites. Prefer the typed API
107//! ([`KemCore`]) in new code.
108//!
109#![doc(
110    html_favicon_url = "https://cloudcdn.pro/kyberlib/v1/favicon.ico",
111    html_logo_url = "https://cloudcdn.pro/kyberlib/v1/logos/kyberlib.svg",
112    html_root_url = "https://docs.rs/kyberlib"
113)]
114#![crate_name = "kyberlib"]
115#![crate_type = "lib"]
116#![cfg_attr(not(feature = "std"), no_std)]
117#![cfg_attr(docsrs, feature(doc_cfg))]
118// Every public item must carry rustdoc. See issue #137.
119#![deny(missing_docs)]
120// `unsafe` policy:
121//   - Default build (no `avx2`, no `nasm`): `forbid(unsafe_code)` —
122//     strongest guarantee, no inner `#[allow]` can lift it.
123//   - With `--features avx2` or `--features nasm`: crate-level
124//     `deny(unsafe_code)` keeps the safe-core modules (api / kex /
125//     kem / ml_kem / params / rng / symmetric / oid / error) unsafe-
126//     free; only the `mod avx2;` declaration itself carries
127//     `#[allow(unsafe_code)]`, so the SIMD intrinsics + assembly
128//     trampolines are the only place `unsafe` is permitted.
129//   - Phase 1.2 (#143) tracks the full source relocation into a
130//     dedicated `kyberlib-asm` workspace crate. The granular gate
131//     below gives the same *safety property* (safe core stays
132//     unsafe-free under every feature combination) without the
133//     cross-crate refactor.
134#![cfg_attr(
135    not(any(feature = "avx2", feature = "nasm")),
136    forbid(unsafe_code)
137)]
138#![cfg_attr(any(feature = "avx2", feature = "nasm"), deny(unsafe_code))]
139
140// Prevent usage of mutually exclusive features
141#[cfg(all(feature = "kyber1024", feature = "kyber512"))]
142compile_error!("Only one security level can be specified");
143
144// Phase 5 backend selection. `fips` is implemented (module `fips`,
145// issue #170). `verified` is still a reservation (#171): it declares
146// the feature name so downstream consumers can pre-wire it, and is a
147// no-op today. The mutual-exclusion guard between the two lands with
148// the first `verified` implementation; until then `--all-features`
149// enabling both simply uses the `fips` backend.
150
151/// Marker for the `verified` backend (skeleton — see issue #171).
152#[cfg(feature = "verified")]
153#[doc(hidden)]
154pub const __VERIFIED_BACKEND_STUB: &str =
155    "kyberlib `verified` feature is a phase-5 placeholder — see issue #171";
156
157// `#[allow(unsafe_code)]` is the granular exception to the crate-level
158// `deny(unsafe_code)` policy (see the policy block above). The safe-core
159// modules — declared below this — inherit `deny` and stay unsafe-free
160// even under `--features avx2`. Phase 1.2 (#143) relocates this module
161// into `kyberlib-asm` so the source layout matches the safety policy
162// 1:1.
163#[cfg(all(target_arch = "x86_64", feature = "avx2"))]
164// `cfg_attr` (rather than `#[allow]` directly) keeps the `allow` and
165// the cfg-gating in sync — without this, Rust 1.74's E0453 check
166// triggers `allow(unsafe_code) incompatible with previous forbid`
167// before cfg evaluation, even though the module is excluded under
168// default features.
169#[cfg_attr(
170    all(target_arch = "x86_64", feature = "avx2"),
171    allow(unsafe_code)
172)]
173mod avx2;
174#[cfg(all(target_arch = "x86_64", feature = "avx2"))]
175use avx2::*;
176
177#[cfg(any(not(target_arch = "x86_64"), not(feature = "avx2")))]
178/// Reference implementation for the KyberLib library.
179pub mod reference;
180#[cfg(any(not(target_arch = "x86_64"), not(feature = "avx2")))]
181use reference::*;
182
183#[cfg(any(not(target_arch = "x86_64"), not(feature = "avx2")))]
184#[cfg(feature = "hazmat")]
185pub use reference::indcpa;
186
187// WebAssembly bindings live in the dedicated `kyberlib-wasm` workspace
188// crate from v0.0.7 onwards (#144). The `wasm` Cargo feature is retained
189// as a no-op for one release for downstream compatibility.
190
191/// API for the KyberLib library.
192pub mod api;
193/// Error types for the KyberLib library.
194pub mod error;
195/// Hazardous APIs, behind the `hazmat` feature: the `Uake` / `Ake`
196/// key exchanges (#156, ADR 0008).
197#[cfg(feature = "hazmat")]
198pub mod hazmat;
199/// Key encapsulation module for the KyberLib library.
200pub mod kem;
201
202/// Macro utilities for the KyberLib library.
203pub mod macros;
204/// Parameters for the KyberLib library.
205pub mod params;
206
207/// Random number generators for the KyberLib library.
208pub mod rng;
209/// Symmetric key encapsulation module for the KyberLib library.
210pub mod symmetric;
211
212/// FIPS 203 ML-KEM type-state API (v0.0.7 — see issue #130).
213pub mod ml_kem;
214
215/// Seeded key generation and backend dispatch for the typed API.
216mod backend;
217
218/// FIPS 203 §7.2 / §7.3 input checks.
219mod input_check;
220
221/// Typed-key import with the FIPS 203 §7.2 / §7.3 checks.
222mod key_import;
223
224/// FIPS 140-3 backend: routes the typed ML-KEM API through the AWS-LC
225/// FIPS module (feature `fips`, issue #170).
226#[cfg(feature = "fips")]
227pub mod fips;
228
229/// Name of the backend serving the typed ML-KEM API in this build.
230#[cfg(not(feature = "fips"))]
231pub const BACKEND: &str = "kyberlib (pure Rust)";
232/// Name of the backend serving the typed ML-KEM API in this build.
233#[cfg(feature = "fips")]
234pub const BACKEND: &str = fips::BACKEND;
235
236/// Parameter-pack trait unifying ML-KEM-512 / 768 / 1024 — foundation
237/// for the const-generic refactor tracked as #130b.
238pub mod paramsets;
239
240/// Internal test-surface wrappers. **Not part of the public API.**
241///
242/// Wraps the generic FIPS 203 pipeline functions for integration-test
243/// harnesses that need deterministic-seed access across all three
244/// parameter sets (e.g. NIST ACVP). Items here may change or
245/// disappear without warning — downstream code MUST NOT depend on
246/// them.
247#[doc(hidden)]
248pub mod __testing__ {
249    use crate::error::KyberLibError;
250    use crate::paramsets::MlKemParams;
251    use rand_core::{CryptoRng, RngCore};
252
253    /// Wrapper around the crate-internal `kem_keypair_generic`.
254    pub fn kem_keypair_generic<P, R>(
255        pk: &mut [u8],
256        sk: &mut [u8],
257        rng: &mut R,
258        seed: Option<(&[u8], &[u8])>,
259    ) -> Result<(), KyberLibError>
260    where
261        P: MlKemParams,
262        R: RngCore + CryptoRng,
263    {
264        crate::kem::kem_keypair_generic::<P, R>(pk, sk, rng, seed)
265    }
266
267    /// Wrapper around the crate-internal `kem_enc_generic`.
268    pub fn kem_enc_generic<P, R>(
269        ct: &mut [u8],
270        ss: &mut [u8],
271        pk: &[u8],
272        rng: &mut R,
273        seed: Option<&[u8]>,
274    ) -> Result<(), KyberLibError>
275    where
276        P: MlKemParams,
277        R: RngCore + CryptoRng,
278    {
279        crate::kem::kem_enc_generic::<P, R>(ct, ss, pk, rng, seed)
280    }
281
282    /// Wrapper around the crate-internal `kem_dec_generic`.
283    pub fn kem_dec_generic<P: MlKemParams>(
284        ss: &mut [u8],
285        ct: &[u8],
286        sk: &[u8],
287    ) {
288        crate::kem::kem_dec_generic::<P>(ss, ct, sk);
289    }
290}
291
292/// IETF LAMPS object identifiers for ML-KEM parameter sets (v0.0.7
293/// — see issue #150).
294pub mod oid;
295
296pub use api::*;
297pub use error::KyberLibError;
298pub use ml_kem::{
299    KemCore, MlKem1024, MlKem1024Ciphertext, MlKem1024DecapKey,
300    MlKem1024EncapKey, MlKem512, MlKem512Ciphertext, MlKem512DecapKey,
301    MlKem512EncapKey, MlKem768, MlKem768Ciphertext, MlKem768DecapKey,
302    MlKem768EncapKey, SharedSecret,
303};
304pub use params::{
305    // Legacy KYBER_* aliases — retained for downstream-consumer
306    // migration; will tighten to `#[deprecated]` in a future release.
307    KYBER_90S,
308    KYBER_CIPHERTEXT_BYTES,
309    KYBER_PUBLIC_KEY_BYTES,
310    KYBER_SECRET_KEY_BYTES,
311    KYBER_SECURITY_PARAMETER,
312    KYBER_SHARED_SECRET_BYTES,
313    KYBER_SYM_BYTES,
314    // v0.0.7 — canonical ML_KEM_* names (preferred in new code).
315    ML_KEM_90S,
316    ML_KEM_CIPHERTEXT_BYTES,
317    ML_KEM_PUBLIC_KEY_BYTES,
318    ML_KEM_SECRET_KEY_BYTES,
319    ML_KEM_SECURITY_PARAMETER,
320    ML_KEM_SHARED_SECRET_BYTES,
321    ML_KEM_SYM_BYTES,
322};
323pub use paramsets::MlKemParams;
324pub use rand_core::{CryptoRng, RngCore};
325
326// Feature hack to expose private functions for the Known Answer Tests
327// and fuzzing. Will fail to compile if used outside `cargo test` or
328// the fuzz binaries.
329#[cfg(any(
330    KYBER_SECURITY_PARAMETERat,
331    fuzzing,
332    feature = "benchmarking"
333))]
334pub use kem::*;