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
23#[allow(unused_imports)]
24use crate::prelude::*;
25
26use crate::error::{CoreError, Result};
27
28/// Multicodec table codes.
29pub 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
36/// The unsigned-varint encoding of a multicodec code in 0x80..0x3fff (two
37/// bytes: the low 7 bits with the continuation bit set, then the rest).
38const fn varint2(code: u16) -> [u8; 2] {
39    [((code & 0x7f) as u8) | 0x80, (code >> 7) as u8]
40}
41
42/// Multicodec 2-byte varint prefixes.
43pub 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
50/// The algorithm name of an SLH-DSA-SHA2-128s key, as [`decode`] reports it.
51pub 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;
56/// The exact length of an SLH-DSA-SHA2-128s Multikey after its 'u': 34 bytes
57/// (2-byte prefix, 32-byte key) in base64url without padding.
58const SLHDSA128_MULTIKEY_BODY_LEN: usize = 46;
59
60/// Maximum base58btc input length accepted by [`decode_base58_bounded`]. base58
61/// decoding is O(n^2), so an unbounded input is a denial-of-service vector. The
62/// largest legitimate value is a hybrid composite proofValue (about 3400 chars);
63/// 8192 is a safe ceiling well above every real key, signature, and proofValue.
64pub const MAX_BASE58_LEN: usize = 8192;
65
66/// Decode base58btc with a length cap to bound the O(n^2) decode cost. Use this
67/// for any externally-supplied base58 (proofValues, multikeys) instead of
68/// calling `bs58::decode` directly.
69pub 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/// A multikey decoded into its algorithm name and raw key bytes.
82#[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
95/// Encode a 32-byte Ed25519 public key as a Multikey string (z-prefixed base58btc).
96pub 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
106/// Encode a 1312-byte ML-DSA-44 public key as a Multikey string (hybrid PQ profile).
107pub 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
117/// Encode a 32-byte SLH-DSA-SHA2-128s public key as a Multikey string
118/// (u-prefixed base64url without padding, as the W3C Quantum-Resistant
119/// Cryptosuites draft writes it).
120pub 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
134/// Decode a u-prefixed (base64url, no padding) Multikey body: only an
135/// SLH-DSA-SHA2-128s public key has this spelling.
136fn 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    // URL_SAFE_NO_PAD refuses padding and non-canonical trailing bits, so a
144    // key has one spelling.
145    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
163/// Decode a Multikey string into algorithm name plus raw key bytes.
164pub 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    // Only public-key codecs decode as keys: a private-key codec in a DID or a
179    // verification method is refused, never read as if it were a public key.
180    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        // Refuse non-canonical and small-order (weak) keys at decode time.
209        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
217/// Return the algorithm name encoded in a Multikey without exposing raw bytes.
218pub 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        // Decode each prefix back as an unsigned varint and compare with the
239        // table code, so the constants cannot drift from the codes.
240        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        // The codes that were used before the multicodec table assigned
264        // mldsa-44-pub (0x1207 public, 0x1208 private) are no longer read.
265        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        // The two prefix bytes are the ones the Quantum-Resistant
298        // Cryptosuites draft tabulates for SLH-DSA-SHA2-128s.
299        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        // The same key under base58btc, a private-key codec, another
314        // algorithm under base64url, a wrong length, padding, and a changed
315        // trailing bit are all refused.
316        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        // Guards the O(n^2) base58 decode DoS.
343        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}