Repository Public Apache-2.0
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SPB Quantum Crypto7// File : crates/spb-pqc-core/src/kem/mod.rs8// Module : Crates9// Repository : https://git.spboucher.ai/spb-quantum-crypto10// Project Website : https://pqce.spboucher.ai11// Created : 2026-12-0312// Last Modified : 2026-12-0313//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : Apache-2.033//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041//! Key-encapsulation mechanisms: typed public API over ML-KEM (FIPS 203).42//!43//! ```44//! use spb_pqc_core::kem::{self, KemAlg};45//! let (pk, sk) = kem::generate_keypair(KemAlg::MlKem768)?;46//! let enc = kem::encapsulate(&pk)?;47//! let shared = kem::decapsulate(&sk, &enc.ciphertext)?;48//! assert_eq!(shared.expose(), enc.shared_secret.expose());49//! # Ok::<(), spb_pqc_core::Error>(())50//! ```51//!52//! A KEM establishes a shared secret; it does not encrypt application data and53//! does not authenticate the sender. Derive symmetric keys from the shared54//! secret with a KDF and use an AEAD (see `docs/security/composition.md`).5556pub mod mlkem;5758use crate::ct::{wipe, Secret};59use crate::error::{Error, Result};60use crate::random;6162/// KEM algorithm identifiers (stable registry names in [`KemAlg::name`]).63#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]64#[non_exhaustive]65pub enum KemAlg {66 /// ML-KEM-512 (NIST security category 1).67 MlKem512,68 /// ML-KEM-768 (NIST security category 3).69 MlKem768,70 /// ML-KEM-1024 (NIST security category 5).71 MlKem1024,72}7374impl KemAlg {75 /// Every KEM, in registry order.76 pub const ALL: [KemAlg; 3] = [KemAlg::MlKem512, KemAlg::MlKem768, KemAlg::MlKem1024];7778 /// Stable registry name.79 pub const fn name(self) -> &'static str {80 match self {81 KemAlg::MlKem512 => "ML-KEM-512",82 KemAlg::MlKem768 => "ML-KEM-768",83 KemAlg::MlKem1024 => "ML-KEM-1024",84 }85 }8687 /// Parses a registry name (exact, case-insensitive).88 pub fn from_name(name: &str) -> Result<Self> {89 Self::ALL90 .into_iter()91 .find(|a| a.name().eq_ignore_ascii_case(name))92 .ok_or(Error::UnsupportedAlgorithm)93 }9495 /// Stable numeric identifier of the SPB registry (`0x01xx` = KEM). This is an96 /// internal, versioned identifier for the C ABI — not an interoperable code point.97 pub const fn id(self) -> u32 {98 match self {99 KemAlg::MlKem512 => 0x0101,100 KemAlg::MlKem768 => 0x0102,101 KemAlg::MlKem1024 => 0x0103,102 }103 }104105 /// Looks an algorithm up by registry identifier.106 pub fn from_id(id: u32) -> Result<Self> {107 Self::ALL108 .into_iter()109 .find(|a| a.id() == id)110 .ok_or(Error::UnsupportedAlgorithm)111 }112113 /// NIST object identifier (`id-alg-ml-kem-*`, arc `2.16.840.1.101.3.4.4`).114 pub const fn oid(self) -> &'static str {115 match self {116 KemAlg::MlKem512 => "2.16.840.1.101.3.4.4.1",117 KemAlg::MlKem768 => "2.16.840.1.101.3.4.4.2",118 KemAlg::MlKem1024 => "2.16.840.1.101.3.4.4.3",119 }120 }121122 /// NIST security category (1, 3 or 5).123 pub const fn security_category(self) -> u8 {124 match self {125 KemAlg::MlKem512 => 1,126 KemAlg::MlKem768 => 3,127 KemAlg::MlKem1024 => 5,128 }129 }130131 pub(crate) const fn params(self) -> mlkem::Params {132 match self {133 KemAlg::MlKem512 => mlkem::MLKEM_512,134 KemAlg::MlKem768 => mlkem::MLKEM_768,135 KemAlg::MlKem1024 => mlkem::MLKEM_1024,136 }137 }138139 /// Encapsulation (public) key length in bytes.140 pub const fn public_key_len(self) -> usize {141 self.params().ek_len()142 }143 /// Decapsulation (private) key length in bytes.144 pub const fn private_key_len(self) -> usize {145 self.params().dk_len()146 }147 /// Ciphertext length in bytes.148 pub const fn ciphertext_len(self) -> usize {149 self.params().ct_len()150 }151 /// Shared-secret length in bytes (32).152 pub const fn shared_secret_len(self) -> usize {153 mlkem::SHARED_SECRET_LEN154 }155}156157/// A validated ML-KEM encapsulation key.158#[derive(Clone, Debug, PartialEq, Eq)]159pub struct KemPublicKey {160 alg: KemAlg,161 bytes: Vec<u8>,162}163164impl KemPublicKey {165 /// Imports an encapsulation key, running the FIPS 203 §7.2 input checks166 /// (length and modulus check). Non-canonical encodings are rejected.167 pub fn from_bytes(alg: KemAlg, bytes: &[u8]) -> Result<Self> {168 mlkem::check_encapsulation_key(&alg.params(), bytes)?;169 Ok(KemPublicKey {170 alg,171 bytes: bytes.to_vec(),172 })173 }174 /// The algorithm this key belongs to.175 pub fn algorithm(&self) -> KemAlg {176 self.alg177 }178 /// The FIPS 203 byte encoding.179 pub fn as_bytes(&self) -> &[u8] {180 &self.bytes181 }182}183184/// A validated ML-KEM decapsulation key. Wiped on drop; not `Clone`, and its185/// `Debug` output is redacted.186#[derive(Debug)]187pub struct KemPrivateKey {188 alg: KemAlg,189 bytes: Secret,190}191192impl KemPrivateKey {193 /// Imports a decapsulation key, running the FIPS 203 §7.3 input checks194 /// (length and hash check).195 pub fn from_bytes(alg: KemAlg, bytes: &[u8]) -> Result<Self> {196 mlkem::check_decapsulation_key(&alg.params(), bytes)?;197 Ok(KemPrivateKey {198 alg,199 bytes: Secret::from_slice(bytes),200 })201 }202 /// The algorithm this key belongs to.203 pub fn algorithm(&self) -> KemAlg {204 self.alg205 }206 /// The FIPS 203 byte encoding. Handle with care: never log or display it.207 pub fn expose_bytes(&self) -> &[u8] {208 self.bytes.expose()209 }210 /// The encapsulation key embedded in this decapsulation key.211 pub fn public_key(&self) -> Result<KemPublicKey> {212 let k = self.alg.params().k;213 KemPublicKey::from_bytes(self.alg, &self.bytes.expose()[384 * k..768 * k + 32])214 }215}216217/// A 32-byte shared secret. Wiped on drop; not `Clone`; redacted `Debug`.218#[derive(Debug)]219pub struct SharedSecret(Secret);220221impl SharedSecret {222 /// The secret bytes. Feed them to a KDF; never use them directly as a long-term key.223 pub fn expose(&self) -> &[u8] {224 self.0.expose()225 }226}227228/// Result of [`encapsulate`]: the ciphertext to send and the local shared secret.229#[derive(Debug)]230pub struct Encapsulation {231 /// Ciphertext to transmit to the holder of the decapsulation key.232 pub ciphertext: Vec<u8>,233 /// The shared secret on the encapsulating side.234 pub shared_secret: SharedSecret,235}236237/// `ML-KEM.KeyGen` (FIPS 203 Algorithm 19): fresh `d` and `z` from the OS CSPRNG.238pub fn generate_keypair(alg: KemAlg) -> Result<(KemPublicKey, KemPrivateKey)> {239 let p = alg.params();240 let mut d = [0u8; 32];241 let mut z = [0u8; 32];242 let seeded = random::fill(&mut d).and_then(|_| random::fill(&mut z));243 if let Err(e) = seeded {244 wipe(&mut d);245 wipe(&mut z);246 return Err(e);247 }248 let mut ek = vec![0u8; p.ek_len()];249 let mut dk = Secret::zeroed(p.dk_len());250 let res = mlkem::keygen_internal(&p, &d, &z, &mut ek, dk.expose_mut());251 wipe(&mut d);252 wipe(&mut z);253 res?;254 Ok((255 KemPublicKey { alg, bytes: ek },256 KemPrivateKey { alg, bytes: dk },257 ))258}259260/// `ML-KEM.Encaps` (FIPS 203 Algorithm 20): fresh `m` from the OS CSPRNG.261/// The key was validated when it was imported.262pub fn encapsulate(pk: &KemPublicKey) -> Result<Encapsulation> {263 let p = pk.alg.params();264 let mut m = [0u8; 32];265 random::fill(&mut m)?;266 let mut ciphertext = vec![0u8; p.ct_len()];267 let res = mlkem::encaps_internal(&p, &pk.bytes, &m, &mut ciphertext);268 wipe(&mut m);269 let mut key = res?;270 let shared_secret = SharedSecret(Secret::from_slice(&key));271 wipe(&mut key);272 Ok(Encapsulation {273 ciphertext,274 shared_secret,275 })276}277278/// `ML-KEM.Decaps` (FIPS 203 Algorithm 21).279///280/// A ciphertext of the wrong length is rejected with [`Error::InvalidCiphertext`]281/// (type check). A ciphertext of the right length that was not produced for282/// this key yields a pseudorandom secret (implicit rejection) — this function283/// does not, and must not, reveal which case occurred.284pub fn decapsulate(sk: &KemPrivateKey, ciphertext: &[u8]) -> Result<SharedSecret> {285 let p = sk.alg.params();286 let mut key = mlkem::decaps_internal(&p, sk.bytes.expose(), ciphertext)?;287 let out = SharedSecret(Secret::from_slice(&key));288 wipe(&mut key);289 Ok(out)290}291292#[cfg(test)]293mod tests {294 use super::*;295296 #[test]297 fn api_round_trip_all_parameter_sets() {298 for alg in KemAlg::ALL {299 let (pk, sk) = generate_keypair(alg).unwrap();300 assert_eq!(pk.as_bytes().len(), alg.public_key_len());301 assert_eq!(sk.expose_bytes().len(), alg.private_key_len());302 assert_eq!(sk.public_key().unwrap(), pk);303 let enc = encapsulate(&pk).unwrap();304 assert_eq!(enc.ciphertext.len(), alg.ciphertext_len());305 let ss = decapsulate(&sk, &enc.ciphertext).unwrap();306 assert_eq!(ss.expose(), enc.shared_secret.expose());307 assert_eq!(ss.expose().len(), 32);308309 // serialisation round trip310 let pk2 = KemPublicKey::from_bytes(alg, pk.as_bytes()).unwrap();311 let sk2 = KemPrivateKey::from_bytes(alg, sk.expose_bytes()).unwrap();312 let enc2 = encapsulate(&pk2).unwrap();313 assert_eq!(314 decapsulate(&sk2, &enc2.ciphertext).unwrap().expose(),315 enc2.shared_secret.expose()316 );317 assert_eq!(KemAlg::from_name(alg.name()).unwrap(), alg);318 }319 }320321 #[test]322 fn rng_failure_aborts_every_randomised_operation() {323 let (pk, _sk) = generate_keypair(KemAlg::MlKem512).unwrap();324 random::testing::force_failure(true);325 assert_eq!(326 generate_keypair(KemAlg::MlKem512).err(),327 Some(Error::RandomFailure)328 );329 assert_eq!(encapsulate(&pk).err(), Some(Error::RandomFailure));330 random::testing::force_failure(false);331 }332333 #[test]334 fn wrong_algorithm_lengths_are_rejected() {335 let (pk, sk) = generate_keypair(KemAlg::MlKem512).unwrap();336 assert_eq!(337 KemPublicKey::from_bytes(KemAlg::MlKem768, pk.as_bytes()).err(),338 Some(Error::InvalidLength)339 );340 assert_eq!(341 KemPrivateKey::from_bytes(KemAlg::MlKem1024, sk.expose_bytes()).err(),342 Some(Error::InvalidLength)343 );344 assert_eq!(345 decapsulate(&sk, &[0u8; 10]).err(),346 Some(Error::InvalidCiphertext)347 );348 assert!(format!("{sk:?}").contains("REDACTED"));349 }350}351