Skip to main content

vouch_core/
multikey.rs

1//! Multikey encoding for verification methods.
2//!
3//! Byte-exact port of the TypeScript SDK `multikey.ts` and `vouch/multikey.py`.
4//! A public key is encoded as `publicKeyMultibase = base58btc(multicodec_prefix
5//! || raw_public_key_bytes)`, with a leading 'z' marking base58btc. Cross-
6//! implementation interop with the other SDKs is REQUIRED.
7//!
8//! Supported algorithms (multicodec table codes; the prefix on the wire is the
9//! code as an unsigned varint):
10//!   Ed25519            ed25519-pub        0xed    (32-byte public key)
11//!   ML-DSA-44          mldsa-44-pub       0x1210  (1312-byte public key)
12//!   SLH-DSA-SHA2-128s  slhdsa-sha2-128s-pub 0x1220  (32-byte public key)
13//!
14//! An SLH-DSA-SHA2-128s key is written the way the W3C Quantum-Resistant
15//! Cryptosuites draft writes it: base64url without padding, with a leading
16//! 'u'. Each algorithm has exactly one spelling: an Ed25519 or ML-DSA-44 key
17//! under 'u', or an SLH-DSA key under 'z', is refused.
18//!
19//! Only public-key codes decode as keys. The private-key codes (ed25519-priv
20//! 0x1300, mldsa-44-priv 0x1317, slhdsa-sha2-128s-priv 0x131d) are recognised
21//! only so they can be refused.
22
23use crate::error::{CoreError, Result};
24
25/// Multicodec table codes.
26pub 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
33/// The unsigned-varint encoding of a multicodec code in 0x80..0x3fff (two
34/// bytes: the low 7 bits with the continuation bit set, then the rest).
35const fn varint2(code: u16) -> [u8; 2] {
36    [((code & 0x7f) as u8) | 0x80, (code >> 7) as u8]
37}
38
39/// Multicodec 2-byte varint prefixes.
40pub 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
47/// The algorithm name of an SLH-DSA-SHA2-128s key, as [`decode`] reports it.
48pub 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;
53/// The exact length of an SLH-DSA-SHA2-128s Multikey after its 'u': 34 bytes
54/// (2-byte prefix, 32-byte key) in base64url without padding.
55const SLHDSA128_MULTIKEY_BODY_LEN: usize = 46;
56
57/// Maximum base58btc input length accepted by [`decode_base58_bounded`]. base58
58/// decoding is O(n^2), so an unbounded input is a denial-of-service vector. The
59/// largest legitimate value is a hybrid composite proofValue (about 3400 chars);
60/// 8192 is a safe ceiling well above every real key, signature, and proofValue.
61pub const MAX_BASE58_LEN: usize = 8192;
62
63/// Decode base58btc with a length cap to bound the O(n^2) decode cost. Use this
64/// for any externally-supplied base58 (proofValues, multikeys) instead of
65/// calling `bs58::decode` directly.
66pub 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/// A multikey decoded into its algorithm name and raw key bytes.
79#[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
92/// Encode a 32-byte Ed25519 public key as a Multikey string (z-prefixed base58btc).
93pub 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
103/// Encode a 1312-byte ML-DSA-44 public key as a Multikey string (hybrid PQ profile).
104pub 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
114/// Encode a 32-byte SLH-DSA-SHA2-128s public key as a Multikey string
115/// (u-prefixed base64url without padding, as the W3C Quantum-Resistant
116/// Cryptosuites draft writes it).
117pub 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
131/// Decode a u-prefixed (base64url, no padding) Multikey body: only an
132/// SLH-DSA-SHA2-128s public key has this spelling.
133fn 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    // URL_SAFE_NO_PAD refuses padding and non-canonical trailing bits, so a
141    // key has one spelling.
142    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
160/// Decode a Multikey string into algorithm name plus raw key bytes.
161pub 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    // Only public-key codecs decode as keys: a private-key codec in a DID or a
176    // verification method is refused, never read as if it were a public key.
177    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        // Refuse non-canonical and small-order (weak) keys at decode time.
206        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
214/// Return the algorithm name encoded in a Multikey without exposing raw bytes.
215pub 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        // Decode each prefix back as an unsigned varint and compare with the
236        // table code, so the constants cannot drift from the codes.
237        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        // The codes that were used before the multicodec table assigned
261        // mldsa-44-pub (0x1207 public, 0x1208 private) are no longer read.
262        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        // The two prefix bytes are the ones the Quantum-Resistant
295        // Cryptosuites draft tabulates for SLH-DSA-SHA2-128s.
296        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        // The same key under base58btc, a private-key codec, another
311        // algorithm under base64url, a wrong length, padding, and a changed
312        // trailing bit are all refused.
313        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        // Guards the O(n^2) base58 decode DoS.
340        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}