pqbox 1.1.0

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
//! Authenticated encryption: XChaCha20-Poly1305 (`chacha20poly1305`, the default) and
//! AES-256-GCM (`aes-gcm`), with a fresh random nonce per message.
//!
//! [`encrypt`] returns `header || nonce || ciphertext || tag`, where the header's suite byte is the
//! cipher id (`0x01` XChaCha20-Poly1305, `0x02` AES-256-GCM), so [`decrypt`] needs only the key. The header is authenticated: the AEAD's
//! associated data is `header || aad`.
//!
//! Nonces are random: 24 bytes for XChaCha20-Poly1305 (no practical limit on messages per key)
//! and 12 bytes for AES-256-GCM (stay well below 2^32 messages per key).

use aes_gcm::Aes256Gcm;
use chacha20poly1305::XChaCha20Poly1305;
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use zeroize::Zeroizing;

use crate::format::{self, Kind, VERSION_2};

use crate::{Error, Result, Rng};

/// Key length of both ciphers.
pub const KEY_LEN: usize = 32;
/// Tag length of both ciphers.
pub const TAG_LEN: usize = 16;
/// XChaCha20-Poly1305 nonce length.
pub const XCHACHA_NONCE_LEN: usize = 24;
/// AES-256-GCM nonce length.
pub const AES_GCM_NONCE_LEN: usize = 12;

/// A supported AEAD.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum Algorithm {
    /// XChaCha20-Poly1305 (draft-irtf-cfrg-xchacha), 24-byte nonces. Id `0x01`.
    #[default]
    XChaCha20Poly1305 = 0x01,
    /// AES-256-GCM (NIST SP 800-38D), 12-byte nonces. Id `0x02`.
    Aes256Gcm = 0x02,
}

impl Algorithm {
    /// Parses `xchacha20poly1305` or `aes256gcm` (case-insensitive, `-`/`_` ignored).
    ///
    /// # Errors
    /// [`Error::InvalidParams`] for an unknown name.
    pub fn from_name(name: &str) -> Result<Self> {
        match name.to_ascii_lowercase().replace(['-', '_'], "").as_str() {
            "xchacha20poly1305" | "xchacha" => Ok(Self::XChaCha20Poly1305),
            "aes256gcm" | "aesgcm" => Ok(Self::Aes256Gcm),
            _ => Err(Error::InvalidParams("unknown AEAD algorithm")),
        }
    }

    /// The canonical name.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::XChaCha20Poly1305 => "xchacha20poly1305",
            Self::Aes256Gcm => "aes256gcm",
        }
    }

    /// Nonce length.
    #[must_use]
    pub fn nonce_len(self) -> usize {
        match self {
            Self::XChaCha20Poly1305 => XCHACHA_NONCE_LEN,
            Self::Aes256Gcm => AES_GCM_NONCE_LEN,
        }
    }

    /// Parses a cipher id.
    ///
    /// # Errors
    /// [`Error::UnknownSuite`] for an unknown id.
    pub fn from_id(id: u8) -> Result<Self> {
        match id {
            0x01 => Ok(Self::XChaCha20Poly1305),
            0x02 => Ok(Self::Aes256Gcm),
            other => Err(Error::UnknownSuite(other)),
        }
    }
}

/// A fresh random 32-byte key. Zeroized on drop.
pub fn generate_key<R: Rng + ?Sized>(rng: &mut R) -> Zeroizing<[u8; KEY_LEN]> {
    Zeroizing::new(crate::random(rng))
}

fn key32(key: &[u8]) -> Result<&[u8; KEY_LEN]> {
    key.try_into().map_err(|_| Error::InvalidLength("AEAD key"))
}

/// Encrypts with a fresh random nonce: `header || nonce || ciphertext || tag`.
///
/// # Errors
/// [`Error::InvalidLength`] when `key` is not 32 bytes.
pub fn encrypt<R: Rng + ?Sized>(
    alg: Algorithm,
    key: &[u8],
    plaintext: &[u8],
    aad: &[u8],
    rng: &mut R,
) -> Result<Vec<u8>> {
    let key = key32(key)?;
    let header = format::Header::current(Kind::AeadCiphertext, alg as u8).to_bytes();
    let mut nonce = vec![0u8; alg.nonce_len()];
    rng.fill_bytes(&mut nonce);
    let full_aad = [&header[..], aad].concat();
    let ct = encrypt_raw(alg, key, &nonce, &full_aad, plaintext)?;
    Ok([&header[..], &nonce, &ct].concat())
}

/// Decrypts the output of [`encrypt`] with the same key and `aad`. The plaintext is zeroized
/// when dropped.
///
/// # Errors
/// Header errors, [`Error::InvalidLength`], or [`Error::Decrypt`] when authentication fails.
pub fn decrypt(key: &[u8], data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
    let key = key32(key)?;
    let (h, body) = format::expect(data, Kind::AeadCiphertext)?;
    let alg = Algorithm::from_id(h.suite)?;
    match h.version {
        VERSION_2 => {
            if body.len() < alg.nonce_len() + TAG_LEN {
                return Err(Error::InvalidLength("AEAD ciphertext"));
            }
            let (nonce, ct) = format::take(body, alg.nonce_len(), "AEAD ciphertext")?;
            let full_aad = [&h.to_bytes()[..], aad].concat();
            decrypt_raw(alg, key, nonce, &full_aad, ct)
        }
        v => Err(Error::UnsupportedVersion(v)),
    }
}

/// Raw AEAD encryption with a caller-chosen nonce: `ciphertext || tag`, no header.
///
/// Reusing a nonce with the same key breaks confidentiality and authenticity; prefer [`encrypt`].
///
/// # Errors
/// [`Error::InvalidLength`] when the nonce has the wrong length.
pub fn encrypt_raw(alg: Algorithm, key: &[u8; KEY_LEN], nonce: &[u8], aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>> {
    if nonce.len() != alg.nonce_len() {
        return Err(Error::InvalidLength("AEAD nonce"));
    }
    let payload = Payload { msg: plaintext, aad };
    let out = match alg {
        Algorithm::XChaCha20Poly1305 => {
            let n: [u8; XCHACHA_NONCE_LEN] = nonce.try_into().map_err(|_| Error::InvalidLength("AEAD nonce"))?;
            XChaCha20Poly1305::new(key.into()).encrypt(&n.into(), payload)
        }
        Algorithm::Aes256Gcm => {
            let n: [u8; AES_GCM_NONCE_LEN] = nonce.try_into().map_err(|_| Error::InvalidLength("AEAD nonce"))?;
            Aes256Gcm::new(key.into()).encrypt(&n.into(), payload)
        }
    };
    out.map_err(|_| Error::InvalidParams("plaintext too long"))
}

/// Raw AEAD decryption of `ciphertext || tag` with an explicit nonce. The plaintext is zeroized
/// when dropped.
///
/// # Errors
/// [`Error::InvalidLength`] for a wrong nonce length, [`Error::Decrypt`] when authentication fails.
pub fn decrypt_raw(
    alg: Algorithm,
    key: &[u8; KEY_LEN],
    nonce: &[u8],
    aad: &[u8],
    ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>> {
    if nonce.len() != alg.nonce_len() {
        return Err(Error::InvalidLength("AEAD nonce"));
    }
    let payload = Payload { msg: ciphertext, aad };
    let out = match alg {
        Algorithm::XChaCha20Poly1305 => {
            let n: [u8; XCHACHA_NONCE_LEN] = nonce.try_into().map_err(|_| Error::InvalidLength("AEAD nonce"))?;
            XChaCha20Poly1305::new(key.into()).decrypt(&n.into(), payload)
        }
        Algorithm::Aes256Gcm => {
            let n: [u8; AES_GCM_NONCE_LEN] = nonce.try_into().map_err(|_| Error::InvalidLength("AEAD nonce"))?;
            Aes256Gcm::new(key.into()).decrypt(&n.into(), payload)
        }
    };
    out.map(Zeroizing::new).map_err(|_| Error::Decrypt)
}

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

    const ALGS: [Algorithm; 2] = [Algorithm::XChaCha20Poly1305, Algorithm::Aes256Gcm];

    #[test]
    fn round_trip() {
        let mut rng = rng();
        for alg in ALGS {
            let key = generate_key(&mut rng);
            let ct = encrypt(alg, &key[..], b"hello", b"aad", &mut rng).unwrap();
            assert_eq!(ct.len(), HEADER_LEN + alg.nonce_len() + 5 + TAG_LEN);
            assert_eq!(*decrypt(&key[..], &ct, b"aad").unwrap(), b"hello");
            assert_eq!(Algorithm::from_name(alg.name()).unwrap(), alg);
            assert_eq!(Algorithm::from_id(alg as u8).unwrap(), alg);
        }
    }

    #[test]
    fn tamper_and_wrong_key_fail() {
        let mut rng = rng();
        for alg in ALGS {
            let key = generate_key(&mut rng);
            let other = generate_key(&mut rng);
            let ct = encrypt(alg, &key[..], b"hello", b"aad", &mut rng).unwrap();
            assert_eq!(decrypt(&other[..], &ct, b"aad"), Err(Error::Decrypt));
            assert_eq!(decrypt(&key[..], &ct, b"other"), Err(Error::Decrypt));
            for i in HEADER_LEN..ct.len() {
                let mut t = ct.clone();
                t[i] ^= 0x01;
                assert_eq!(decrypt(&key[..], &t, b"aad"), Err(Error::Decrypt), "byte {i}");
            }
            assert_eq!(
                decrypt(&key[..], &ct[..HEADER_LEN + 3], b"aad"),
                Err(Error::InvalidLength("AEAD ciphertext"))
            );
        }
    }

    #[test]
    fn header_is_authenticated() {
        // Swapping the cipher type byte is caught (as a failed decryption, not a silent downgrade).
        let mut rng = rng();
        let key = generate_key(&mut rng);
        let mut ct = encrypt(Algorithm::Aes256Gcm, &key[..], b"hello", b"", &mut rng).unwrap();
        ct[5] = Algorithm::XChaCha20Poly1305 as u8;
        // The nonce is now read with the wrong length, and the header is authenticated anyway.
        assert!(decrypt(&key[..], &ct, b"").is_err());
        ct[5] = 0x07;
        assert_eq!(decrypt(&key[..], &ct, b""), Err(Error::UnknownSuite(7)));
    }

    #[test]
    fn rejects_bad_key_length() {
        let mut rng = rng();
        assert_eq!(
            encrypt(Algorithm::default(), &[0u8; 16], b"", b"", &mut rng),
            Err(Error::InvalidLength("AEAD key"))
        );
    }
}