pqbox 1.1.1

Post-quantum crypto toolkit: hybrid ML-KEM-1024 + P-384 sealed boxes, composite ML-DSA-87 signatures, an opt-in paranoid suite adding Classic McEliece and SLH-DSA, AEAD, KDF, hashing and Argon2id
Documentation
//! Sealed boxes: anonymous public-key encryption to a KEM public key, in the spirit of
//! libsodium's `crypto_box_seal`. The box uses the recipient key's suite.
//!
//! ```text
//! (ct, ss) = KEM.Encaps(pk)                       -- the suite's hybrid KEM
//! header   = "PQB" || 0x01 || 0x21 || suite
//! key      = HKDF-SHA-256(ikm = ss, salt = "",
//!                         info = "pqbox/v1/seal" || header || ct || SHA3-256(serialized pk), 32)
//! nonce    = 24 random bytes
//! box      = header || ct || nonce || XChaCha20-Poly1305(key, nonce, aad = header, plaintext)
//! ```
//!
//! The key derivation binds the suite, the encapsulation ciphertext and the recipient's public
//! key, so a box cannot be re-targeted or downgraded. Sealed boxes are not authenticated to a
//! sender: sign the plaintext with [`crate::sign`] when the recipient needs to know who sent it.

use zeroize::Zeroizing;

use crate::aead::{self, Algorithm, TAG_LEN, XCHACHA_NONCE_LEN};
use crate::format::{self, HEADER_LEN, Header, Kind, VERSION_2};
use crate::kem::{self, Ciphertext, PublicKey, SecretKey, SharedSecret};
use crate::{Error, Result, Rng, Suite, SuitePolicy};

/// HKDF info label.
pub const INFO: &[u8] = b"pqbox/v1/seal";

/// Bytes a sealed box adds to the plaintext for `suite`.
#[must_use]
pub fn overhead(suite: Suite) -> usize {
    HEADER_LEN + kem::ciphertext_len(suite) + XCHACHA_NONCE_LEN + TAG_LEN
}

fn derive_key(ss: &SharedSecret, header: &[u8], ct: &Ciphertext, pk: &PublicKey) -> Result<Zeroizing<[u8; 32]>> {
    let mut key = Zeroizing::new([0u8; 32]);
    crate::kdf::hkdf_sha256_into(
        ss.as_bytes(),
        b"",
        &[INFO, header, ct.as_raw(), &pk.fingerprint()],
        &mut key[..],
    )?;
    Ok(key)
}

/// Seals `plaintext` to `recipient`.
///
/// # Errors
/// Only if the KEM fails, which a parsed public key does not allow.
pub fn seal<R: Rng + ?Sized>(recipient: &PublicKey, plaintext: &[u8], rng: &mut R) -> Result<Vec<u8>> {
    let header = Header::current(Kind::SealedBox, recipient.suite().id()).to_bytes();
    let (ct, ss) = recipient.encapsulate(rng)?;
    let key = derive_key(&ss, &header, &ct, recipient)?;
    let nonce: [u8; XCHACHA_NONCE_LEN] = crate::random(rng);
    let body = aead::encrypt_raw(Algorithm::XChaCha20Poly1305, &key, &nonce, &header, plaintext)?;
    Ok([&header[..], ct.as_raw(), &nonce, &body].concat())
}

/// Opens a box sealed to `recipient`'s public key, accepting only boxes of the
/// [`SuitePolicy::DEFAULT`] suites (`pqbox-max`). The plaintext is zeroized when dropped.
///
/// # Errors
/// Header errors, [`Error::SuiteNotAllowed`] for a box of a suite the policy refuses,
/// [`Error::SuiteMismatch`] for a box of another suite than the key's, [`Error::InvalidLength`],
/// or [`Error::Decrypt`] for a tampered box or a box sealed to another key.
pub fn open(recipient: &SecretKey, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
    open_with_policy(recipient, sealed, SuitePolicy::DEFAULT)
}

/// [`open`] for boxes of the suites `policy` allows (for example
/// `SuitePolicy::DEFAULT.allow(Suite::XWing)`).
///
/// # Errors
/// As [`open`].
pub fn open_with_policy(recipient: &SecretKey, sealed: &[u8], policy: SuitePolicy) -> Result<Zeroizing<Vec<u8>>> {
    let (h, body) = format::expect(sealed, Kind::SealedBox)?;
    if h.version != VERSION_2 {
        return Err(Error::UnsupportedVersion(h.version));
    }
    let suite = policy.suite_from_id(h.suite)?;
    if suite != recipient.suite() {
        return Err(Error::SuiteMismatch {
            expected: recipient.suite().name(),
            found: suite.name(),
        });
    }
    if body.len() < kem::ciphertext_len(suite) + XCHACHA_NONCE_LEN + TAG_LEN {
        return Err(Error::InvalidLength("sealed box"));
    }
    let (ct, rest) = format::take(body, kem::ciphertext_len(suite), "sealed box")?;
    let (nonce, body) = format::take(rest, XCHACHA_NONCE_LEN, "sealed box")?;
    let ct = Ciphertext::from_raw(suite, ct)?;
    let ss = recipient.decapsulate(&ct)?;
    let header = h.to_bytes();
    let key = derive_key(&ss, &header, &ct, recipient.public_key())?;
    aead::decrypt_raw(Algorithm::XChaCha20Poly1305, &key, nonce, &header, body)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::rng;

    #[test]
    fn round_trip_every_suite() {
        let mut rng = rng();
        for suite in Suite::ALL {
            let sk = SecretKey::generate(suite, &mut rng).unwrap();
            for len in [0usize, 1, 1000] {
                let msg = vec![0x5a; len];
                let sealed = seal(sk.public_key(), &msg, &mut rng).unwrap();
                assert_eq!(sealed.len(), msg.len() + overhead(suite));
                assert_eq!(*open_with_policy(&sk, &sealed, SuitePolicy::ALL).unwrap(), msg);
                if suite != Suite::Max {
                    assert_eq!(open(&sk, &sealed), Err(Error::SuiteNotAllowed(suite.name())));
                }
            }
        }
    }

    #[test]
    fn wrong_key_and_wrong_suite_fail() {
        let mut rng = rng();
        let a = SecretKey::generate(Suite::Max, &mut rng).unwrap();
        let b = SecretKey::generate(Suite::Max, &mut rng).unwrap();
        let x = SecretKey::generate(Suite::XWing, &mut rng).unwrap();
        let sealed = seal(a.public_key(), b"secret", &mut rng).unwrap();
        assert_eq!(open(&b, &sealed), Err(Error::Decrypt));
        assert!(matches!(open(&x, &sealed), Err(Error::SuiteMismatch { .. })));
    }
}