1use crate::error::{CoreError, Result};
24
25pub const ED25519_PUB_CODEC: u16 = 0xed;
27pub const ED25519_PRIV_CODEC: u16 = 0x1300;
28pub const MLDSA44_PUB_CODEC: u16 = 0x1210;
29pub const MLDSA44_PRIV_CODEC: u16 = 0x1317;
30pub const SLHDSA128_PUB_CODEC: u16 = 0x1220;
31pub const SLHDSA128_PRIV_CODEC: u16 = 0x131d;
32
33const fn varint2(code: u16) -> [u8; 2] {
36 [((code & 0x7f) as u8) | 0x80, (code >> 7) as u8]
37}
38
39pub const ED25519_PUB_PREFIX: [u8; 2] = varint2(ED25519_PUB_CODEC);
41pub const ED25519_PRIV_PREFIX: [u8; 2] = varint2(ED25519_PRIV_CODEC);
42pub const MLDSA44_PUB_PREFIX: [u8; 2] = varint2(MLDSA44_PUB_CODEC);
43pub const MLDSA44_PRIV_PREFIX: [u8; 2] = varint2(MLDSA44_PRIV_CODEC);
44pub const SLHDSA128_PUB_PREFIX: [u8; 2] = varint2(SLHDSA128_PUB_CODEC);
45pub const SLHDSA128_PRIV_PREFIX: [u8; 2] = varint2(SLHDSA128_PRIV_CODEC);
46
47pub const SLHDSA128: &str = "SLH-DSA-SHA2-128s";
49
50const ED25519_PUBLIC_LEN: usize = 32;
51const MLDSA44_PUBLIC_LEN: usize = 1312;
52const SLHDSA128_PUBLIC_LEN: usize = 32;
53const SLHDSA128_MULTIKEY_BODY_LEN: usize = 46;
56
57pub const MAX_BASE58_LEN: usize = 8192;
62
63pub fn decode_base58_bounded(s: &str) -> Result<Vec<u8>> {
67 if s.len() > MAX_BASE58_LEN {
68 return Err(CoreError::InvalidMultikey(format!(
69 "base58 input too long: {} > {MAX_BASE58_LEN}",
70 s.len()
71 )));
72 }
73 bs58::decode(s)
74 .into_vec()
75 .map_err(|e| CoreError::InvalidMultikey(format!("bad base58: {e}")))
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct DecodedKey {
81 pub algorithm: String,
82 pub raw_key: Vec<u8>,
83}
84
85fn encode_with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
86 let mut buf = Vec::with_capacity(2 + raw.len());
87 buf.extend_from_slice(&prefix);
88 buf.extend_from_slice(raw);
89 format!("z{}", bs58::encode(buf).into_string())
90}
91
92pub fn encode_ed25519_public(raw: &[u8]) -> Result<String> {
94 if raw.len() != ED25519_PUBLIC_LEN {
95 return Err(CoreError::InvalidKeyLength {
96 expected: ED25519_PUBLIC_LEN,
97 got: raw.len(),
98 });
99 }
100 Ok(encode_with_prefix(ED25519_PUB_PREFIX, raw))
101}
102
103pub fn encode_mldsa44_public(raw: &[u8]) -> Result<String> {
105 if raw.len() != MLDSA44_PUBLIC_LEN {
106 return Err(CoreError::InvalidKeyLength {
107 expected: MLDSA44_PUBLIC_LEN,
108 got: raw.len(),
109 });
110 }
111 Ok(encode_with_prefix(MLDSA44_PUB_PREFIX, raw))
112}
113
114pub fn encode_slhdsa128_public(raw: &[u8]) -> Result<String> {
118 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
119 if raw.len() != SLHDSA128_PUBLIC_LEN {
120 return Err(CoreError::InvalidKeyLength {
121 expected: SLHDSA128_PUBLIC_LEN,
122 got: raw.len(),
123 });
124 }
125 let mut buf = Vec::with_capacity(2 + raw.len());
126 buf.extend_from_slice(&SLHDSA128_PUB_PREFIX);
127 buf.extend_from_slice(raw);
128 Ok(format!("u{}", URL_SAFE_NO_PAD.encode(buf)))
129}
130
131fn decode_base64url(body: &str) -> Result<DecodedKey> {
134 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
135 if body.len() != SLHDSA128_MULTIKEY_BODY_LEN {
136 return Err(CoreError::InvalidMultikey(
137 "a base64url Multikey must be an SLH-DSA-SHA2-128s public key".into(),
138 ));
139 }
140 let decoded = URL_SAFE_NO_PAD
143 .decode(body)
144 .map_err(|e| CoreError::InvalidMultikey(format!("bad base64url: {e}")))?;
145 let prefix = [decoded[0], decoded[1]];
146 match prefix {
147 SLHDSA128_PUB_PREFIX => Ok(DecodedKey {
148 algorithm: SLHDSA128.to_string(),
149 raw_key: decoded[2..].to_vec(),
150 }),
151 SLHDSA128_PRIV_PREFIX => Err(CoreError::InvalidMultikey(
152 "a private-key codec is not a public key".into(),
153 )),
154 _ => Err(CoreError::InvalidMultikey(
155 "a base64url Multikey must be an SLH-DSA-SHA2-128s public key".into(),
156 )),
157 }
158}
159
160pub fn decode(multikey: &str) -> Result<DecodedKey> {
162 if let Some(body) = multikey.strip_prefix('u') {
163 return decode_base64url(body);
164 }
165 let body = multikey.strip_prefix('z').ok_or_else(|| {
166 CoreError::InvalidMultikey(
167 "must use base58btc encoding (z-prefix), or base64url (u-prefix) for SLH-DSA".into(),
168 )
169 })?;
170 let decoded = decode_base58_bounded(body)?;
171 if decoded.len() < 2 {
172 return Err(CoreError::InvalidMultikey("too short".into()));
173 }
174 let prefix = [decoded[0], decoded[1]];
175 let (algorithm, expected_len) = match prefix {
178 ED25519_PUB_PREFIX => ("Ed25519", ED25519_PUBLIC_LEN),
179 MLDSA44_PUB_PREFIX => ("ML-DSA-44", MLDSA44_PUBLIC_LEN),
180 ED25519_PRIV_PREFIX | MLDSA44_PRIV_PREFIX | SLHDSA128_PRIV_PREFIX => {
181 return Err(CoreError::InvalidMultikey(
182 "a private-key codec is not a public key".into(),
183 ))
184 }
185 SLHDSA128_PUB_PREFIX => {
186 return Err(CoreError::InvalidMultikey(
187 "an SLH-DSA-SHA2-128s Multikey is base64url (u-prefix)".into(),
188 ))
189 }
190 _ => {
191 return Err(CoreError::UnknownMulticodec(format!(
192 "{:02x}{:02x}",
193 prefix[0], prefix[1]
194 )))
195 }
196 };
197 let raw_key = &decoded[2..];
198 if raw_key.len() != expected_len {
199 return Err(CoreError::InvalidKeyLength {
200 expected: expected_len,
201 got: raw_key.len(),
202 });
203 }
204 if algorithm == "Ed25519" {
205 crate::keys::strict_verifying_key(raw_key)?;
207 }
208 Ok(DecodedKey {
209 algorithm: algorithm.to_string(),
210 raw_key: raw_key.to_vec(),
211 })
212}
213
214pub fn algorithm_of(multikey: &str) -> Result<String> {
216 Ok(decode(multikey)?.algorithm)
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222
223 #[test]
224 fn ed25519_roundtrip() {
225 let raw = crate::keys::Ed25519KeyPair::from_seed(&[7u8; 32]).public_key();
226 let mk = encode_ed25519_public(&raw).unwrap();
227 assert!(mk.starts_with("z6Mk"));
228 let decoded = decode(&mk).unwrap();
229 assert_eq!(decoded.algorithm, "Ed25519");
230 assert_eq!(decoded.raw_key, raw);
231 }
232
233 #[test]
234 fn varint_prefixes_match_the_multicodec_codes() {
235 for (prefix, code) in [
238 (ED25519_PUB_PREFIX, ED25519_PUB_CODEC),
239 (ED25519_PRIV_PREFIX, ED25519_PRIV_CODEC),
240 (MLDSA44_PUB_PREFIX, MLDSA44_PUB_CODEC),
241 (MLDSA44_PRIV_PREFIX, MLDSA44_PRIV_CODEC),
242 (SLHDSA128_PUB_PREFIX, SLHDSA128_PUB_CODEC),
243 (SLHDSA128_PRIV_PREFIX, SLHDSA128_PRIV_CODEC),
244 ] {
245 assert!(prefix[0] & 0x80 != 0 && prefix[1] & 0x80 == 0);
246 let back = u16::from(prefix[0] & 0x7f) | (u16::from(prefix[1]) << 7);
247 assert_eq!(back, code);
248 }
249 }
250
251 fn with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
252 encode_with_prefix(prefix, raw)
253 }
254
255 #[test]
256 fn private_key_codecs_never_decode_as_keys() {
257 let ed = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
258 assert!(decode(&with_prefix(ED25519_PRIV_PREFIX, &ed.seed())).is_err());
259 assert!(decode(&with_prefix(MLDSA44_PRIV_PREFIX, &[0u8; 2560])).is_err());
260 assert!(decode(&with_prefix(varint2(0x1207), &[0u8; MLDSA44_PUBLIC_LEN])).is_err());
263 assert!(decode(&with_prefix(varint2(0x1208), &[0u8; 2560])).is_err());
264 }
265
266 #[test]
267 fn exact_key_lengths() {
268 let ed = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]).public_key();
269 let mut long = ed.to_vec();
270 long.push(0);
271 assert!(decode(&with_prefix(ED25519_PUB_PREFIX, &long)).is_err());
272 assert!(decode(&with_prefix(ED25519_PUB_PREFIX, &ed[..31])).is_err());
273 assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; 1311])).is_err());
274 assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; 1313])).is_err());
275 assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; MLDSA44_PUBLIC_LEN])).is_ok());
276 }
277
278 #[test]
279 fn weak_ed25519_keys_refused_at_decode() {
280 for hex in crate::keys::tests::SMALL_ORDER_ENCODINGS
281 .iter()
282 .chain(crate::keys::tests::NON_CANONICAL_ENCODINGS.iter())
283 {
284 let raw = crate::keys::tests::unhex32(hex);
285 let mk = with_prefix(ED25519_PUB_PREFIX, &raw);
286 assert!(decode(&mk).is_err(), "{hex} must be refused");
287 assert!(crate::keys::did_key_to_ed25519(&format!("did:key:{mk}")).is_err());
288 }
289 }
290
291 #[test]
292 fn slhdsa128_keys_have_one_spelling() {
293 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
294 assert_eq!(SLHDSA128_PUB_PREFIX, [0xa0, 0x24]);
297 assert_eq!(SLHDSA128_PRIV_PREFIX, [0x9d, 0x26]);
298 let raw = [7u8; 32];
299 let mk = encode_slhdsa128_public(&raw).unwrap();
300 assert!(mk.starts_with('u') && mk.len() == 47);
301 let decoded = decode(&mk).unwrap();
302 assert_eq!(decoded.algorithm, SLHDSA128);
303 assert_eq!(decoded.raw_key, raw);
304 assert!(encode_slhdsa128_public(&raw[..31]).is_err());
305 let u = |prefix: [u8; 2], raw: &[u8]| {
306 let mut buf = prefix.to_vec();
307 buf.extend_from_slice(raw);
308 format!("u{}", URL_SAFE_NO_PAD.encode(buf))
309 };
310 assert!(decode(&with_prefix(SLHDSA128_PUB_PREFIX, &raw)).is_err());
314 assert!(decode(&u(SLHDSA128_PRIV_PREFIX, &raw)).is_err());
315 assert!(decode(&u(SLHDSA128_PRIV_PREFIX, &[0u8; 64])).is_err());
316 assert!(decode(&u(ED25519_PUB_PREFIX, &raw)).is_err());
317 assert!(decode(&u(SLHDSA128_PUB_PREFIX, &raw[..31])).is_err());
318 assert!(decode(&u(SLHDSA128_PUB_PREFIX, &[0u8; 33])).is_err());
319 assert!(decode(&format!("{mk}=")).is_err());
320 let mut bits = mk.clone().into_bytes();
321 let last = bits.len() - 1;
322 bits[last] = if bits[last] == b'A' { b'B' } else { b'A' };
323 let changed = String::from_utf8(bits).unwrap();
324 assert!(decode(&changed).map(|d| d.raw_key != raw).unwrap_or(true));
325 }
326
327 #[test]
328 fn rejects_wrong_length() {
329 assert!(encode_ed25519_public(&[0u8; 31]).is_err());
330 }
331
332 #[test]
333 fn rejects_non_z_prefix() {
334 assert!(decode("Qabc").is_err());
335 }
336
337 #[test]
338 fn rejects_overlong_base58() {
339 let overlong = "1".repeat(MAX_BASE58_LEN + 1);
341 assert!(decode_base58_bounded(&overlong).is_err());
342 assert!(decode(&format!("z{overlong}")).is_err());
343 }
344}