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
//! The versioned wire format.
//!
//! Every serialized object is `header || body`, where the six-byte header is:
//!
//! | Offset | Size | Value |
//! |---|---|---|
//! | 0 | 3 | magic `PQB` (`0x50 0x51 0x42`) |
//! | 3 | 1 | format version (`0x02`) |
//! | 4 | 1 | object type ([`Kind`]) |
//! | 5 | 1 | suite id ([`crate::Suite`]); for AEAD ciphertexts, the cipher id ([`crate::aead::Algorithm`]) |
//!
//! The body layout depends on the version, the type and the suite, and is documented on each
//! type. Parsers dispatch on the version byte: a future version adds a new arm next to
//! [`VERSION_2`] while the older arms stay, so objects written by released versions remain
//! readable. Unknown versions are rejected with [`Error::UnsupportedVersion`].
//!
//! Version 2 is the first released format. Version 1 was a pre-release layout (its
//! `pqbox-paranoid` KEM secret key did not bind the public key) and is not read: no release ever
//! wrote it. The `pqbox/v1/...` domain-separation labels of the combiners, sealed boxes and
//! signatures are protocol constants, independent of the wire format version, and did not change.

use crate::{Error, Result};

/// The magic bytes every object starts with.
pub const MAGIC: [u8; 3] = *b"PQB";
/// Format version 2, the current one.
pub const VERSION_2: u8 = 0x02;
/// The version this build writes.
pub const CURRENT_VERSION: u8 = VERSION_2;
/// Every version this build reads.
pub const SUPPORTED_VERSIONS: &[u8] = &[VERSION_2];
/// Header length.
pub const HEADER_LEN: usize = 6;

/// The object type carried in the fifth header byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Kind {
    /// KEM public (encapsulation) key.
    KemPublicKey = 0x01,
    /// KEM secret (decapsulation) key.
    KemSecretKey = 0x02,
    /// KEM ciphertext.
    KemCiphertext = 0x03,
    /// Hybrid signing public key.
    SignPublicKey = 0x11,
    /// Hybrid signing secret key.
    SignSecretKey = 0x12,
    /// Hybrid signature.
    Signature = 0x13,
    /// Sealed box.
    SealedBox = 0x21,
    /// AEAD ciphertext with its nonce.
    AeadCiphertext = 0x31,
}

impl Kind {
    /// Parses a type byte.
    ///
    /// # Errors
    /// [`Error::UnknownKind`] for an unassigned value.
    pub fn from_u8(b: u8) -> Result<Self> {
        Ok(match b {
            0x01 => Self::KemPublicKey,
            0x02 => Self::KemSecretKey,
            0x03 => Self::KemCiphertext,
            0x11 => Self::SignPublicKey,
            0x12 => Self::SignSecretKey,
            0x13 => Self::Signature,
            0x21 => Self::SealedBox,
            0x31 => Self::AeadCiphertext,
            other => return Err(Error::UnknownKind(other)),
        })
    }

    /// A human-readable name.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::KemPublicKey => "KEM public key",
            Self::KemSecretKey => "KEM secret key",
            Self::KemCiphertext => "KEM ciphertext",
            Self::SignPublicKey => "signing public key",
            Self::SignSecretKey => "signing secret key",
            Self::Signature => "signature",
            Self::SealedBox => "sealed box",
            Self::AeadCiphertext => "AEAD ciphertext",
        }
    }
}

/// A parsed header.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
    /// Format version.
    pub version: u8,
    /// Object type.
    pub kind: Kind,
    /// Suite id (or AEAD cipher id), validated by the module that owns the type.
    pub suite: u8,
}

impl Header {
    /// A header in the current version.
    #[must_use]
    pub fn current(kind: Kind, suite: u8) -> Self {
        Self {
            version: CURRENT_VERSION,
            kind,
            suite,
        }
    }

    /// The six header bytes.
    #[must_use]
    pub fn to_bytes(self) -> [u8; HEADER_LEN] {
        [MAGIC[0], MAGIC[1], MAGIC[2], self.version, self.kind as u8, self.suite]
    }
}

/// Splits `data` into its header and body.
///
/// # Errors
/// [`Error::BadMagic`], [`Error::UnsupportedVersion`] or [`Error::UnknownKind`].
pub fn parse(data: &[u8]) -> Result<(Header, &[u8])> {
    let Some(([m0, m1, m2, version, kind, suite], body)) = data.split_first_chunk::<HEADER_LEN>() else {
        return Err(Error::BadMagic);
    };
    if [*m0, *m1, *m2] != MAGIC {
        return Err(Error::BadMagic);
    }
    if !SUPPORTED_VERSIONS.contains(version) {
        return Err(Error::UnsupportedVersion(*version));
    }
    let kind = Kind::from_u8(*kind)?;
    Ok((
        Header {
            version: *version,
            kind,
            suite: *suite,
        },
        body,
    ))
}

/// Like [`parse`], also checking the object type.
///
/// # Errors
/// As [`parse`], plus [`Error::WrongKind`].
pub fn expect(data: &[u8], kind: Kind) -> Result<(Header, &[u8])> {
    let (h, body) = parse(data)?;
    if h.kind != kind {
        return Err(Error::WrongKind {
            expected: kind.name(),
            found: h.kind.name(),
        });
    }
    Ok((h, body))
}

/// `header || parts...` in the current version.
pub(crate) fn encode(kind: Kind, suite: u8, parts: &[&[u8]]) -> Vec<u8> {
    let len = HEADER_LEN + parts.iter().map(|p| p.len()).sum::<usize>();
    let mut out = Vec::with_capacity(len);
    out.extend_from_slice(&Header::current(kind, suite).to_bytes());
    for p in parts {
        out.extend_from_slice(p);
    }
    out
}

/// Splits `n` bytes off the front of `data`, or reports `what` as truncated.
pub(crate) fn take<'a>(data: &'a [u8], n: usize, what: &'static str) -> Result<(&'a [u8], &'a [u8])> {
    data.split_at_checked(n).ok_or(Error::InvalidLength(what))
}

/// Splits `data` into consecutive fields of the given lengths, requiring an exact fit.
pub(crate) fn fields<'a, const N: usize>(
    data: &'a [u8],
    lens: [usize; N],
    what: &'static str,
) -> Result<[&'a [u8]; N]> {
    let mut out: [&'a [u8]; N] = [&[]; N];
    let mut rest = data;
    for (slot, n) in out.iter_mut().zip(lens) {
        let (field, tail) = take(rest, n, what)?;
        *slot = field;
        rest = tail;
    }
    if rest.is_empty() {
        Ok(out)
    } else {
        Err(Error::InvalidLength(what))
    }
}

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

    #[test]
    fn header_round_trip() {
        let bytes = encode(Kind::Signature, 2, &[b"body"]);
        assert_eq!(&bytes[..6], b"PQB\x02\x13\x02");
        let (h, body) = parse(&bytes).unwrap();
        assert_eq!(h, Header::current(Kind::Signature, 2));
        assert_eq!(body, b"body");
    }

    #[test]
    fn rejects_bad_headers() {
        assert_eq!(parse(b"PQB\x02\x01"), Err(Error::BadMagic));
        assert_eq!(parse(b"XQB\x01\x01\x02"), Err(Error::BadMagic));
        assert_eq!(parse(b"PQB\x03\x01\x02"), Err(Error::UnsupportedVersion(3)));
        // The pre-release version 1 is not read.
        assert_eq!(parse(b"PQB\x01\x01\x02"), Err(Error::UnsupportedVersion(1)));
        assert_eq!(parse(b"PQB\x00\x01\x02"), Err(Error::UnsupportedVersion(0)));
        assert_eq!(parse(b"PQB\x02\x7f\x02"), Err(Error::UnknownKind(0x7f)));
        assert!(matches!(
            expect(b"PQB\x02\x01\x02", Kind::Signature),
            Err(Error::WrongKind { .. })
        ));
    }

    #[test]
    fn fields_require_exact_fit() {
        assert_eq!(fields(b"abcdef", [2, 4], "x").unwrap(), [&b"ab"[..], &b"cdef"[..]]);
        assert_eq!(fields(b"abcdef", [2, 3], "x"), Err(Error::InvalidLength("x")));
        assert_eq!(fields(b"abcdef", [2, 5], "x"), Err(Error::InvalidLength("x")));
    }

    #[test]
    fn every_kind_round_trips() {
        for b in 0..=255u8 {
            if let Ok(k) = Kind::from_u8(b) {
                assert_eq!(k as u8, b);
            }
        }
    }
}