zaun_community_protocol/
keys.rs1use std::fmt;
10
11use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
12
13use crate::b64;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17#[repr(u8)]
18pub enum Suite {
19 MlDsa65Ed25519 = 1,
21}
22
23impl Suite {
24 #[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 #[must_use]
35 pub const fn byte(self) -> u8 {
36 self as u8
37 }
38}
39
40pub const MLDSA65_PK_LEN: usize = 1_952;
42pub const MLDSA65_SIG_LEN: usize = 3_309;
44pub const ED25519_PK_LEN: usize = 32;
46pub const ED25519_SIG_LEN: usize = 64;
48pub const PUBLIC_KEY_LEN: usize = 1 + MLDSA65_PK_LEN + ED25519_PK_LEN;
50pub const SIGNATURE_LEN: usize = 1 + MLDSA65_SIG_LEN + ED25519_SIG_LEN;
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
55pub enum KeyEncodingError {
56 #[error("unknown signature suite {0}")]
58 UnknownSuite(u8),
59 #[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 pub fn from_bytes(bytes: &[u8]) -> Result<Self, KeyEncodingError> {
86 check(bytes, $len)?;
87 Ok(Self(bytes.into()))
88 }
89
90 #[must_use]
92 pub fn as_bytes(&self) -> &[u8] {
93 &self.0
94 }
95
96 #[must_use]
98 pub fn suite(&self) -> Suite {
99 Suite::MlDsa65Ed25519
101 }
102
103 #[must_use]
105 pub fn mldsa(&self) -> &[u8] {
106 &self.0[1..1 + $split]
107 }
108
109 #[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 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 PublicKey, PUBLIC_KEY_LEN, MLDSA65_PK_LEN
146);
147encoded!(
148 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}