//! ML-KEM-768 (FIPS 203) install key. //! //! The decapsulation key is stored as the 64-byte seed (`DecapsulationKey::to_seed`), //! the form the crate prefers. The 1184-byte encapsulation key is what an invite //! carries. Ciphertext is 1088 bytes; the shared secret is 32. use ml_kem::kem::{Decapsulate, Encapsulate, Kem}; use ml_kem::{DecapsulationKey768, EncapsulationKey768, KeyExport, MlKem768, Seed}; use zeroize::Zeroizing; pub const PK_LEN: usize = 1184; pub const CT_LEN: usize = 1088; pub const SS_LEN: usize = 32; pub const SEED_LEN: usize = 64; pub type Result = std::result::Result; #[derive(Debug)] pub struct Error(String); impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl std::error::Error for Error {} /// A freshly generated install key. `seed` wipes on drop. pub struct Keypair { pub seed: Zeroizing<[u8; SEED_LEN]>, pub pk: [u8; PK_LEN], } pub fn generate() -> Keypair { let (dk, ek) = MlKem768::generate_keypair(); let seed_arr = dk.to_seed().expect("generate_keypair yields a seed"); let pk_arr = ek.to_bytes(); let mut seed = Zeroizing::new([0u8; SEED_LEN]); let mut pk = [0u8; PK_LEN]; seed.copy_from_slice(seed_arr.as_slice()); pk.copy_from_slice(pk_arr.as_slice()); Keypair { seed, pk } } /// Canonical encapsulation-key bytes. Rejects a length or a key the crate /// will not load, so a garbage `kem=` never becomes a friend row. pub fn encode_pk(pk: &[u8]) -> Result> { let ek = encapsulation_key(pk)?; Ok(ek.to_bytes().as_slice().to_vec()) } pub fn decode_pk(bytes: &[u8]) -> Result> { encode_pk(bytes) } pub fn encapsulate(pk: &[u8]) -> Result<(Vec, Vec)> { let ek = encapsulation_key(pk)?; let (ct, ss) = ek.encapsulate(); Ok((ct.as_slice().to_vec(), ss.as_slice().to_vec())) } /// Ciphertext bytes. Length is the only check: ML-KEM decapsulation of a /// wrong ciphertext does not error (implicit rejection), so a bad ct is /// caught by the handshake prologue, not here. pub fn encode_ct(ct: &[u8]) -> Result> { if ct.len() != CT_LEN { return Err(Error("ct length".into())); } Ok(ct.to_vec()) } pub fn decode_ct(bytes: &[u8]) -> Result> { encode_ct(bytes) } pub fn decapsulate(seed: &[u8], ct: &[u8]) -> Result> { if ct.len() != CT_LEN { return Err(Error("ct length".into())); } let seed_arr = Seed::try_from(seed).map_err(|_| Error("seed length".into()))?; let dk = DecapsulationKey768::from_seed(seed_arr); let ss = dk .decapsulate_slice(ct) .map_err(|_| Error("ct length".into()))?; Ok(ss.as_slice().to_vec()) } fn encapsulation_key(pk: &[u8]) -> Result { if pk.len() != PK_LEN { return Err(Error("pk length".into())); } let key = ml_kem::kem::Key::::try_from(pk) .map_err(|_| Error("pk length".into()))?; EncapsulationKey768::new(&key).map_err(|_| Error("invalid encapsulation key".into())) }