1use crate::error::{CoreError, Result};
17
18pub const ED25519_PUB_CODEC: u16 = 0xed;
20pub const ED25519_PRIV_CODEC: u16 = 0x1300;
21pub const MLDSA44_PUB_CODEC: u16 = 0x1210;
22pub const MLDSA44_PRIV_CODEC: u16 = 0x1317;
23
24const fn varint2(code: u16) -> [u8; 2] {
27 [((code & 0x7f) as u8) | 0x80, (code >> 7) as u8]
28}
29
30pub const ED25519_PUB_PREFIX: [u8; 2] = varint2(ED25519_PUB_CODEC);
32pub const ED25519_PRIV_PREFIX: [u8; 2] = varint2(ED25519_PRIV_CODEC);
33pub const MLDSA44_PUB_PREFIX: [u8; 2] = varint2(MLDSA44_PUB_CODEC);
34pub const MLDSA44_PRIV_PREFIX: [u8; 2] = varint2(MLDSA44_PRIV_CODEC);
35
36const ED25519_PUBLIC_LEN: usize = 32;
37const MLDSA44_PUBLIC_LEN: usize = 1312;
38
39pub const MAX_BASE58_LEN: usize = 8192;
44
45pub fn decode_base58_bounded(s: &str) -> Result<Vec<u8>> {
49 if s.len() > MAX_BASE58_LEN {
50 return Err(CoreError::InvalidMultikey(format!(
51 "base58 input too long: {} > {MAX_BASE58_LEN}",
52 s.len()
53 )));
54 }
55 bs58::decode(s)
56 .into_vec()
57 .map_err(|e| CoreError::InvalidMultikey(format!("bad base58: {e}")))
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct DecodedKey {
63 pub algorithm: String,
64 pub raw_key: Vec<u8>,
65}
66
67fn encode_with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
68 let mut buf = Vec::with_capacity(2 + raw.len());
69 buf.extend_from_slice(&prefix);
70 buf.extend_from_slice(raw);
71 format!("z{}", bs58::encode(buf).into_string())
72}
73
74pub fn encode_ed25519_public(raw: &[u8]) -> Result<String> {
76 if raw.len() != ED25519_PUBLIC_LEN {
77 return Err(CoreError::InvalidKeyLength {
78 expected: ED25519_PUBLIC_LEN,
79 got: raw.len(),
80 });
81 }
82 Ok(encode_with_prefix(ED25519_PUB_PREFIX, raw))
83}
84
85pub fn encode_mldsa44_public(raw: &[u8]) -> Result<String> {
87 if raw.len() != MLDSA44_PUBLIC_LEN {
88 return Err(CoreError::InvalidKeyLength {
89 expected: MLDSA44_PUBLIC_LEN,
90 got: raw.len(),
91 });
92 }
93 Ok(encode_with_prefix(MLDSA44_PUB_PREFIX, raw))
94}
95
96pub fn decode(multikey: &str) -> Result<DecodedKey> {
98 let body = multikey.strip_prefix('z').ok_or_else(|| {
99 CoreError::InvalidMultikey("must use base58btc encoding (z-prefix)".into())
100 })?;
101 let decoded = decode_base58_bounded(body)?;
102 if decoded.len() < 2 {
103 return Err(CoreError::InvalidMultikey("too short".into()));
104 }
105 let prefix = [decoded[0], decoded[1]];
106 let (algorithm, expected_len) = match prefix {
109 ED25519_PUB_PREFIX => ("Ed25519", ED25519_PUBLIC_LEN),
110 MLDSA44_PUB_PREFIX => ("ML-DSA-44", MLDSA44_PUBLIC_LEN),
111 ED25519_PRIV_PREFIX | MLDSA44_PRIV_PREFIX => {
112 return Err(CoreError::InvalidMultikey(
113 "a private-key codec is not a public key".into(),
114 ))
115 }
116 _ => {
117 return Err(CoreError::UnknownMulticodec(format!(
118 "{:02x}{:02x}",
119 prefix[0], prefix[1]
120 )))
121 }
122 };
123 let raw_key = &decoded[2..];
124 if raw_key.len() != expected_len {
125 return Err(CoreError::InvalidKeyLength {
126 expected: expected_len,
127 got: raw_key.len(),
128 });
129 }
130 if algorithm == "Ed25519" {
131 crate::keys::strict_verifying_key(raw_key)?;
133 }
134 Ok(DecodedKey {
135 algorithm: algorithm.to_string(),
136 raw_key: raw_key.to_vec(),
137 })
138}
139
140pub fn algorithm_of(multikey: &str) -> Result<String> {
142 Ok(decode(multikey)?.algorithm)
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148
149 #[test]
150 fn ed25519_roundtrip() {
151 let raw = crate::keys::Ed25519KeyPair::from_seed(&[7u8; 32]).public_key();
152 let mk = encode_ed25519_public(&raw).unwrap();
153 assert!(mk.starts_with("z6Mk"));
154 let decoded = decode(&mk).unwrap();
155 assert_eq!(decoded.algorithm, "Ed25519");
156 assert_eq!(decoded.raw_key, raw);
157 }
158
159 #[test]
160 fn varint_prefixes_match_the_multicodec_codes() {
161 for (prefix, code) in [
164 (ED25519_PUB_PREFIX, ED25519_PUB_CODEC),
165 (ED25519_PRIV_PREFIX, ED25519_PRIV_CODEC),
166 (MLDSA44_PUB_PREFIX, MLDSA44_PUB_CODEC),
167 (MLDSA44_PRIV_PREFIX, MLDSA44_PRIV_CODEC),
168 ] {
169 assert!(prefix[0] & 0x80 != 0 && prefix[1] & 0x80 == 0);
170 let back = u16::from(prefix[0] & 0x7f) | (u16::from(prefix[1]) << 7);
171 assert_eq!(back, code);
172 }
173 }
174
175 fn with_prefix(prefix: [u8; 2], raw: &[u8]) -> String {
176 encode_with_prefix(prefix, raw)
177 }
178
179 #[test]
180 fn private_key_codecs_never_decode_as_keys() {
181 let ed = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
182 assert!(decode(&with_prefix(ED25519_PRIV_PREFIX, &ed.seed())).is_err());
183 assert!(decode(&with_prefix(MLDSA44_PRIV_PREFIX, &[0u8; 2560])).is_err());
184 assert!(decode(&with_prefix(varint2(0x1207), &[0u8; MLDSA44_PUBLIC_LEN])).is_err());
187 assert!(decode(&with_prefix(varint2(0x1208), &[0u8; 2560])).is_err());
188 }
189
190 #[test]
191 fn exact_key_lengths() {
192 let ed = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]).public_key();
193 let mut long = ed.to_vec();
194 long.push(0);
195 assert!(decode(&with_prefix(ED25519_PUB_PREFIX, &long)).is_err());
196 assert!(decode(&with_prefix(ED25519_PUB_PREFIX, &ed[..31])).is_err());
197 assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; 1311])).is_err());
198 assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; 1313])).is_err());
199 assert!(decode(&with_prefix(MLDSA44_PUB_PREFIX, &[0u8; MLDSA44_PUBLIC_LEN])).is_ok());
200 }
201
202 #[test]
203 fn weak_ed25519_keys_refused_at_decode() {
204 for hex in crate::keys::tests::SMALL_ORDER_ENCODINGS
205 .iter()
206 .chain(crate::keys::tests::NON_CANONICAL_ENCODINGS.iter())
207 {
208 let raw = crate::keys::tests::unhex32(hex);
209 let mk = with_prefix(ED25519_PUB_PREFIX, &raw);
210 assert!(decode(&mk).is_err(), "{hex} must be refused");
211 assert!(crate::keys::did_key_to_ed25519(&format!("did:key:{mk}")).is_err());
212 }
213 }
214
215 #[test]
216 fn rejects_wrong_length() {
217 assert!(encode_ed25519_public(&[0u8; 31]).is_err());
218 }
219
220 #[test]
221 fn rejects_non_z_prefix() {
222 assert!(decode("Qabc").is_err());
223 }
224
225 #[test]
226 fn rejects_overlong_base58() {
227 let overlong = "1".repeat(MAX_BASE58_LEN + 1);
229 assert!(decode_base58_bounded(&overlong).is_err());
230 assert!(decode(&format!("z{overlong}")).is_err());
231 }
232}