diff --git a/crates/ccc-crypto-boring/src/kem.rs b/crates/ccc-crypto-boring/src/kem.rs new file mode 100644 index 0000000..6796c96 --- /dev/null +++ b/crates/ccc-crypto-boring/src/kem.rs @@ -0,0 +1,329 @@ +//! KEMs: X25519 (`EVP_PKEY_X25519`) and ML-KEM-768/1024 (FIPS 203) from +//! BoringSSL. +//! +//! Key and ciphertext formats match the wolfSSL and RustCrypto providers: +//! +//! | 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 | +//! +//! X25519 follows the providers' KEM convention: encapsulation makes an +//! ephemeral key pair, the ciphertext is its public key and the secret is +//! the raw RFC 7748 shared value. BoringSSL rejects an all-zero shared value +//! (a low-order peer point). `boring` has no raw X25519 key import, so keys +//! go in through their fixed RFC 8410 DER wrappers (PKCS#8 and SPKI). +//! +//! X448, X-Wing, Classic McEliece, HQC and FrodoKEM are not in the `boring` +//! API and return [`CryptoError::FeatureNotCompiled`]. + +use boring::derive::Deriver; +use boring::mlkem::{self, MlKemPrivateKey, MlKemPublicKey}; +use boring::pkey::{Id, PKey, Private, Public}; +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 { + match algo { + KemAlgorithm::X25519 => { + let sk = PKey::generate(Id::X25519).map_err(internal("X25519 keygen"))?; + Ok(KemKeyPair { + public_key: x25519_raw_public(&sk)?, + private_key: x25519_raw_private(&sk)?.to_vec(), + }) + } + KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => { + let (pk, sk) = + MlKemPrivateKey::generate(mlkem_alg(algo)?).map_err(internal(algo.name()))?; + Ok(KemKeyPair { + public_key: pk.as_bytes().to_vec(), + private_key: sk.seed_bytes().to_vec(), + }) + } + _ => not_compiled(algo), + } +} + +/// Encapsulate a fresh shared secret to `public_key`. +pub fn encapsulate(algo: KemAlgorithm, public_key: &[u8]) -> Result { + match algo { + KemAlgorithm::X25519 => { + let peer = x25519_public(public_key)?; + let eph = PKey::generate(Id::X25519).map_err(internal("X25519 keygen"))?; + let ss = x25519_derive(&eph, &peer)?; + Ok(KemEncapResult { + ciphertext: x25519_raw_public(&eph)?, + shared_secret: ss.to_vec(), + }) + } + KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => { + let pk = MlKemPublicKey::from_slice(mlkem_alg(algo)?, public_key).map_err(|_| { + CryptoError::InvalidKey(format!("{}: invalid public key", algo.name())) + })?; + let (ct, ss) = pk.encapsulate().map_err(internal(algo.name()))?; + let ss = Zeroizing::new(ss); + Ok(KemEncapResult { + ciphertext: ct, + shared_secret: ss.to_vec(), + }) + } + _ => not_compiled(algo), + } +} + +/// Recover the shared secret from `ciphertext` with `private_key`. +pub fn decapsulate( + algo: KemAlgorithm, + private_key: &[u8], + ciphertext: &[u8], +) -> Result>, CryptoError> { + match algo { + KemAlgorithm::X25519 => { + let sk = x25519_private(private_key)?; + let peer = x25519_public(ciphertext)?; + x25519_derive(&sk, &peer) + } + KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => { + let alg = mlkem_alg(algo)?; + let seed: Zeroizing = + Zeroizing::new(private_key.try_into().map_err(|_| { + CryptoError::InvalidKey(format!( + "{}: private key must be a {}-byte seed", + algo.name(), + mlkem::PRIVATE_KEY_SEED_BYTES + )) + })?); + if ciphertext.len() != alg.ciphertext_bytes() { + return Err(CryptoError::InvalidInput(format!( + "{}: wrong ciphertext length", + algo.name() + ))); + } + // The private key wipes its seed and expanded form on drop. + let sk = MlKemPrivateKey::from_seed(alg, &seed).map_err(internal(algo.name()))?; + let ss = Zeroizing::new(sk.decapsulate(ciphertext).map_err(internal(algo.name()))?); + Ok(Zeroizing::new(ss.to_vec())) + } + _ => not_compiled(algo), + } +} + +fn not_compiled(algo: KemAlgorithm) -> Result { + Err(CryptoError::FeatureNotCompiled(format!( + "{} is not offered by the boring provider", + algo.name() + ))) +} + +fn internal(what: &str) -> impl Fn(boring::error::ErrorStack) -> CryptoError + '_ { + move |e| CryptoError::InternalError(format!("{what}: {e}")) +} + +fn mlkem_alg(algo: KemAlgorithm) -> Result { + match algo { + KemAlgorithm::MlKem768 => Ok(mlkem::Algorithm::MlKem768), + KemAlgorithm::MlKem1024 => Ok(mlkem::Algorithm::MlKem1024), + _ => not_compiled(algo), + } +} + +// ── X25519 ─────────────────────────────────────────────────────────────────── + +/// RFC 8410 PKCS#8 `OneAsymmetricKey` prefix for a 32-byte X25519 key. +const X25519_PKCS8_PREFIX: [u8; 16] = [ + 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20, +]; +/// RFC 8410 `SubjectPublicKeyInfo` prefix for a 32-byte X25519 key. +const X25519_SPKI_PREFIX: [u8; 12] = [ + 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x03, 0x21, 0x00, +]; + +fn x25519_private(raw: &[u8]) -> Result, CryptoError> { + if raw.len() != 32 { + return Err(CryptoError::InvalidKey( + "X25519: private key must be 32 bytes".into(), + )); + } + let mut der = Zeroizing::new(Vec::with_capacity(48)); + der.extend_from_slice(&X25519_PKCS8_PREFIX); + der.extend_from_slice(raw); + PKey::private_key_from_der(&der) + .map_err(|_| CryptoError::InvalidKey("X25519: invalid private key".into())) +} + +fn x25519_public(raw: &[u8]) -> Result, CryptoError> { + if raw.len() != 32 { + return Err(CryptoError::InvalidKey( + "X25519: public key must be 32 bytes".into(), + )); + } + let mut der = Vec::with_capacity(44); + der.extend_from_slice(&X25519_SPKI_PREFIX); + der.extend_from_slice(raw); + PKey::public_key_from_der(&der) + .map_err(|_| CryptoError::InvalidKey("X25519: invalid public key".into())) +} + +fn x25519_raw_public(key: &PKey) -> Result, CryptoError> { + let mut buf = [0u8; 32]; + let pk = key + .raw_public_key(&mut buf) + .map_err(internal("X25519 public key"))?; + Ok(pk.to_vec()) +} + +fn x25519_raw_private(key: &PKey) -> Result, CryptoError> { + let mut buf = Zeroizing::new([0u8; 32]); + let len = key + .raw_private_key(&mut buf[..]) + .map_err(internal("X25519 private key"))? + .len(); + if len != 32 { + return Err(CryptoError::InternalError( + "X25519: unexpected private key length".into(), + )); + } + Ok(buf) +} + +fn x25519_derive( + sk: &PKey, + peer: &PKey, +) -> Result>, CryptoError> { + let low_order = + || CryptoError::InvalidKey("X25519: low-order public key (all-zero shared secret)".into()); + let mut d = Deriver::new(sk).map_err(internal("X25519 derive"))?; + d.set_peer(peer).map_err(internal("X25519 derive"))?; + let mut ss = Zeroizing::new(vec![0u8; 32]); + // BoringSSL fails the derivation exactly when the result is all zero. + let len = d.derive(&mut ss).map_err(|_| low_order())?; + if len != 32 { + return Err(CryptoError::InternalError( + "X25519: unexpected shared secret length".into(), + )); + } + Ok(ss) +} + +#[cfg(test)] +mod tests { + use super::*; + + const OFFERED: [KemAlgorithm; 3] = [ + KemAlgorithm::X25519, + KemAlgorithm::MlKem768, + KemAlgorithm::MlKem1024, + ]; + + fn h(s: &str) -> Vec { + hex::decode(s).unwrap() + } + + #[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), + ] { + 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 = h("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + let alice_pub = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"; + let bob = h("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"); + let bob_pub = h("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"); + let shared = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"; + let ss = decapsulate(KemAlgorithm::X25519, &alice, &bob_pub).unwrap(); + assert_eq!(hex::encode(&*ss), shared); + let ss = decapsulate(KemAlgorithm::X25519, &bob, &h(alice_pub)).unwrap(); + assert_eq!(hex::encode(&*ss), shared); + let sk = x25519_private(&alice).unwrap(); + assert_eq!(hex::encode(x25519_raw_public(&sk).unwrap()), alice_pub); + assert_eq!(*x25519_raw_private(&sk).unwrap(), alice[..]); + } + + #[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] { + 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::XWing, + KemAlgorithm::ClassicMcEliece460896, + KemAlgorithm::ClassicMcEliece460896f, + KemAlgorithm::Hqc192, + KemAlgorithm::FrodoKem976Shake, + ] { + assert!(matches!( + generate_keypair(algo), + Err(CryptoError::FeatureNotCompiled(_)) + )); + assert!(matches!( + encapsulate(algo, &[0u8; 32]), + Err(CryptoError::FeatureNotCompiled(_)) + )); + assert!(matches!( + decapsulate(algo, &[0u8; 32], &[0u8; 32]), + Err(CryptoError::FeatureNotCompiled(_)) + )); + } + } +} diff --git a/crates/ccc-crypto-boring/src/lib.rs b/crates/ccc-crypto-boring/src/lib.rs index d93955d..f403b4d 100644 --- a/crates/ccc-crypto-boring/src/lib.rs +++ b/crates/ccc-crypto-boring/src/lib.rs @@ -19,6 +19,7 @@ pub mod aead; pub mod hash; pub mod kdf; +pub mod kem; pub mod mac; /// The provider's registry name.