358 lines
14 KiB
Rust
358 lines
14 KiB
Rust
//! KEMs: X25519 (`x25519-dalek`), ML-KEM-768/1024 (`ml-kem`, FIPS 203) and
|
|
//! X-Wing (`x-wing`, draft-connolly-cfrg-xwing-kem-06).
|
|
//!
|
|
//! Key and ciphertext formats:
|
|
//!
|
|
//! | Algorithm | Private key | Public key | Ciphertext | Secret |
|
|
//! |-------------|------------------------|------------|-----------------------|--------|
|
|
//! | X25519 | 32-byte scalar (LE) | 32 | 32 (ephemeral public) | 32 |
|
|
//! | ML-KEM-768 | 64-byte seed `d \|\| z` | 1184 | 1088 | 32 |
|
|
//! | ML-KEM-1024 | 64-byte seed `d \|\| z` | 1568 | 1568 | 32 |
|
|
//! | X-Wing | 32-byte seed | 1216 | 1120 | 32 |
|
|
//!
|
|
//! X25519 follows the wolfSSL provider's KEM convention: encapsulation makes
|
|
//! an ephemeral key pair, the ciphertext is its public key and the secret is
|
|
//! the raw RFC 7748 shared value. An all-zero shared value (a low-order
|
|
//! peer point) is rejected.
|
|
//!
|
|
//! Classic McEliece 460896f (`mceliece` feature, on by default) lives in
|
|
//! [`crate::mceliece`]. X448 and Classic McEliece 460896 (non-"f") are not
|
|
//! offered by this provider.
|
|
|
|
use ml_kem::array::Array;
|
|
use ml_kem::kem::{Decapsulate, KeyExport, TryKeyInit};
|
|
use x25519_dalek::{PublicKey, StaticSecret};
|
|
use zeroize::Zeroizing;
|
|
|
|
use ccc_crypto_core::{
|
|
algorithms::KemAlgorithm,
|
|
error::CryptoError,
|
|
types::{KemEncapResult, KemKeyPair},
|
|
};
|
|
|
|
/// Generate a key pair.
|
|
pub fn generate_keypair(algo: KemAlgorithm) -> Result<KemKeyPair, CryptoError> {
|
|
match algo {
|
|
KemAlgorithm::X25519 => {
|
|
let sk = random::<32>()?;
|
|
let pk = PublicKey::from(&StaticSecret::from(*sk));
|
|
Ok(KemKeyPair {
|
|
public_key: pk.as_bytes().to_vec(),
|
|
private_key: sk.to_vec(),
|
|
})
|
|
}
|
|
KemAlgorithm::MlKem768 => mlkem768::generate(),
|
|
KemAlgorithm::MlKem1024 => mlkem1024::generate(),
|
|
KemAlgorithm::XWing => {
|
|
let seed = random::<32>()?;
|
|
Ok(KemKeyPair {
|
|
public_key: xwing_public_key(&seed[..])?,
|
|
private_key: seed.to_vec(),
|
|
})
|
|
}
|
|
#[cfg(feature = "mceliece")]
|
|
KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::generate(),
|
|
#[cfg(not(feature = "mceliece"))]
|
|
KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo),
|
|
KemAlgorithm::X448 | KemAlgorithm::ClassicMcEliece460896 => not_compiled(algo),
|
|
}
|
|
}
|
|
|
|
/// Encapsulate a fresh shared secret to `public_key`.
|
|
pub fn encapsulate(algo: KemAlgorithm, public_key: &[u8]) -> Result<KemEncapResult, CryptoError> {
|
|
match algo {
|
|
KemAlgorithm::X25519 => {
|
|
let eph = random::<32>()?;
|
|
x25519_encapsulate_deterministic(&eph[..], public_key)
|
|
}
|
|
KemAlgorithm::MlKem768 => mlkem768::encapsulate_deterministic(public_key, &*random()?),
|
|
KemAlgorithm::MlKem1024 => mlkem1024::encapsulate_deterministic(public_key, &*random()?),
|
|
KemAlgorithm::XWing => xwing_encapsulate_deterministic(public_key, &*random()?),
|
|
#[cfg(feature = "mceliece")]
|
|
KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::encapsulate(public_key),
|
|
#[cfg(not(feature = "mceliece"))]
|
|
KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo),
|
|
KemAlgorithm::X448 | KemAlgorithm::ClassicMcEliece460896 => not_compiled(algo),
|
|
}
|
|
}
|
|
|
|
/// Recover the shared secret from `ciphertext` with `private_key`.
|
|
pub fn decapsulate(
|
|
algo: KemAlgorithm,
|
|
private_key: &[u8],
|
|
ciphertext: &[u8],
|
|
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
|
|
match algo {
|
|
KemAlgorithm::X25519 => x25519_dh(private_key, ciphertext),
|
|
KemAlgorithm::MlKem768 => mlkem768::decapsulate(private_key, ciphertext),
|
|
KemAlgorithm::MlKem1024 => mlkem1024::decapsulate(private_key, ciphertext),
|
|
KemAlgorithm::XWing => xwing_decapsulate(private_key, ciphertext),
|
|
#[cfg(feature = "mceliece")]
|
|
KemAlgorithm::ClassicMcEliece460896f => crate::mceliece::decapsulate(private_key, ciphertext),
|
|
#[cfg(not(feature = "mceliece"))]
|
|
KemAlgorithm::ClassicMcEliece460896f => not_compiled(algo),
|
|
KemAlgorithm::X448 | KemAlgorithm::ClassicMcEliece460896 => not_compiled(algo),
|
|
}
|
|
}
|
|
|
|
fn not_compiled<T>(algo: KemAlgorithm) -> Result<T, CryptoError> {
|
|
Err(CryptoError::FeatureNotCompiled(format!(
|
|
"{} is not offered by the rustcrypto provider",
|
|
algo.name()
|
|
)))
|
|
}
|
|
|
|
fn random<const N: usize>() -> Result<Zeroizing<[u8; N]>, CryptoError> {
|
|
let mut buf = Zeroizing::new([0u8; N]);
|
|
getrandom::fill(&mut buf[..])
|
|
.map_err(|e| CryptoError::InternalError(format!("getrandom failed: {e}")))?;
|
|
Ok(buf)
|
|
}
|
|
|
|
fn array32(bytes: &[u8], what: &str) -> Result<Zeroizing<[u8; 32]>, CryptoError> {
|
|
let arr: [u8; 32] = bytes
|
|
.try_into()
|
|
.map_err(|_| CryptoError::InvalidKey(format!("{what}: expected 32 bytes")))?;
|
|
Ok(Zeroizing::new(arr))
|
|
}
|
|
|
|
// ── X25519 ───────────────────────────────────────────────────────────────────
|
|
|
|
/// X25519 encapsulation with a caller-chosen ephemeral scalar (for KATs).
|
|
pub fn x25519_encapsulate_deterministic(
|
|
ephemeral_private: &[u8],
|
|
public_key: &[u8],
|
|
) -> Result<KemEncapResult, CryptoError> {
|
|
let eph = StaticSecret::from(*array32(ephemeral_private, "X25519 private key")?);
|
|
let ct = PublicKey::from(&eph).as_bytes().to_vec();
|
|
let ss = x25519_dh(eph.as_bytes(), public_key)?;
|
|
Ok(KemEncapResult {
|
|
ciphertext: ct,
|
|
shared_secret: ss.to_vec(),
|
|
})
|
|
}
|
|
|
|
fn x25519_dh(private_key: &[u8], public_key: &[u8]) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
|
|
if private_key.len() != 32 || public_key.len() != 32 {
|
|
return Err(CryptoError::InvalidKey(
|
|
"X25519: keys must be 32 bytes each".into(),
|
|
));
|
|
}
|
|
let sk = StaticSecret::from(*array32(private_key, "X25519 private key")?);
|
|
let pk = PublicKey::from(*array32(public_key, "X25519 public key")?);
|
|
let ss = sk.diffie_hellman(&pk);
|
|
if !ss.was_contributory() {
|
|
return Err(CryptoError::InvalidKey(
|
|
"X25519: low-order public key (all-zero shared secret)".into(),
|
|
));
|
|
}
|
|
Ok(Zeroizing::new(ss.as_bytes().to_vec()))
|
|
}
|
|
|
|
// ── ML-KEM ───────────────────────────────────────────────────────────────────
|
|
|
|
macro_rules! mlkem_impl {
|
|
($module:ident, $params:ident, $name:literal) => {
|
|
pub(crate) mod $module {
|
|
use super::*;
|
|
use ml_kem::$params::{Ciphertext, DecapsulationKey, EncapsulationKey};
|
|
|
|
fn dk_from_seed(seed: &[u8]) -> Result<DecapsulationKey, CryptoError> {
|
|
let seed = ml_kem::Seed::try_from(seed).map_err(|_| {
|
|
CryptoError::InvalidKey(
|
|
concat!($name, ": private key must be a 64-byte seed").into(),
|
|
)
|
|
})?;
|
|
Ok(DecapsulationKey::from_seed(seed))
|
|
}
|
|
|
|
/// Public key for a 64-byte seed (FIPS 203 `ML-KEM.KeyGen_internal`).
|
|
pub(crate) fn public_key(seed: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
|
Ok(dk_from_seed(seed)?.encapsulation_key().to_bytes().to_vec())
|
|
}
|
|
|
|
pub(super) fn generate() -> Result<KemKeyPair, CryptoError> {
|
|
let seed = random::<64>()?;
|
|
Ok(KemKeyPair {
|
|
public_key: public_key(&seed[..])?,
|
|
private_key: seed.to_vec(),
|
|
})
|
|
}
|
|
|
|
/// Encapsulate with caller-chosen randomness `m` (for KATs).
|
|
pub(crate) fn encapsulate_deterministic(
|
|
public_key: &[u8],
|
|
m: &[u8; 32],
|
|
) -> Result<KemEncapResult, CryptoError> {
|
|
let ek = EncapsulationKey::new_from_slice(public_key).map_err(|_| {
|
|
CryptoError::InvalidKey(concat!($name, ": invalid public key").into())
|
|
})?;
|
|
let (ct, ss) = ek.encapsulate_deterministic(&Array::from(*m));
|
|
Ok(KemEncapResult {
|
|
ciphertext: ct.to_vec(),
|
|
shared_secret: ss.to_vec(),
|
|
})
|
|
}
|
|
|
|
pub(super) fn decapsulate(
|
|
private_key: &[u8],
|
|
ciphertext: &[u8],
|
|
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
|
|
let dk = dk_from_seed(private_key)?;
|
|
let ct = Ciphertext::try_from(ciphertext).map_err(|_| {
|
|
CryptoError::InvalidInput(concat!($name, ": wrong ciphertext length").into())
|
|
})?;
|
|
Ok(Zeroizing::new(dk.decapsulate(&ct).to_vec()))
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
mlkem_impl!(mlkem768, ml_kem_768, "ML-KEM-768");
|
|
mlkem_impl!(mlkem1024, ml_kem_1024, "ML-KEM-1024");
|
|
|
|
// ── X-Wing ───────────────────────────────────────────────────────────────────
|
|
|
|
fn xwing_dk(seed: &[u8]) -> Result<x_wing::DecapsulationKey, CryptoError> {
|
|
Ok(x_wing::DecapsulationKey::from(*array32(
|
|
seed,
|
|
"X-Wing private key",
|
|
)?))
|
|
}
|
|
|
|
pub(crate) fn xwing_public_key(seed: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
|
use x_wing::Decapsulator;
|
|
Ok(xwing_dk(seed)?.encapsulation_key().to_bytes().to_vec())
|
|
}
|
|
|
|
/// X-Wing encapsulation with caller-chosen 64-byte randomness (for KATs).
|
|
pub(crate) fn xwing_encapsulate_deterministic(
|
|
public_key: &[u8],
|
|
eseed: &[u8; 64],
|
|
) -> Result<KemEncapResult, CryptoError> {
|
|
let ek = x_wing::EncapsulationKey::try_from(public_key)
|
|
.map_err(|_| CryptoError::InvalidKey("X-Wing: invalid public key".into()))?;
|
|
let (ct, ss) = ek.encapsulate_deterministic(&Array::from(*eseed));
|
|
Ok(KemEncapResult {
|
|
ciphertext: ct.to_vec(),
|
|
shared_secret: ss.to_vec(),
|
|
})
|
|
}
|
|
|
|
fn xwing_decapsulate(
|
|
private_key: &[u8],
|
|
ciphertext: &[u8],
|
|
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
|
|
let dk = xwing_dk(private_key)?;
|
|
let ss = dk
|
|
.decapsulate_slice(ciphertext)
|
|
.map_err(|_| CryptoError::InvalidInput("X-Wing: wrong ciphertext length".into()))?;
|
|
Ok(Zeroizing::new(ss.to_vec()))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
const OFFERED: [KemAlgorithm; 4] = [
|
|
KemAlgorithm::X25519,
|
|
KemAlgorithm::MlKem768,
|
|
KemAlgorithm::MlKem1024,
|
|
KemAlgorithm::XWing,
|
|
];
|
|
|
|
#[test]
|
|
fn roundtrip_all_offered() {
|
|
for algo in OFFERED {
|
|
let kp = generate_keypair(algo).unwrap();
|
|
let enc = encapsulate(algo, &kp.public_key).unwrap();
|
|
let ss = decapsulate(algo, &kp.private_key, &enc.ciphertext).unwrap();
|
|
assert_eq!(*ss, enc.shared_secret, "{}", algo.name());
|
|
assert_eq!(ss.len(), 32);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn sizes() {
|
|
for (algo, sk, pk, ct) in [
|
|
(KemAlgorithm::X25519, 32, 32, 32),
|
|
(KemAlgorithm::MlKem768, 64, 1184, 1088),
|
|
(KemAlgorithm::MlKem1024, 64, 1568, 1568),
|
|
(KemAlgorithm::XWing, 32, 1216, 1120),
|
|
] {
|
|
let kp = generate_keypair(algo).unwrap();
|
|
assert_eq!(kp.private_key.len(), sk);
|
|
assert_eq!(kp.public_key.len(), pk);
|
|
assert_eq!(
|
|
encapsulate(algo, &kp.public_key).unwrap().ciphertext.len(),
|
|
ct
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn x25519_rfc7748() {
|
|
let alice = hex::decode("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")
|
|
.unwrap();
|
|
let bob_pub =
|
|
hex::decode("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")
|
|
.unwrap();
|
|
let ss = decapsulate(KemAlgorithm::X25519, &alice, &bob_pub).unwrap();
|
|
assert_eq!(
|
|
hex::encode(&*ss),
|
|
"4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn x25519_low_order_point_rejected() {
|
|
let sk = [0x11u8; 32];
|
|
assert!(matches!(
|
|
decapsulate(KemAlgorithm::X25519, &sk, &[0u8; 32]),
|
|
Err(CryptoError::InvalidKey(_))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn wrong_lengths_rejected() {
|
|
for algo in OFFERED {
|
|
let kp = generate_keypair(algo).unwrap();
|
|
let enc = encapsulate(algo, &kp.public_key).unwrap();
|
|
assert!(encapsulate(algo, &kp.public_key[1..]).is_err());
|
|
assert!(decapsulate(algo, &kp.private_key[1..], &enc.ciphertext).is_err());
|
|
assert!(decapsulate(algo, &kp.private_key, &enc.ciphertext[1..]).is_err());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn mlkem_implicit_rejection() {
|
|
for algo in [
|
|
KemAlgorithm::MlKem768,
|
|
KemAlgorithm::MlKem1024,
|
|
KemAlgorithm::XWing,
|
|
] {
|
|
let kp = generate_keypair(algo).unwrap();
|
|
let enc = encapsulate(algo, &kp.public_key).unwrap();
|
|
let mut ct = enc.ciphertext.clone();
|
|
ct[0] ^= 1;
|
|
let ss = decapsulate(algo, &kp.private_key, &ct).unwrap();
|
|
assert_ne!(*ss, enc.shared_secret);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn unsupported_kems() {
|
|
for algo in [
|
|
KemAlgorithm::X448,
|
|
KemAlgorithm::ClassicMcEliece460896,
|
|
#[cfg(not(feature = "mceliece"))]
|
|
KemAlgorithm::ClassicMcEliece460896f,
|
|
] {
|
|
assert!(matches!(
|
|
generate_keypair(algo),
|
|
Err(CryptoError::FeatureNotCompiled(_))
|
|
));
|
|
}
|
|
}
|
|
}
|