use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; pub const VERSION: u8 = 1; /// PQ handshake prelude. Body is `uint16 ct_len` (big-endian) followed by /// exactly `ct_len` bytes. Only the opening frame of a session may use it. pub const VERSION_PRELUDE: u8 = 2; pub const MAX_FRAME: usize = 65535; pub type Result = std::result::Result; #[derive(Debug)] pub struct Error(pub String); impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl std::error::Error for Error {} pub fn encode(body: &[u8]) -> Result> { if body.len() > MAX_FRAME { return Err(Error("frame too large".into())); } let mut out = Vec::with_capacity(5 + body.len()); out.push(VERSION); out.extend_from_slice(&(body.len() as u32).to_be_bytes()); out.extend_from_slice(body); Ok(out) } pub fn decode(data: &[u8]) -> Result> { if data.len() < 5 { return Err(Error("short frame".into())); } if data[0] != VERSION { return Err(Error("bad version".into())); } let len = u32::from_be_bytes(data[1..5].try_into().expect("4 bytes")) as usize; if data.len() != 5 + len { return Err(Error("length mismatch".into())); } if len > MAX_FRAME { return Err(Error("frame too large".into())); } Ok(data[5..].to_vec()) } pub async fn write_frame(w: &mut W, body: &[u8]) -> Result<()> { let framed = encode(body)?; w.write_all(&framed) .await .map_err(|e| Error(e.to_string()))?; w.flush().await.map_err(|e| Error(e.to_string())) } pub async fn read_frame(r: &mut R) -> Result> { let (version, body) = read_versioned(r).await?; if version != VERSION { return Err(Error("bad version".into())); } Ok(body) } /// First frame of a handshake. Version 1 is Noise msg 1 (classical). Version 2 /// is the PQ prelude; the ciphertext is exactly `ct_len` bytes and must be the /// ML-KEM-768 ciphertext length. pub enum Opening { Classical(Vec), Prelude(Vec), } pub async fn read_opening(r: &mut R) -> Result { let (version, body) = read_versioned(r).await?; match version { VERSION => Ok(Opening::Classical(body)), VERSION_PRELUDE => Ok(Opening::Prelude(parse_prelude(&body)?)), _ => Err(Error("bad version".into())), } } pub async fn write_prelude(w: &mut W, ct: &[u8]) -> Result<()> { if ct.len() > u16::MAX as usize { return Err(Error("frame too large".into())); } let mut body = Vec::with_capacity(2 + ct.len()); body.extend_from_slice(&(ct.len() as u16).to_be_bytes()); body.extend_from_slice(ct); let framed = encode_version(VERSION_PRELUDE, &body)?; w.write_all(&framed) .await .map_err(|e| Error(e.to_string()))?; w.flush().await.map_err(|e| Error(e.to_string())) } pub fn parse_prelude(body: &[u8]) -> Result> { if body.len() < 2 { return Err(Error("short frame".into())); } let ct_len = u16::from_be_bytes(body[..2].try_into().expect("2 bytes")) as usize; if body.len() != 2 + ct_len { return Err(Error("length mismatch".into())); } if ct_len != crate::kem::CT_LEN { return Err(Error("bad prelude".into())); } Ok(body[2..].to_vec()) } async fn read_versioned(r: &mut R) -> Result<(u8, Vec)> { let mut hdr = [0u8; 5]; r.read_exact(&mut hdr) .await .map_err(|e| Error(e.to_string()))?; let version = hdr[0]; if version != VERSION && version != VERSION_PRELUDE { return Err(Error("bad version".into())); } let len = u32::from_be_bytes(hdr[1..5].try_into().expect("4 bytes")) as usize; if len > MAX_FRAME { return Err(Error("frame too large".into())); } let mut body = vec![0u8; len]; r.read_exact(&mut body) .await .map_err(|e| Error(e.to_string()))?; Ok((version, body)) } fn encode_version(version: u8, body: &[u8]) -> Result> { if body.len() > MAX_FRAME { return Err(Error("frame too large".into())); } let mut out = Vec::with_capacity(5 + body.len()); out.push(version); out.extend_from_slice(&(body.len() as u32).to_be_bytes()); out.extend_from_slice(body); Ok(out) }