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