cascade: add RFC 9180 HPKE base mode over the providers

Inbox seals and LGP hand-outs use X-Wing HPKE with the vetted AEAD and
KDF; interop is checked against the independent hpke crate.
Refs: R3-9
This commit is contained in:
JohnE 2026-11-16 03:33:58 -05:00
parent 9ee740497b
commit 71d07bd495
3 changed files with 272 additions and 0 deletions

View File

@ -0,0 +1,204 @@
//! HPKE base mode, single shot (RFC 9180 §5.1, §6.1), over the provider
//! traits (R3-9). Used for the inbox seal to the channel ingest key (CIK) and
//! for LGP key hand-outs to receive keys, with the X-Wing KEM.
//!
//! The KEM, the KDF (HKDF via the provider's HMAC) and the AEAD each come from
//! a provider, so in release builds the AEAD and KDF are the FIPS module's.
//! Extract and Expand are built on HMAC so the labelled key schedule is exactly
//! RFC 9180's; interop is checked against the independent `hpke` crate.
//!
//! Output of [`seal`]: `enc || ciphertext`, where `enc` is the KEM ciphertext.
use ccc_crypto_core::{AeadAlgorithm, AeadProvider, KemAlgorithm, KemProvider, MacAlgorithm, MacProvider};
use zeroize::Zeroizing;
use crate::CascadeError;
/// An HPKE ciphersuite: KEM, KDF and AEAD with their RFC 9180 / IANA IDs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HpkeSuite {
/// The KEM.
pub kem: KemAlgorithm,
/// IANA HPKE KEM ID (X-Wing: 0x647a).
pub kem_id: u16,
/// Length of `enc` (the KEM ciphertext) in bytes.
pub enc_len: usize,
/// HMAC for HKDF: `HmacSha256` (KDF ID 1) or `HmacSha512` (KDF ID 3).
pub kdf: MacAlgorithm,
/// The AEAD (AES-256-GCM: ID 2, ChaCha20-Poly1305: ID 3).
pub aead: AeadAlgorithm,
}
impl HpkeSuite {
/// X-Wing, HKDF-SHA256, AES-256-GCM: the LGP and inbox suite.
pub const XWING_SHA256_AES256GCM: HpkeSuite = HpkeSuite {
kem: KemAlgorithm::XWing,
kem_id: 0x647a,
enc_len: 1120,
kdf: MacAlgorithm::HmacSha256,
aead: AeadAlgorithm::AesGcm256,
};
fn kdf_id(&self) -> Result<u16, CascadeError> {
match self.kdf {
MacAlgorithm::HmacSha256 => Ok(1),
MacAlgorithm::HmacSha384 => Ok(2),
MacAlgorithm::HmacSha512 => Ok(3),
_ => Err(CascadeError::InvalidInput("HPKE KDF must be HMAC-SHA-2")),
}
}
fn hash_len(&self) -> usize {
match self.kdf {
MacAlgorithm::HmacSha384 => 48,
MacAlgorithm::HmacSha512 => 64,
_ => 32,
}
}
fn aead_id(&self) -> Result<u16, CascadeError> {
match self.aead {
AeadAlgorithm::AesGcm256 => Ok(2),
AeadAlgorithm::ChaCha20Poly1305 => Ok(3),
_ => Err(CascadeError::InvalidInput("HPKE AEAD must be AES-256-GCM or ChaCha20-Poly1305")),
}
}
fn suite_id(&self) -> Result<Vec<u8>, CascadeError> {
let mut id = b"HPKE".to_vec();
id.extend_from_slice(&self.kem_id.to_be_bytes());
id.extend_from_slice(&self.kdf_id()?.to_be_bytes());
id.extend_from_slice(&self.aead_id()?.to_be_bytes());
Ok(id)
}
}
/// The providers one HPKE operation uses.
pub struct HpkeProviders<'a> {
/// Provider of the KEM.
pub kem: &'a dyn KemProvider,
/// Provider of HMAC (the KDF).
pub mac: &'a dyn MacProvider,
/// Provider of the AEAD.
pub aead: &'a dyn AeadProvider,
}
type Secret = Zeroizing<Vec<u8>>;
struct Schedule<'a> {
suite: HpkeSuite,
suite_id: Vec<u8>,
mac: &'a dyn MacProvider,
}
impl Schedule<'_> {
// RFC 9180 §4: LabeledExtract(salt, label, ikm) = Extract(salt, "HPKE-v1" || suite_id || label || ikm)
fn labeled_extract(&self, salt: &[u8], label: &[u8], ikm: &[u8]) -> Result<Secret, CascadeError> {
let mut input = Zeroizing::new(Vec::with_capacity(7 + self.suite_id.len() + label.len() + ikm.len()));
input.extend_from_slice(b"HPKE-v1");
input.extend_from_slice(&self.suite_id);
input.extend_from_slice(label);
input.extend_from_slice(ikm);
// HKDF-Extract: an empty salt means HashLen zero bytes (RFC 5869 §2.2).
let zero = vec![0u8; self.suite.hash_len()];
let salt = if salt.is_empty() { &zero[..] } else { salt };
Ok(Zeroizing::new(self.mac.compute_mac(self.suite.kdf, salt, &input)?))
}
// LabeledExpand(prk, label, info, L) = Expand(prk, I2OSP(L, 2) || "HPKE-v1" || suite_id || label || info, L)
fn labeled_expand(&self, prk: &[u8], label: &[u8], info: &[u8], len: usize) -> Result<Secret, CascadeError> {
let mut labeled = Vec::with_capacity(9 + self.suite_id.len() + label.len() + info.len());
labeled.extend_from_slice(&(len as u16).to_be_bytes());
labeled.extend_from_slice(b"HPKE-v1");
labeled.extend_from_slice(&self.suite_id);
labeled.extend_from_slice(label);
labeled.extend_from_slice(info);
let hash_len = self.suite.hash_len();
if len > 255 * hash_len {
return Err(CascadeError::InvalidInput("HKDF output too long"));
}
let mut okm = Zeroizing::new(Vec::with_capacity(len));
let mut t: Secret = Zeroizing::new(Vec::new());
let mut counter = 1u8;
while okm.len() < len {
let mut input = Zeroizing::new(t.to_vec());
input.extend_from_slice(&labeled);
input.push(counter);
t = Zeroizing::new(self.mac.compute_mac(self.suite.kdf, prk, &input)?);
let take = (len - okm.len()).min(hash_len);
okm.extend_from_slice(&t[..take]);
counter = counter.wrapping_add(1);
}
Ok(okm)
}
// RFC 9180 §5.1 KeySchedule, mode_base, no PSK. Returns (key, base_nonce).
fn key_schedule(&self, shared_secret: &[u8], info: &[u8]) -> Result<(Secret, Secret), CascadeError> {
let psk_id_hash = self.labeled_extract(b"", b"psk_id_hash", b"")?;
let info_hash = self.labeled_extract(b"", b"info_hash", info)?;
let mut context = vec![0u8]; // mode_base
context.extend_from_slice(&psk_id_hash);
context.extend_from_slice(&info_hash);
let secret = self.labeled_extract(shared_secret, b"secret", b"")?;
let key = self.labeled_expand(&secret, b"key", &context, self.suite.aead.key_len())?;
let nonce = self.labeled_expand(&secret, b"base_nonce", &context, self.suite.aead.nonce_len())?;
Ok((key, nonce))
}
}
fn schedule<'a>(suite: HpkeSuite, mac: &'a dyn MacProvider) -> Result<Schedule<'a>, CascadeError> {
Ok(Schedule { suite, suite_id: suite.suite_id()?, mac })
}
/// Key schedule only, from a known shared secret (for test vectors).
pub fn key_schedule_for_tests(
suite: HpkeSuite,
mac: &dyn MacProvider,
shared_secret: &[u8],
info: &[u8],
) -> Result<(Vec<u8>, Vec<u8>), CascadeError> {
let (k, n) = schedule(suite, mac)?.key_schedule(shared_secret, info)?;
Ok((k.to_vec(), n.to_vec()))
}
/// Seal `plaintext` to `recipient_pk` (RFC 9180 SealBase, one message, so the
/// nonce is `base_nonce`). Returns `enc || ciphertext`.
pub fn seal(
suite: HpkeSuite,
p: &HpkeProviders<'_>,
recipient_pk: &[u8],
info: &[u8],
aad: &[u8],
plaintext: &[u8],
) -> Result<Vec<u8>, CascadeError> {
let encap = p.kem.encapsulate(suite.kem, recipient_pk)?;
if encap.ciphertext.len() != suite.enc_len {
return Err(CascadeError::Crypto("KEM returned an unexpected enc length".into()));
}
let (key, nonce) = schedule(suite, p.mac)?.key_schedule(&encap.shared_secret, info)?;
let ct = p.aead.encrypt_aead(suite.aead, &key, &nonce, plaintext, aad)?;
let mut out = Vec::with_capacity(encap.ciphertext.len() + ct.len());
out.extend_from_slice(&encap.ciphertext);
out.extend_from_slice(&ct);
Ok(out)
}
/// Open `enc || ciphertext` with the recipient's private key. Any failure is
/// [`CascadeError::AuthenticationFailed`].
pub fn open(
suite: HpkeSuite,
p: &HpkeProviders<'_>,
recipient_sk: &[u8],
info: &[u8],
aad: &[u8],
sealed: &[u8],
) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
if sealed.len() < suite.enc_len + suite.aead.tag_len() {
return Err(CascadeError::AuthenticationFailed);
}
let (enc, ct) = sealed.split_at(suite.enc_len);
let ss = p.kem.decapsulate(suite.kem, recipient_sk, enc).map_err(|_| CascadeError::AuthenticationFailed)?;
let (key, nonce) = schedule(suite, p.mac)?.key_schedule(&ss, info)?;
let pt = p.aead.decrypt_aead(suite.aead, &key, &nonce, ct, aad).map_err(|_| CascadeError::AuthenticationFailed)?;
Ok(Zeroizing::new(pt))
}

View File

@ -12,6 +12,7 @@
#![warn(missing_docs)] #![warn(missing_docs)]
pub mod cascade; pub mod cascade;
pub mod hpke;
pub mod padding; pub mod padding;
pub mod secret; pub mod secret;
pub mod stream; pub mod stream;

View File

@ -0,0 +1,67 @@
//! HPKE (X-Wing, HKDF-SHA256, AES-256-GCM) interop with the independent
//! `hpke` crate, both directions, plus tamper and context checks.
//! KEM from the RustCrypto provider; HMAC and AEAD from wolfSSL (the vetted
//! provider), as in production.
use ccc_cascade::hpke::{self as ours, HpkeProviders, HpkeSuite};
use ccc_cascade::CascadeError;
use ccc_crypto_core::{KemAlgorithm, KemProvider};
use ccc_crypto_rustcrypto::RustCryptoProvider;
use ccc_crypto_wolfssl::WolfSslProvider;
use ::hpke::{Deserializable, Kem as _, OpModeR, OpModeS, Serializable};
type Kem = ::hpke::kem::XWing;
type Kdf = ::hpke::kdf::HkdfSha256;
type Aead = ::hpke::aead::AesGcm256;
const SUITE: HpkeSuite = HpkeSuite::XWING_SHA256_AES256GCM;
#[test]
fn our_seal_opens_with_the_hpke_crate() {
let rc = RustCryptoProvider::new();
let wolf = WolfSslProvider::new();
let p = HpkeProviders { kem: &rc, mac: &wolf, aead: &wolf };
let (sk, pk) = Kem::derive_keypair(b"interop test seed for x-wing hpke");
let sealed = ours::seal(SUITE, &p, &pk.to_bytes(), b"lum/inbox", b"aad", b"inbox envelope").unwrap();
let (enc, ct) = sealed.split_at(SUITE.enc_len);
let enc = <Kem as ::hpke::Kem>::EncappedKey::from_bytes(enc).unwrap();
let pt = ::hpke::single_shot_open::<Aead, Kdf, Kem>(&OpModeR::Base, &sk, &enc, b"lum/inbox", ct, b"aad").unwrap();
assert_eq!(pt, b"inbox envelope");
}
#[test]
fn hpke_crate_seal_opens_with_ours() {
let rc = RustCryptoProvider::new();
let wolf = WolfSslProvider::new();
let p = HpkeProviders { kem: &rc, mac: &wolf, aead: &wolf };
let kp = rc.generate_keypair(KemAlgorithm::XWing).unwrap();
let pk = <Kem as ::hpke::Kem>::PublicKey::from_bytes(&kp.public_key).unwrap();
let (enc, ct) =
::hpke::single_shot_seal::<Aead, Kdf, Kem>(&OpModeS::Base, &pk, b"lum/lgp/handout", b"seed", b"a").unwrap();
let mut sealed = enc.to_bytes().to_vec();
sealed.extend_from_slice(&ct);
let pt = ours::open(SUITE, &p, &kp.private_key, b"lum/lgp/handout", b"a", &sealed).unwrap();
assert_eq!(pt.as_slice(), b"seed");
}
#[test]
fn wrong_context_or_tamper_fails_closed() {
let rc = RustCryptoProvider::new();
let wolf = WolfSslProvider::new();
let p = HpkeProviders { kem: &rc, mac: &wolf, aead: &wolf };
let kp = rc.generate_keypair(KemAlgorithm::XWing).unwrap();
let other = rc.generate_keypair(KemAlgorithm::XWing).unwrap();
let sealed = ours::seal(SUITE, &p, &kp.public_key, b"info", b"aad", b"msg").unwrap();
assert_eq!(sealed.len(), SUITE.enc_len + 3 + 16);
let fails =
|r: Result<zeroize::Zeroizing<Vec<u8>>, CascadeError>| matches!(r, Err(CascadeError::AuthenticationFailed));
assert!(fails(ours::open(SUITE, &p, &kp.private_key, b"other", b"aad", &sealed)), "info");
assert!(fails(ours::open(SUITE, &p, &kp.private_key, b"info", b"x", &sealed)), "aad");
assert!(fails(ours::open(SUITE, &p, &other.private_key, b"info", b"aad", &sealed)), "key");
for i in [0, SUITE.enc_len, sealed.len() - 1] {
let mut t = sealed.clone();
t[i] ^= 1;
assert!(fails(ours::open(SUITE, &p, &kp.private_key, b"info", b"aad", &t)), "byte {i}");
}
assert!(fails(ours::open(SUITE, &p, &kp.private_key, b"info", b"aad", &sealed[..100])), "short");
}