use crate::{Error, Result};
pub const MAGIC: [u8; 3] = *b"PQB";
pub const VERSION_2: u8 = 0x02;
pub const CURRENT_VERSION: u8 = VERSION_2;
pub const SUPPORTED_VERSIONS: &[u8] = &[VERSION_2];
pub const HEADER_LEN: usize = 6;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Kind {
KemPublicKey = 0x01,
KemSecretKey = 0x02,
KemCiphertext = 0x03,
SignPublicKey = 0x11,
SignSecretKey = 0x12,
Signature = 0x13,
SealedBox = 0x21,
AeadCiphertext = 0x31,
}
impl Kind {
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)),
})
}
#[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",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
pub version: u8,
pub kind: Kind,
pub suite: u8,
}
impl Header {
#[must_use]
pub fn current(kind: Kind, suite: u8) -> Self {
Self {
version: CURRENT_VERSION,
kind,
suite,
}
}
#[must_use]
pub fn to_bytes(self) -> [u8; HEADER_LEN] {
[MAGIC[0], MAGIC[1], MAGIC[2], self.version, self.kind as u8, self.suite]
}
}
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,
))
}
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))
}
#[cfg(any(feature = "suite-max", feature = "suite-xwing"))]
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
}
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))
}
#[cfg(any(feature = "suite-max", feature = "suite-xwing"))]
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::*;
#[cfg(any(feature = "suite-max", feature = "suite-xwing"))]
#[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)));
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 { .. })
));
}
#[cfg(any(feature = "suite-max", feature = "suite-xwing"))]
#[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);
}
}
}
}