Skip to main content

zaun_community_protocol/
keys.rs

1//! Public key and signature encodings (specification §3.2, §3.4). Only the byte layout and
2//! suite check live here; signing and verification are in the `crypto` module.
3//!
4//! ```text
5//! PublicKey = suite u8 ‖ mldsa65_pk [1952] ‖ ed25519_pk [32]    (1 985 B)
6//! Signature = suite u8 ‖ mldsa65_sig [3309] ‖ ed25519_sig [64]  (3 374 B)
7//! ```
8
9use std::fmt;
10
11use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
12
13use crate::b64;
14
15/// A signature suite (specification §3.2). `0x00` and `0x02`–`0xFF` are rejected.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17#[repr(u8)]
18pub enum Suite {
19    /// RFC 10073 `id-MLDSA65-Ed25519-SHA512` (OID 1.3.6.1.5.5.7.6.48).
20    MlDsa65Ed25519 = 1,
21}
22
23impl Suite {
24    /// Parses a suite byte.
25    #[must_use]
26    pub const fn from_byte(byte: u8) -> Option<Self> {
27        match byte {
28            1 => Some(Self::MlDsa65Ed25519),
29            _ => None,
30        }
31    }
32
33    /// The suite byte.
34    #[must_use]
35    pub const fn byte(self) -> u8 {
36        self as u8
37    }
38}
39
40/// ML-DSA-65 public key length.
41pub const MLDSA65_PK_LEN: usize = 1_952;
42/// ML-DSA-65 signature length.
43pub const MLDSA65_SIG_LEN: usize = 3_309;
44/// Ed25519 public key length.
45pub const ED25519_PK_LEN: usize = 32;
46/// Ed25519 signature length.
47pub const ED25519_SIG_LEN: usize = 64;
48/// Encoded [`PublicKey`] length.
49pub const PUBLIC_KEY_LEN: usize = 1 + MLDSA65_PK_LEN + ED25519_PK_LEN;
50/// Encoded [`Signature`] length.
51pub const SIGNATURE_LEN: usize = 1 + MLDSA65_SIG_LEN + ED25519_SIG_LEN;
52
53/// The encoding is not a known suite or has the wrong length.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
55pub enum KeyEncodingError {
56    /// Suite byte `0x00` or `0x02`–`0xFF`.
57    #[error("unknown signature suite {0}")]
58    UnknownSuite(u8),
59    /// Wrong total length for the suite.
60    #[error("wrong length {0}")]
61    Length(usize),
62}
63
64fn check(bytes: &[u8], len: usize) -> Result<Suite, KeyEncodingError> {
65    let first = *bytes.first().ok_or(KeyEncodingError::Length(0))?;
66    let suite = Suite::from_byte(first).ok_or(KeyEncodingError::UnknownSuite(first))?;
67    if bytes.len() == len {
68        Ok(suite)
69    } else {
70        Err(KeyEncodingError::Length(bytes.len()))
71    }
72}
73
74macro_rules! encoded {
75    ($(#[$doc:meta])* $name:ident, $len:expr, $split:expr) => {
76        $(#[$doc])*
77        #[derive(Clone, PartialEq, Eq, Hash)]
78        pub struct $name(Box<[u8]>);
79
80        impl $name {
81            /// Parses the encoding, checking the suite byte and length.
82            ///
83            /// # Errors
84            /// [`KeyEncodingError`] for an unknown suite or a wrong length.
85            pub fn from_bytes(bytes: &[u8]) -> Result<Self, KeyEncodingError> {
86                check(bytes, $len)?;
87                Ok(Self(bytes.into()))
88            }
89
90            /// The full encoding, suite byte first.
91            #[must_use]
92            pub fn as_bytes(&self) -> &[u8] {
93                &self.0
94            }
95
96            /// The suite.
97            #[must_use]
98            pub fn suite(&self) -> Suite {
99                // Checked in `from_bytes`; suite 1 is the only one.
100                Suite::MlDsa65Ed25519
101            }
102
103            /// The ML-DSA-65 component (RFC 10073 serialisation, first part).
104            #[must_use]
105            pub fn mldsa(&self) -> &[u8] {
106                &self.0[1..1 + $split]
107            }
108
109            /// The Ed25519 component (RFC 10073 serialisation, second part).
110            #[must_use]
111            pub fn ed25519(&self) -> &[u8] {
112                &self.0[1 + $split..]
113            }
114        }
115
116        impl fmt::Debug for $name {
117            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118                // Long values: show the suite and a short prefix only.
119                let head: String = b64::encode(&self.0[1..13]);
120                write!(f, "{}(suite={}, {}…)", stringify!($name), self.0[0], head)
121            }
122        }
123
124        impl Serialize for $name {
125            fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
126                s.serialize_str(&b64::encode(&self.0))
127            }
128        }
129
130        impl<'de> Deserialize<'de> for $name {
131            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
132                let text = <std::borrow::Cow<'de, str>>::deserialize(d)?;
133                if text.len() != b64::encoded_len($len) {
134                    return Err(D::Error::custom(concat!("invalid ", stringify!($name))));
135                }
136                let bytes = b64::decode(&text).map_err(D::Error::custom)?;
137                Self::from_bytes(&bytes).map_err(D::Error::custom)
138            }
139        }
140    };
141}
142
143encoded!(
144    /// A composite public key (specification §3.4), 1 985 bytes.
145    PublicKey, PUBLIC_KEY_LEN, MLDSA65_PK_LEN
146);
147encoded!(
148    /// A composite signature (specification §3.4), 3 374 bytes.
149    Signature, SIGNATURE_LEN, MLDSA65_SIG_LEN
150);
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn sizes_match_the_specification() {
158        assert_eq!(PUBLIC_KEY_LEN, 1_985);
159        assert_eq!(SIGNATURE_LEN, 3_374);
160    }
161
162    #[test]
163    fn suites_zero_and_two_up_are_rejected() {
164        for suite in [0u8, 2, 3, 0x7f, 0xff] {
165            let mut pk = vec![0u8; PUBLIC_KEY_LEN];
166            pk[0] = suite;
167            assert_eq!(
168                PublicKey::from_bytes(&pk),
169                Err(KeyEncodingError::UnknownSuite(suite))
170            );
171            let mut sig = vec![0u8; SIGNATURE_LEN];
172            sig[0] = suite;
173            assert_eq!(
174                Signature::from_bytes(&sig),
175                Err(KeyEncodingError::UnknownSuite(suite))
176            );
177        }
178        let mut pk = vec![0u8; PUBLIC_KEY_LEN];
179        pk[0] = 1;
180        let key = PublicKey::from_bytes(&pk).unwrap();
181        assert_eq!(key.mldsa().len(), MLDSA65_PK_LEN);
182        assert_eq!(key.ed25519().len(), ED25519_PK_LEN);
183        assert!(PublicKey::from_bytes(&pk[..PUBLIC_KEY_LEN - 1]).is_err());
184        assert!(PublicKey::from_bytes(&[]).is_err());
185        let json = serde_json::to_string(&key).unwrap();
186        assert_eq!(serde_json::from_str::<PublicKey>(&json).unwrap(), key);
187    }
188}