#[cfg(feature = "suite-max")]
use libcrux_ml_kem::mlkem1024::{MlKem1024Ciphertext, MlKem1024PrivateKey, MlKem1024PublicKey, portable as mlkem1024};
#[cfg(feature = "suite-max")]
use p384::elliptic_curve::Generate;
#[cfg(feature = "suite-max")]
use p384::elliptic_curve::sec1::ToSec1Point;
use sha3::{Digest, Sha3_256};
#[cfg(feature = "suite-xwing")]
use x_wing::{DecapsulationKeyRejectNonContrib, Decapsulator, KeyExport, TryDecapsulate};
#[cfg(feature = "suite-max")]
use zeroize::Zeroize;
use zeroize::{ZeroizeOnDrop, Zeroizing};
use crate::format::{self, Kind, VERSION_2, fields};
use crate::{Error, Result, Rng, Suite, SuitePolicy};
pub const SHARED_SECRET_LEN: usize = 32;
pub const MLKEM1024_EK_LEN: usize = 1568;
pub const MLKEM1024_CT_LEN: usize = 1568;
pub const MLKEM_SEED_LEN: usize = 64;
pub const P384_POINT_LEN: usize = 97;
pub const P384_SCALAR_LEN: usize = 48;
pub const MCELIECE_PK_LEN: usize = 1_357_824;
pub const MCELIECE_SK_LEN: usize = 14_120;
pub const MCELIECE_CT_LEN: usize = 208;
#[cfg(feature = "paranoid")]
const _: () = assert!(
MCELIECE_PK_LEN == classic_mceliece_rust::CRYPTO_PUBLICKEYBYTES
&& MCELIECE_SK_LEN == classic_mceliece_rust::CRYPTO_SECRETKEYBYTES
&& MCELIECE_CT_LEN == classic_mceliece_rust::CRYPTO_CIPHERTEXTBYTES
);
pub const FINGERPRINT_LEN: usize = 32;
pub const LABEL_MAX: &[u8] = b"pqbox/v1/kem-max";
pub const LABEL_PARANOID: &[u8] = b"pqbox/v1/kem-paranoid";
#[must_use]
pub fn public_key_len(suite: Suite) -> usize {
match suite {
#[cfg(feature = "suite-xwing")]
Suite::XWing => x_wing::ENCAPSULATION_KEY_SIZE,
#[cfg(feature = "suite-max")]
Suite::Max => MLKEM1024_EK_LEN + P384_POINT_LEN,
#[cfg(feature = "paranoid")]
Suite::Paranoid => MLKEM1024_EK_LEN + MCELIECE_PK_LEN + P384_POINT_LEN,
}
}
#[must_use]
pub fn secret_key_len(suite: Suite) -> usize {
match suite {
#[cfg(feature = "suite-xwing")]
Suite::XWing => x_wing::DECAPSULATION_KEY_SIZE,
#[cfg(feature = "suite-max")]
Suite::Max => MLKEM_SEED_LEN + P384_SCALAR_LEN,
#[cfg(feature = "paranoid")]
Suite::Paranoid => MLKEM_SEED_LEN + MCELIECE_SK_LEN + P384_SCALAR_LEN + MCELIECE_PK_LEN + FINGERPRINT_LEN,
}
}
#[must_use]
pub fn ciphertext_len(suite: Suite) -> usize {
match suite {
#[cfg(feature = "suite-xwing")]
Suite::XWing => x_wing::CIPHERTEXT_SIZE,
#[cfg(feature = "suite-max")]
Suite::Max => MLKEM1024_CT_LEN + P384_POINT_LEN,
#[cfg(feature = "paranoid")]
Suite::Paranoid => MLKEM1024_CT_LEN + MCELIECE_CT_LEN + P384_POINT_LEN,
}
}
#[derive(Clone)]
pub struct SharedSecret(Zeroizing<[u8; SHARED_SECRET_LEN]>);
impl ZeroizeOnDrop for SharedSecret {}
impl SharedSecret {
#[cfg(feature = "suite-xwing")]
fn copy_from(bytes: &[u8]) -> Result<Self> {
let mut out = Zeroizing::new([0u8; SHARED_SECRET_LEN]);
if bytes.len() != SHARED_SECRET_LEN {
return Err(Error::InvalidLength("shared secret"));
}
out.copy_from_slice(bytes);
Ok(Self(out))
}
#[must_use]
pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
&self.0
}
}
impl PartialEq for SharedSecret {
fn eq(&self, other: &Self) -> bool {
crate::ct_eq(&*self.0, &*other.0)
}
}
impl Eq for SharedSecret {}
impl core::fmt::Debug for SharedSecret {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("SharedSecret(<redacted>)")
}
}
#[cfg(feature = "suite-max")]
type MlEk = MlKem1024PublicKey;
#[cfg(feature = "suite-max")]
struct MlDk(MlKem1024PrivateKey);
#[cfg(feature = "suite-max")]
impl Zeroize for MlDk {
fn zeroize(&mut self) {
core::ops::IndexMut::index_mut(&mut self.0, 0..).zeroize();
}
}
#[cfg(feature = "suite-max")]
impl Drop for MlDk {
fn drop(&mut self) {
self.zeroize();
}
}
#[cfg(feature = "suite-max")]
impl ZeroizeOnDrop for MlDk {}
#[derive(Clone)]
enum PkInner {
#[cfg(feature = "suite-xwing")]
XWing(Box<x_wing::EncapsulationKey>),
#[cfg(feature = "suite-max")]
Max { ml: Box<MlEk>, ec: p384::PublicKey },
#[cfg(feature = "paranoid")]
Paranoid {
ml: Box<MlEk>,
mce: Box<[u8; MCELIECE_PK_LEN]>,
ec: p384::PublicKey,
},
}
#[derive(Clone)]
pub struct PublicKey {
suite: Suite,
inner: PkInner,
raw: Vec<u8>,
}
impl PartialEq for PublicKey {
fn eq(&self, other: &Self) -> bool {
self.suite == other.suite && self.raw == other.raw
}
}
impl Eq for PublicKey {}
impl core::fmt::Debug for PublicKey {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "kem::PublicKey({}, {} bytes)", self.suite, self.raw.len())
}
}
fn fingerprint(suite: Suite, raw: &[u8]) -> [u8; FINGERPRINT_LEN] {
let header = format::Header::current(Kind::KemPublicKey, suite.id()).to_bytes();
Sha3_256::new().chain_update(header).chain_update(raw).finalize().into()
}
#[cfg(feature = "suite-max")]
fn mlkem_ek(raw: &[u8]) -> Result<Box<MlEk>> {
let key = MlEk::try_from(raw).map_err(|_| Error::InvalidLength("ML-KEM-1024 public key"))?;
if !mlkem1024::validate_public_key(&key) {
return Err(Error::InvalidKey);
}
Ok(Box::new(key))
}
#[cfg(feature = "suite-max")]
fn mlkem_encapsulate<R: Rng + ?Sized>(ek: &MlEk, rng: &mut R) -> (MlKem1024Ciphertext, Zeroizing<[u8; 32]>) {
let m = Zeroizing::new(crate::random::<32, R>(rng));
let (ct, ss) = mlkem1024::encapsulate(ek, *m);
(ct, Zeroizing::new(ss))
}
#[cfg(feature = "suite-max")]
pub(crate) fn p384_point(raw: &[u8]) -> Result<p384::PublicKey> {
if raw.len() != P384_POINT_LEN || raw.first() != Some(&0x04) {
return Err(Error::InvalidKey);
}
p384::PublicKey::from_sec1_bytes(raw).map_err(|_| Error::InvalidKey)
}
#[cfg(feature = "suite-max")]
fn p384_encode(pk: &p384::PublicKey) -> Vec<u8> {
pk.to_sec1_point(false).as_bytes().to_vec()
}
#[cfg(feature = "paranoid")]
fn boxed_array<const N: usize>(raw: &[u8], what: &'static str) -> Result<Box<[u8; N]>> {
raw.to_vec()
.into_boxed_slice()
.try_into()
.map_err(|_| Error::InvalidLength(what))
}
impl PublicKey {
pub fn from_raw(suite: Suite, raw: &[u8]) -> Result<Self> {
let inner = match suite {
#[cfg(feature = "suite-xwing")]
Suite::XWing => {
let [_, x] = fields(raw, [x_wing::ENCAPSULATION_KEY_SIZE - 32, 32], "KEM public key")?;
let x: [u8; 32] = x.try_into().map_err(|_| Error::InvalidLength("KEM public key"))?;
crate::hazmat::x25519_check_public(&x)?;
PkInner::XWing(Box::new(
x_wing::EncapsulationKey::try_from(raw).map_err(|_| Error::InvalidKey)?,
))
}
#[cfg(feature = "suite-max")]
Suite::Max => {
let [ml, ec] = fields(raw, [MLKEM1024_EK_LEN, P384_POINT_LEN], "KEM public key")?;
PkInner::Max {
ml: mlkem_ek(ml)?,
ec: p384_point(ec)?,
}
}
#[cfg(feature = "paranoid")]
Suite::Paranoid => {
let [ml, mce, ec] = fields(
raw,
[MLKEM1024_EK_LEN, MCELIECE_PK_LEN, P384_POINT_LEN],
"KEM public key",
)?;
PkInner::Paranoid {
ml: mlkem_ek(ml)?,
mce: boxed_array(mce, "KEM public key")?,
ec: p384_point(ec)?,
}
}
};
Ok(Self {
suite,
inner,
raw: raw.to_vec(),
})
}
#[must_use]
pub fn suite(&self) -> Suite {
self.suite
}
#[must_use]
pub fn as_raw(&self) -> &[u8] {
&self.raw
}
#[must_use]
pub fn fingerprint(&self) -> [u8; FINGERPRINT_LEN] {
fingerprint(self.suite, &self.raw)
}
#[must_use]
pub fn to_bytes(&self) -> Vec<u8> {
format::encode(Kind::KemPublicKey, self.suite.id(), &[&self.raw])
}
pub fn from_bytes(data: &[u8]) -> Result<Self> {
Self::from_bytes_with_policy(data, SuitePolicy::DEFAULT)
}
pub fn from_bytes_with_policy(data: &[u8], policy: SuitePolicy) -> Result<Self> {
match format::expect(data, Kind::KemPublicKey)? {
(h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
(h, _) => Err(Error::UnsupportedVersion(h.version)),
}
}
pub fn encapsulate<R: Rng + ?Sized>(&self, rng: &mut R) -> Result<(Ciphertext, SharedSecret)> {
match &self.inner {
#[cfg(feature = "suite-xwing")]
PkInner::XWing(ek) => {
let (ct, ss) = x_wing::Encapsulate::encapsulate_with_rng(&**ek, rng);
let ss = Zeroizing::new(ss);
Ok((
Ciphertext {
suite: self.suite,
raw: ct.to_vec(),
},
SharedSecret::copy_from(&ss)?,
))
}
#[cfg(feature = "suite-max")]
PkInner::Max { ml, ec } => {
let (ct_m, ss_m) = mlkem_encapsulate(ml, rng);
let (ct_x, ss_x) = p384_encapsulate(ec, rng);
let pk_x = p384_encode(ec);
let ss = combine_max(&*ss_m, &ss_x, &ct_x, &pk_x);
Ok((
Ciphertext {
suite: self.suite,
raw: [ct_m.as_ref(), &ct_x].concat(),
},
ss,
))
}
#[cfg(feature = "paranoid")]
PkInner::Paranoid { ml, mce, ec } => {
let (ct_m, ss_m) = mlkem_encapsulate(ml, rng);
let mce_pk = classic_mceliece_rust::PublicKey::from(mce.clone());
let (ct_c, ss_c) = classic_mceliece_rust::encapsulate_boxed(&mce_pk, &mut Rng06(rng));
let (ct_x, ss_x) = p384_encapsulate(ec, rng);
let pk_x = p384_encode(ec);
let ss = combine_paranoid(
&*ss_m,
ss_c.as_array(),
&ss_x,
&ct_x,
&pk_x,
ct_m.as_ref(),
ct_c.as_array(),
);
Ok((
Ciphertext {
suite: self.suite,
raw: [ct_m.as_ref(), ct_c.as_array(), &ct_x].concat(),
},
ss,
))
}
}
}
}
#[cfg(feature = "suite-max")]
fn p384_encapsulate<R: Rng + ?Sized>(pk: &p384::PublicKey, rng: &mut R) -> (Vec<u8>, Zeroizing<[u8; 48]>) {
let esk = <p384::ecdh::EphemeralSecret as Generate>::generate_from_rng(rng);
let ct = p384_encode(&esk.public_key());
let ss = esk.diffie_hellman(pk);
let mut out = Zeroizing::new([0u8; 48]);
out.copy_from_slice(ss.raw_secret_bytes());
(ct, out)
}
#[cfg(feature = "suite-max")]
fn combine_max(ss_m: &[u8], ss_x: &[u8; 48], ct_x: &[u8], pk_x: &[u8]) -> SharedSecret {
let ss: [u8; 32] = Sha3_256::new()
.chain_update(ss_m)
.chain_update(ss_x)
.chain_update(ct_x)
.chain_update(pk_x)
.chain_update(LABEL_MAX)
.finalize()
.into();
SharedSecret(Zeroizing::new(ss))
}
#[cfg(feature = "paranoid")]
fn combine_paranoid(
ss_m: &[u8],
ss_c: &[u8],
ss_x: &[u8; 48],
ct_x: &[u8],
pk_x: &[u8],
ct_m: &[u8],
ct_c: &[u8],
) -> SharedSecret {
let ss: [u8; 32] = Sha3_256::new()
.chain_update(ss_m)
.chain_update(ss_c)
.chain_update(ss_x)
.chain_update(ct_x)
.chain_update(pk_x)
.chain_update(Sha3_256::digest(ct_m))
.chain_update(Sha3_256::digest(ct_c))
.chain_update(LABEL_PARANOID)
.finalize()
.into();
SharedSecret(Zeroizing::new(ss))
}
#[derive(Clone, PartialEq, Eq)]
pub struct Ciphertext {
suite: Suite,
raw: Vec<u8>,
}
impl core::fmt::Debug for Ciphertext {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "kem::Ciphertext({}, {} bytes)", self.suite, self.raw.len())
}
}
impl Ciphertext {
pub fn from_raw(suite: Suite, raw: &[u8]) -> Result<Self> {
if raw.len() != ciphertext_len(suite) {
return Err(Error::InvalidLength("KEM ciphertext"));
}
Ok(Self {
suite,
raw: raw.to_vec(),
})
}
#[must_use]
pub fn suite(&self) -> Suite {
self.suite
}
#[must_use]
pub fn as_raw(&self) -> &[u8] {
&self.raw
}
#[must_use]
pub fn to_bytes(&self) -> Vec<u8> {
format::encode(Kind::KemCiphertext, self.suite.id(), &[&self.raw])
}
pub fn from_bytes(data: &[u8]) -> Result<Self> {
Self::from_bytes_with_policy(data, SuitePolicy::DEFAULT)
}
pub fn from_bytes_with_policy(data: &[u8], policy: SuitePolicy) -> Result<Self> {
match format::expect(data, Kind::KemCiphertext)? {
(h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
(h, _) => Err(Error::UnsupportedVersion(h.version)),
}
}
}
enum SkInner {
#[cfg(feature = "suite-xwing")]
XWing(Box<DecapsulationKeyRejectNonContrib>),
#[cfg(feature = "suite-max")]
Max { ml: Box<MlDk>, ec: p384::SecretKey },
#[cfg(feature = "paranoid")]
Paranoid {
ml: Box<MlDk>,
mce: classic_mceliece_rust::SecretKey<'static>,
ec: p384::SecretKey,
},
}
pub struct SecretKey {
inner: SkInner,
secret: Zeroizing<Vec<u8>>,
public: PublicKey,
}
impl ZeroizeOnDrop for SecretKey {}
impl core::fmt::Debug for SecretKey {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "kem::SecretKey({}, <redacted>)", self.public.suite)
}
}
#[cfg(feature = "paranoid")]
struct Rng06<'a, R: ?Sized>(&'a mut R);
#[cfg(feature = "paranoid")]
impl<R: Rng + ?Sized> rand_core_06::RngCore for Rng06<'_, R> {
fn next_u32(&mut self) -> u32 {
rand_core::Rng::next_u32(self.0)
}
fn next_u64(&mut self) -> u64 {
rand_core::Rng::next_u64(self.0)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
rand_core::Rng::fill_bytes(self.0, dest);
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> core::result::Result<(), rand_core_06::Error> {
rand_core::Rng::fill_bytes(self.0, dest);
Ok(())
}
}
#[cfg(feature = "paranoid")]
impl<R: Rng + ?Sized> rand_core_06::CryptoRng for Rng06<'_, R> {}
#[cfg(feature = "suite-max")]
fn mlkem_keypair(seed: &[u8]) -> Result<(Box<MlDk>, Vec<u8>)> {
let seed: Zeroizing<[u8; MLKEM_SEED_LEN]> =
Zeroizing::new(seed.try_into().map_err(|_| Error::InvalidLength("KEM secret key"))?);
let (dk, ek) = mlkem1024::generate_key_pair(*seed).into_parts();
Ok((Box::new(MlDk(dk)), ek.as_ref().to_vec()))
}
#[cfg(feature = "suite-max")]
fn p384_secret(raw: &[u8]) -> Result<p384::SecretKey> {
p384::SecretKey::from_slice(raw).map_err(|_| Error::InvalidKey)
}
impl SecretKey {
pub fn generate<R: Rng + ?Sized>(suite: Suite, rng: &mut R) -> Result<Self> {
match suite {
#[cfg(feature = "suite-xwing")]
Suite::XWing => {
let seed = Zeroizing::new(crate::random::<32, R>(rng));
Self::from_raw(suite, &seed[..])
}
#[cfg(feature = "suite-max")]
Suite::Max => {
let seed = Zeroizing::new(crate::random::<MLKEM_SEED_LEN, R>(rng));
let ec = <p384::SecretKey as Generate>::generate_from_rng(rng);
let ec_bytes = Zeroizing::new(ec.to_bytes());
let raw = Zeroizing::new([&seed[..], &ec_bytes[..]].concat());
Self::from_raw(suite, &raw)
}
#[cfg(feature = "paranoid")]
Suite::Paranoid => {
let seed = Zeroizing::new(crate::random::<MLKEM_SEED_LEN, R>(rng));
let ec = <p384::SecretKey as Generate>::generate_from_rng(rng);
let (mce_public, mce_secret) = classic_mceliece_rust::keypair_boxed(&mut Rng06(rng));
let ec_bytes = Zeroizing::new(ec.to_bytes());
let public = [
mlkem_keypair(&seed[..])?.1,
mce_public.as_array().to_vec(),
p384_encode(&ec.public_key()),
]
.concat();
let raw = Zeroizing::new(
[
&seed[..],
mce_secret.as_array(),
&ec_bytes[..],
mce_public.as_array(),
&fingerprint(suite, &public),
]
.concat(),
);
Self::from_raw(suite, &raw)
}
}
}
pub fn from_raw(suite: Suite, raw: &[u8]) -> Result<Self> {
let (inner, public_raw, bound_fingerprint): (SkInner, Vec<u8>, Option<&[u8]>) = match suite {
#[cfg(feature = "suite-xwing")]
Suite::XWing => {
let seed: Zeroizing<[u8; 32]> =
Zeroizing::new(raw.try_into().map_err(|_| Error::InvalidLength("KEM secret key"))?);
let dk = DecapsulationKeyRejectNonContrib::from(*seed);
let pk = KeyExport::to_bytes(dk.encapsulation_key()).to_vec();
(SkInner::XWing(Box::new(dk)), pk, None)
}
#[cfg(feature = "suite-max")]
Suite::Max => {
let [seed, ec] = fields(raw, [MLKEM_SEED_LEN, P384_SCALAR_LEN], "KEM secret key")?;
let (ml, ml_pk) = mlkem_keypair(seed)?;
let ec = p384_secret(ec)?;
let pk = [ml_pk, p384_encode(&ec.public_key())].concat();
(SkInner::Max { ml, ec }, pk, None)
}
#[cfg(feature = "paranoid")]
Suite::Paranoid => {
let [seed, mce_secret, ec, mce_public, bound] = fields(
raw,
[
MLKEM_SEED_LEN,
MCELIECE_SK_LEN,
P384_SCALAR_LEN,
MCELIECE_PK_LEN,
FINGERPRINT_LEN,
],
"KEM secret key",
)?;
let (ml, ml_pk) = mlkem_keypair(seed)?;
let ec = p384_secret(ec)?;
let mce = classic_mceliece_rust::SecretKey::from(boxed_array::<MCELIECE_SK_LEN>(
mce_secret,
"KEM secret key",
)?);
let pk = [ml_pk, mce_public.to_vec(), p384_encode(&ec.public_key())].concat();
(SkInner::Paranoid { ml, mce, ec }, pk, Some(bound))
}
};
let public = PublicKey::from_raw(suite, &public_raw)?;
if let Some(bound) = bound_fingerprint
&& !crate::ct_eq(&public.fingerprint(), bound)
{
return Err(Error::InvalidKey);
}
Ok(Self {
inner,
secret: Zeroizing::new(raw.to_vec()),
public,
})
}
#[must_use]
pub fn suite(&self) -> Suite {
self.public.suite
}
#[must_use]
pub fn public_key(&self) -> &PublicKey {
&self.public
}
#[must_use]
pub fn as_raw(&self) -> &[u8] {
&self.secret
}
#[must_use]
pub fn to_bytes(&self) -> Zeroizing<Vec<u8>> {
Zeroizing::new(format::encode(Kind::KemSecretKey, self.suite().id(), &[&self.secret]))
}
pub fn from_bytes(data: &[u8]) -> Result<Self> {
Self::from_bytes_with_policy(data, SuitePolicy::DEFAULT)
}
pub fn from_bytes_with_policy(data: &[u8], policy: SuitePolicy) -> Result<Self> {
match format::expect(data, Kind::KemSecretKey)? {
(h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
(h, _) => Err(Error::UnsupportedVersion(h.version)),
}
}
pub fn decapsulate(&self, ct: &Ciphertext) -> Result<SharedSecret> {
if ct.suite != self.suite() {
return Err(Error::SuiteMismatch {
expected: self.suite().name(),
found: ct.suite.name(),
});
}
match &self.inner {
#[cfg(feature = "suite-xwing")]
SkInner::XWing(dk) => {
let c = x_wing::Ciphertext::try_from(ct.raw.as_slice())
.map_err(|_| Error::InvalidLength("KEM ciphertext"))?;
let ss = Zeroizing::new(dk.try_decapsulate(&c).map_err(|_| Error::Decrypt)?);
SharedSecret::copy_from(&ss)
}
#[cfg(feature = "suite-max")]
SkInner::Max { ml, ec } => {
let [ct_m, ct_x] = fields(&ct.raw, [MLKEM1024_CT_LEN, P384_POINT_LEN], "KEM ciphertext")?;
let ss_m = mlkem_decapsulate(ml, ct_m)?;
let ss_x = p384_decapsulate(ec, ct_x)?;
let pk_x = p384_encode(&ec.public_key());
Ok(combine_max(&*ss_m, &ss_x, ct_x, &pk_x))
}
#[cfg(feature = "paranoid")]
SkInner::Paranoid { ml, mce, ec } => {
let [ct_m, ct_c, ct_x] = fields(
&ct.raw,
[MLKEM1024_CT_LEN, MCELIECE_CT_LEN, P384_POINT_LEN],
"KEM ciphertext",
)?;
let ss_m = mlkem_decapsulate(ml, ct_m)?;
let ct_c_arr: [u8; MCELIECE_CT_LEN] =
ct_c.try_into().map_err(|_| Error::InvalidLength("KEM ciphertext"))?;
let ss_c = classic_mceliece_rust::decapsulate_boxed(&ct_c_arr.into(), mce);
let ss_x = p384_decapsulate(ec, ct_x)?;
let pk_x = p384_encode(&ec.public_key());
Ok(combine_paranoid(
&*ss_m,
ss_c.as_array(),
&ss_x,
ct_x,
&pk_x,
ct_m,
ct_c,
))
}
}
}
}
#[cfg(feature = "suite-max")]
fn mlkem_decapsulate(dk: &MlDk, ct: &[u8]) -> Result<Zeroizing<[u8; 32]>> {
let ct = MlKem1024Ciphertext::try_from(ct).map_err(|_| Error::InvalidLength("KEM ciphertext"))?;
Ok(Zeroizing::new(mlkem1024::decapsulate(&dk.0, &ct)))
}
#[cfg(feature = "suite-max")]
fn p384_decapsulate(sk: &p384::SecretKey, ct: &[u8]) -> Result<Zeroizing<[u8; 48]>> {
let point = p384_point(ct).map_err(|_| Error::Decrypt)?;
let ss = sk.diffie_hellman(&point);
let mut out = Zeroizing::new([0u8; 48]);
out.copy_from_slice(ss.raw_secret_bytes());
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::rng;
fn suites() -> impl Iterator<Item = Suite> {
Suite::ALL.into_iter()
}
#[test]
fn round_trip_every_suite() {
let mut rng = rng();
for suite in suites() {
let sk = SecretKey::generate(suite, &mut rng).unwrap();
assert_eq!(sk.as_raw().len(), secret_key_len(suite));
assert_eq!(sk.public_key().as_raw().len(), public_key_len(suite));
let (ct, ss) = sk.public_key().encapsulate(&mut rng).unwrap();
assert_eq!(ct.as_raw().len(), ciphertext_len(suite));
assert_eq!(sk.decapsulate(&ct).unwrap(), ss);
let all = SuitePolicy::ALL;
let sk2 = SecretKey::from_bytes_with_policy(&sk.to_bytes(), all).unwrap();
assert_eq!(sk2.public_key(), sk.public_key());
let pk = PublicKey::from_bytes_with_policy(&sk.public_key().to_bytes(), all).unwrap();
assert_eq!(&pk, sk.public_key());
assert_eq!(Ciphertext::from_bytes_with_policy(&ct.to_bytes(), all).unwrap(), ct);
let default = PublicKey::from_bytes(&sk.public_key().to_bytes());
if suite.id() == 0x02 {
assert_eq!(default.unwrap(), pk);
} else {
assert_eq!(default.unwrap_err(), Error::SuiteNotAllowed(suite.name()));
assert_eq!(
SecretKey::from_bytes(&sk.to_bytes()).unwrap_err(),
Error::SuiteNotAllowed(suite.name())
);
assert_eq!(
Ciphertext::from_bytes(&ct.to_bytes()).unwrap_err(),
Error::SuiteNotAllowed(suite.name())
);
}
}
}
#[test]
fn wrong_key_gives_unrelated_secret() {
let mut rng = rng();
for suite in suites() {
let a = SecretKey::generate(suite, &mut rng).unwrap();
let b = SecretKey::generate(suite, &mut rng).unwrap();
let (ct, ss) = a.public_key().encapsulate(&mut rng).unwrap();
assert_ne!(b.decapsulate(&ct).unwrap(), ss);
}
}
#[cfg(all(feature = "suite-max", feature = "suite-xwing"))]
#[test]
fn cross_suite_is_rejected() {
let mut rng = rng();
let x = SecretKey::generate(Suite::XWing, &mut rng).unwrap();
let m = SecretKey::generate(Suite::Max, &mut rng).unwrap();
let (ct, _) = x.public_key().encapsulate(&mut rng).unwrap();
assert!(matches!(m.decapsulate(&ct), Err(Error::SuiteMismatch { .. })));
let mut relabeled = m.public_key().to_bytes();
relabeled[5] = Suite::XWing.id();
assert_eq!(
PublicKey::from_bytes_with_policy(&relabeled, SuitePolicy::ALL),
Err(Error::InvalidLength("KEM public key"))
);
}
#[cfg(feature = "paranoid")]
#[test]
fn paranoid_secret_key_binds_its_public_key() {
let mut rng = rng();
let a = SecretKey::generate(Suite::Paranoid, &mut rng).unwrap();
let b = SecretKey::generate(Suite::Paranoid, &mut rng).unwrap();
let start = MLKEM_SEED_LEN + MCELIECE_SK_LEN + P384_SCALAR_LEN;
let mce = start..start + MCELIECE_PK_LEN;
assert_eq!(a.as_raw().len(), mce.end + FINGERPRINT_LEN);
assert_eq!(&a.as_raw()[mce.end..], a.public_key().fingerprint());
let mut franken = a.as_raw().to_vec();
franken[mce.clone()].copy_from_slice(&b.as_raw()[mce.clone()]);
assert_eq!(
SecretKey::from_raw(Suite::Paranoid, &franken).unwrap_err(),
Error::InvalidKey
);
for pos in [
mce.start,
mce.start + MCELIECE_PK_LEN / 2,
mce.end - 1,
0,
31,
start - 1,
mce.end,
a.as_raw().len() - 1,
] {
let mut raw = a.as_raw().to_vec();
raw[pos] ^= 1;
assert!(
matches!(SecretKey::from_raw(Suite::Paranoid, &raw), Err(Error::InvalidKey)),
"flip at {pos} accepted"
);
}
assert_eq!(
SecretKey::from_raw(Suite::Paranoid, a.as_raw()).unwrap().public_key(),
a.public_key()
);
}
#[test]
fn debug_redacts_secrets() {
let mut rng = rng();
let sk = SecretKey::generate(Suite::ALL[0], &mut rng).unwrap();
let dbg = format!("{sk:?}");
assert!(dbg.contains("redacted"));
let hex = crate::test_util::to_hex(&sk.as_raw()[..8]);
assert!(!dbg.contains(&hex));
let (_, ss) = sk.public_key().encapsulate(&mut rng).unwrap();
assert_eq!(format!("{ss:?}"), "SharedSecret(<redacted>)");
}
#[test]
fn secret_types_zeroize_on_drop() {
fn assert_zod<T: ZeroizeOnDrop>() {}
assert_zod::<SecretKey>();
assert_zod::<SharedSecret>();
#[cfg(feature = "suite-max")]
assert_zod::<MlDk>();
#[cfg(feature = "suite-max")]
assert_zod::<p384::SecretKey>();
#[cfg(feature = "suite-xwing")]
assert_zod::<x_wing::DecapsulationKey>();
#[cfg(feature = "paranoid")]
assert_zod::<classic_mceliece_rust::SecretKey<'static>>();
}
#[cfg(feature = "suite-max")]
#[test]
fn mlkem_decapsulation_key_zeroizes() {
let (mut dk, _) = mlkem_keypair(&[7u8; MLKEM_SEED_LEN]).unwrap();
assert!(dk.0.as_slice().iter().any(|&b| b != 0));
dk.zeroize();
assert!(dk.0.as_slice().iter().all(|&b| b == 0));
}
}