368 lines
13 KiB
Rust
368 lines
13 KiB
Rust
//! KEMs: X25519 (`aws_lc_rs::agreement`) and ML-KEM-768/1024 (FIPS 203,
|
|
//! `aws_lc_rs::kem`).
|
|
//!
|
|
//! Key and ciphertext formats:
|
|
//!
|
|
//! | Algorithm | Private key | Public key | Ciphertext | Secret |
|
|
//! |-------------|---------------------------------|------------|-----------------------|--------|
|
|
//! | X25519 | 32-byte scalar (LE) | 32 | 32 (ephemeral public) | 32 |
|
|
//! | ML-KEM-768 | 2400-byte FIPS 203 `dk` | 1184 | 1088 | 32 |
|
|
//! | ML-KEM-1024 | 3168-byte FIPS 203 `dk` | 1568 | 1568 | 32 |
|
|
//!
|
|
//! X25519 follows the other 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. An all-zero shared value (a low-order peer
|
|
//! point) is rejected.
|
|
//!
|
|
//! Public keys and ciphertexts are the standard encodings, so they
|
|
//! interoperate with every provider. The ML-KEM private key is the expanded
|
|
//! FIPS 203 decapsulation key, because aws-lc-rs has no stable API for seed
|
|
//! key generation; the RustCrypto provider stores the 64-byte seed instead,
|
|
//! so ML-KEM private keys are not portable between those two providers.
|
|
//!
|
|
//! X448, X-Wing, Classic McEliece, HQC and FrodoKEM are not offered.
|
|
|
|
use aws_lc_rs::agreement::{self, PrivateKey, UnparsedPublicKey, X25519};
|
|
use aws_lc_rs::encoding::{AsBigEndian, Curve25519SeedBin};
|
|
use aws_lc_rs::kem::{self, Ciphertext, DecapsulationKey, EncapsulationKey};
|
|
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 = PrivateKey::generate(&X25519).map_err(internal("X25519 keygen"))?;
|
|
Ok(KemKeyPair {
|
|
public_key: x25519_public(&sk)?,
|
|
private_key: x25519_private_bytes(&sk)?,
|
|
})
|
|
}
|
|
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => {
|
|
let (p, name) = mlkem(algo)?;
|
|
let dk = DecapsulationKey::generate(p.alg).map_err(internal(name))?;
|
|
let ek = dk.encapsulation_key().map_err(internal(name))?;
|
|
Ok(KemKeyPair {
|
|
public_key: ek.key_bytes().map_err(internal(name))?.as_ref().to_vec(),
|
|
private_key: dk.key_bytes().map_err(internal(name))?.as_ref().to_vec(),
|
|
})
|
|
}
|
|
_ => 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 = PrivateKey::generate(&X25519).map_err(internal("X25519 keygen"))?;
|
|
x25519_encapsulate_with(&eph, public_key)
|
|
}
|
|
KemAlgorithm::MlKem768 | KemAlgorithm::MlKem1024 => {
|
|
let (p, name) = mlkem(algo)?;
|
|
mlkem_encapsulate(p, name, public_key)
|
|
}
|
|
_ => 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 | KemAlgorithm::MlKem1024 => {
|
|
let (p, name) = mlkem(algo)?;
|
|
mlkem_decapsulate(p, name, private_key, ciphertext)
|
|
}
|
|
_ => not_compiled(algo),
|
|
}
|
|
}
|
|
|
|
fn not_compiled<T>(algo: KemAlgorithm) -> Result<T, CryptoError> {
|
|
Err(CryptoError::FeatureNotCompiled(format!(
|
|
"{} is not offered by the awslc provider",
|
|
algo.name()
|
|
)))
|
|
}
|
|
|
|
fn internal<E>(what: &'static str) -> impl Fn(E) -> CryptoError {
|
|
move |_| CryptoError::InternalError(format!("{what} failed"))
|
|
}
|
|
|
|
// ── X25519 ───────────────────────────────────────────────────────────────────
|
|
|
|
fn x25519_public(sk: &PrivateKey) -> Result<Vec<u8>, CryptoError> {
|
|
Ok(sk
|
|
.compute_public_key()
|
|
.map_err(internal("X25519 public key"))?
|
|
.as_ref()
|
|
.to_vec())
|
|
}
|
|
|
|
fn x25519_private_bytes(sk: &PrivateKey) -> Result<Vec<u8>, CryptoError> {
|
|
let bin: Curve25519SeedBin = sk
|
|
.as_be_bytes()
|
|
.map_err(internal("X25519 private key export"))?;
|
|
Ok(bin.as_ref().to_vec())
|
|
}
|
|
|
|
fn x25519_private(bytes: &[u8]) -> Result<PrivateKey, CryptoError> {
|
|
if bytes.len() != 32 {
|
|
return Err(CryptoError::InvalidKey(
|
|
"X25519: private key must be 32 bytes".into(),
|
|
));
|
|
}
|
|
PrivateKey::from_private_key(&X25519, bytes)
|
|
.map_err(|_| CryptoError::InvalidKey("X25519: invalid private key".into()))
|
|
}
|
|
|
|
/// X25519 encapsulation with a caller-chosen ephemeral scalar (for KATs).
|
|
pub fn x25519_encapsulate_deterministic(
|
|
ephemeral_private: &[u8],
|
|
public_key: &[u8],
|
|
) -> Result<KemEncapResult, CryptoError> {
|
|
x25519_encapsulate_with(&x25519_private(ephemeral_private)?, public_key)
|
|
}
|
|
|
|
fn x25519_encapsulate_with(
|
|
eph: &PrivateKey,
|
|
public_key: &[u8],
|
|
) -> Result<KemEncapResult, CryptoError> {
|
|
let ss = x25519_agree(eph, public_key)?;
|
|
Ok(KemEncapResult {
|
|
ciphertext: x25519_public(eph)?,
|
|
shared_secret: ss.to_vec(),
|
|
})
|
|
}
|
|
|
|
fn x25519_dh(private_key: &[u8], public_key: &[u8]) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
|
|
x25519_agree(&x25519_private(private_key)?, public_key)
|
|
}
|
|
|
|
fn x25519_agree(sk: &PrivateKey, public_key: &[u8]) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
|
|
if public_key.len() != 32 {
|
|
return Err(CryptoError::InvalidKey(
|
|
"X25519: public key must be 32 bytes".into(),
|
|
));
|
|
}
|
|
let low_order = || CryptoError::InvalidKey("X25519: low-order public key".into());
|
|
let ss = agreement::agree(sk, UnparsedPublicKey::new(&X25519, public_key), (), |s| {
|
|
Ok(Zeroizing::new(s.to_vec()))
|
|
})
|
|
.map_err(|()| low_order())?;
|
|
// AWS-LC already refuses an all-zero result; checked here as well so the
|
|
// rule does not depend on the backend version.
|
|
if ss.iter().fold(0u8, |acc, b| acc | b) == 0 {
|
|
return Err(low_order());
|
|
}
|
|
Ok(ss)
|
|
}
|
|
|
|
// ── ML-KEM ───────────────────────────────────────────────────────────────────
|
|
|
|
/// FIPS 203 sizes for one parameter set.
|
|
#[derive(Clone, Copy)]
|
|
pub(crate) struct MlKemParams {
|
|
pub(crate) alg: &'static kem::Algorithm,
|
|
pub(crate) dk_len: usize,
|
|
pub(crate) ek_len: usize,
|
|
pub(crate) ct_len: usize,
|
|
}
|
|
|
|
pub(crate) const MLKEM768: MlKemParams = MlKemParams {
|
|
alg: &kem::ML_KEM_768,
|
|
dk_len: 2400,
|
|
ek_len: 1184,
|
|
ct_len: 1088,
|
|
};
|
|
|
|
pub(crate) const MLKEM1024: MlKemParams = MlKemParams {
|
|
alg: &kem::ML_KEM_1024,
|
|
dk_len: 3168,
|
|
ek_len: 1568,
|
|
ct_len: 1568,
|
|
};
|
|
|
|
fn mlkem(algo: KemAlgorithm) -> Result<(MlKemParams, &'static str), CryptoError> {
|
|
match algo {
|
|
KemAlgorithm::MlKem768 => Ok((MLKEM768, "ML-KEM-768")),
|
|
KemAlgorithm::MlKem1024 => Ok((MLKEM1024, "ML-KEM-1024")),
|
|
_ => not_compiled(algo),
|
|
}
|
|
}
|
|
|
|
pub(crate) fn mlkem_encapsulate(
|
|
p: MlKemParams,
|
|
name: &'static str,
|
|
public_key: &[u8],
|
|
) -> Result<KemEncapResult, CryptoError> {
|
|
if public_key.len() != p.ek_len {
|
|
return Err(CryptoError::InvalidKey(format!(
|
|
"{name}: public key must be {} bytes",
|
|
p.ek_len
|
|
)));
|
|
}
|
|
let ek = EncapsulationKey::new(p.alg, public_key)
|
|
.map_err(|_| CryptoError::InvalidKey(format!("{name}: invalid public key")))?;
|
|
let (ct, ss) = ek.encapsulate().map_err(internal(name))?;
|
|
Ok(KemEncapResult {
|
|
ciphertext: ct.as_ref().to_vec(),
|
|
shared_secret: ss.as_ref().to_vec(),
|
|
})
|
|
}
|
|
|
|
pub(crate) fn mlkem_decapsulate(
|
|
p: MlKemParams,
|
|
name: &'static str,
|
|
private_key: &[u8],
|
|
ciphertext: &[u8],
|
|
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
|
|
if private_key.len() != p.dk_len {
|
|
return Err(CryptoError::InvalidKey(format!(
|
|
"{name}: private key must be {} bytes",
|
|
p.dk_len
|
|
)));
|
|
}
|
|
if ciphertext.len() != p.ct_len {
|
|
return Err(CryptoError::InvalidInput(format!(
|
|
"{name}: wrong ciphertext length"
|
|
)));
|
|
}
|
|
let dk = DecapsulationKey::new(p.alg, private_key)
|
|
.map_err(|_| CryptoError::InvalidKey(format!("{name}: invalid private key")))?;
|
|
// A malformed ciphertext of the right length gets FIPS 203 implicit
|
|
// rejection (a pseudo-random secret), not an error.
|
|
let ss = dk
|
|
.decapsulate(Ciphertext::from(ciphertext))
|
|
.map_err(|_| CryptoError::InvalidKey(format!("{name}: decapsulation failed")))?;
|
|
Ok(Zeroizing::new(ss.as_ref().to_vec()))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
const OFFERED: [KemAlgorithm; 3] = [
|
|
KemAlgorithm::X25519,
|
|
KemAlgorithm::MlKem768,
|
|
KemAlgorithm::MlKem1024,
|
|
];
|
|
|
|
#[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, 2400, 1184, 1088),
|
|
(KemAlgorithm::MlKem1024, 3168, 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 = 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_private_key_round_trips() {
|
|
let kp = generate_keypair(KemAlgorithm::X25519).unwrap();
|
|
let mut base = [0u8; 32];
|
|
base[0] = 9;
|
|
let pk = decapsulate(KemAlgorithm::X25519, &kp.private_key, &base).unwrap();
|
|
assert_eq!(*pk, kp.public_key);
|
|
}
|
|
|
|
#[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(_))
|
|
));
|
|
}
|
|
}
|
|
}
|