6780abc0c2
R2-01: PublicKey::encapsulate, SecretKey::decapsulate and SharedSecret::as_bytes are hazmat-only; release consumers reach keys only through exchange and seal. R2-02: PublicKey::from_bytes refuses a non-canonical X25519 half (bit 255 set, or a value of at least 2^255 - 19). Honest keys and the draft vectors pass. R2-03: schedule::expand takes one static label and one fixed-width field, so its info is injective by signature. v1 bytes unchanged (golden vectors pass). R2-04: generate, initiate, respond and seal say the RNG must be the OS RNG. R2-05: Initiation is ZeroizeOnDrop; seal's buffer stays Zeroizing until the plaintext in it is encrypted, so the MessageTooLong path wipes it. QA's A-33 case for PublicKey::encapsulate moves to exchange::respond, and its A-08 test pins the new expand signature to the v1 encoding.
129 lines
5.5 KiB
Rust
129 lines
5.5 KiB
Rust
//! One-shot sealed box to a recipient's hybrid public key, for Custos sealing and Tabellarius.
|
|
//!
|
|
//! ```text
|
|
//! sealed = 0x01 || ct (1120 B) || ChaCha20-Poly1305(key, nonce, plaintext, aad = 0x01) || tag
|
|
//! th = SHA-256("domi/arcanum/v1/transcript/seal" || pk || ct || u64be(len aad) || aad)
|
|
//! prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss || th)
|
|
//! key = HKDF-Expand(prk, "domi/arcanum/v1/seal/key", 32)
|
|
//! nonce = HKDF-Expand(prk, "domi/arcanum/v1/seal/nonce", 12)
|
|
//! ```
|
|
//!
|
|
//! Every seal runs a fresh encapsulation, so a key and nonce pair is never used twice.
|
|
//!
|
|
//! **Anyone who knows the recipient's public key can seal.** There is no sender authentication,
|
|
//! and ChaCha20-Poly1305 is not key-committing: a successful [`open`] says nothing about who
|
|
//! sealed. This is a documented construction, not HPKE (RFC 9180).
|
|
|
|
use alloc::vec::Vec;
|
|
|
|
use chacha20poly1305::aead::AeadInOut;
|
|
use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce};
|
|
use rand_core::CryptoRng;
|
|
use zeroize::Zeroizing;
|
|
|
|
use crate::error::{Error, Input};
|
|
use crate::schedule::{LABEL_SEAL_KEY, LABEL_SEAL_NONCE, Prk, expand, seal_prk};
|
|
use crate::xwing::{CIPHERTEXT_LEN, Ciphertext, ENCAPSULATION_SEED_LEN, PublicKey, SecretKey};
|
|
|
|
/// The format version written as the first byte.
|
|
pub const VERSION: u8 = 1;
|
|
const TAG_LEN: usize = 16;
|
|
const HEADER_LEN: usize = 1 + CIPHERTEXT_LEN;
|
|
/// Bytes a sealed box adds to the plaintext: version, ciphertext and the Poly1305 tag.
|
|
pub const OVERHEAD: usize = HEADER_LEN + TAG_LEN;
|
|
|
|
fn cipher(prk: &Prk) -> (ChaCha20Poly1305, Nonce) {
|
|
let key = expand::<32, 0>(prk, LABEL_SEAL_KEY, &[]);
|
|
let nonce = expand::<12, 0>(prk, LABEL_SEAL_NONCE, &[]);
|
|
// Infallible: the key is exactly 32 bytes.
|
|
let aead = ChaCha20Poly1305::new_from_slice(key.as_slice()).expect("32-byte key");
|
|
(aead, Nonce::from(*nonce))
|
|
}
|
|
|
|
/// Seal `plaintext` to `recipient`, bound to `aad` (which is not encrypted and must be given again
|
|
/// to open).
|
|
///
|
|
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
|
|
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
|
|
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
|
|
///
|
|
/// # Errors
|
|
/// [`Error::NonContributory`] if the recipient's X25519 key is a low-order point.
|
|
pub fn seal<R: CryptoRng + ?Sized>(
|
|
recipient: &PublicKey,
|
|
plaintext: &[u8],
|
|
aad: &[u8],
|
|
rng: &mut R,
|
|
) -> Result<Vec<u8>, Error> {
|
|
let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]);
|
|
rng.fill_bytes(eseed.as_mut_slice());
|
|
seal_inner(recipient, plaintext, aad, &eseed)
|
|
}
|
|
|
|
/// [`seal`] with explicit randomness. **Hazmat** (feature `hazmat`), for tests: reusing an
|
|
/// `eseed` reuses key and nonce.
|
|
///
|
|
/// # Errors
|
|
/// As [`seal`].
|
|
#[cfg(feature = "hazmat")]
|
|
pub fn seal_derand(
|
|
recipient: &PublicKey,
|
|
plaintext: &[u8],
|
|
aad: &[u8],
|
|
eseed: &[u8; ENCAPSULATION_SEED_LEN],
|
|
) -> Result<Vec<u8>, Error> {
|
|
seal_inner(recipient, plaintext, aad, eseed)
|
|
}
|
|
|
|
fn seal_inner(
|
|
recipient: &PublicKey,
|
|
plaintext: &[u8],
|
|
aad: &[u8],
|
|
eseed: &[u8; ENCAPSULATION_SEED_LEN],
|
|
) -> Result<Vec<u8>, Error> {
|
|
let (ct, ss) = recipient.encapsulate_inner(eseed)?;
|
|
let (aead, nonce) = cipher(&seal_prk(&ss, recipient, &ct, aad));
|
|
|
|
// Allocated once at its final size, so no buffer that held plaintext is ever reallocated. It is
|
|
// `Zeroizing` until the plaintext has been encrypted in place, so an early return (the
|
|
// `MessageTooLong` path) wipes the copy instead of freeing it unwiped (QA R2-05).
|
|
let mut out = Zeroizing::new(Vec::with_capacity(plaintext.len() + OVERHEAD));
|
|
out.push(VERSION);
|
|
out.extend_from_slice(ct.as_bytes());
|
|
out.extend_from_slice(plaintext);
|
|
// ChaCha20-Poly1305 refuses only messages over 2^38 bytes; that is reported, not a panic.
|
|
let tag = aead
|
|
.encrypt_inout_detached(&nonce, &[VERSION], (&mut out[HEADER_LEN..]).into())
|
|
.map_err(|_| Error::MessageTooLong)?;
|
|
out.extend_from_slice(tag.as_slice());
|
|
// Now only ciphertext: move the buffer out without copying it (the wrapper keeps an empty Vec).
|
|
Ok(core::mem::take(&mut *out))
|
|
}
|
|
|
|
/// Open a sealed box with the recipient's secret key and the same `aad`.
|
|
///
|
|
/// # Errors
|
|
/// [`Error::TooShort`], [`Error::UnsupportedVersion`], [`Error::NonContributory`], or
|
|
/// [`Error::DecryptionFailed`] for a wrong key, wrong `aad`, or any tampering.
|
|
pub fn open(recipient: &SecretKey, sealed: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>, Error> {
|
|
if sealed.len() < OVERHEAD {
|
|
return Err(Error::TooShort { input: Input::SealedBox, minimum: OVERHEAD, actual: sealed.len() });
|
|
}
|
|
let (header, rest) = sealed.split_at(HEADER_LEN);
|
|
let (&version, ct) = header.split_first().ok_or(Error::DecryptionFailed)?;
|
|
if version != VERSION {
|
|
return Err(Error::UnsupportedVersion(version));
|
|
}
|
|
let ct = Ciphertext::from_bytes(ct)?;
|
|
let ss = recipient.decapsulate_inner(&ct)?;
|
|
let (aead, nonce) = cipher(&seal_prk(&ss, recipient.public_key(), &ct, aad));
|
|
|
|
let (body, tag) = rest.split_at(rest.len() - TAG_LEN);
|
|
let tag = chacha20poly1305::Tag::try_from(tag).map_err(|_| Error::DecryptionFailed)?;
|
|
// The tag is checked before anything is decrypted; on failure the buffer holds only ciphertext.
|
|
let mut plaintext = Zeroizing::new(body.to_vec());
|
|
aead.decrypt_inout_detached(&nonce, &[VERSION], plaintext.as_mut_slice().into(), &tag)
|
|
.map_err(|_| Error::DecryptionFailed)?;
|
|
Ok(plaintext)
|
|
}
|