Skip to main content

auths_crypto/
did_key.rs

1//! DID:key encoding and decoding for Ed25519 and P-256 public keys.
2//!
3//! Centralizes all `did:key` ↔ public key byte conversions in one place.
4//! The `did:key` method encodes a public key directly in the DID string
5//! using multicodec + base58btc, per the [did:key spec](https://w3c-ccg.github.io/did-method-key/).
6// allow during curve-agnostic refactor
7#![allow(clippy::disallowed_methods)]
8
9/// Ed25519 multicodec prefix (varint-encoded `0xED`).
10const ED25519_MULTICODEC: [u8; 2] = [0xED, 0x01];
11
12/// P-256 (secp256r1) compressed multicodec prefix (varint-encoded `0x1200`).
13const P256_MULTICODEC: [u8; 2] = [0x80, 0x24];
14
15/// Errors from parsing or encoding `did:key` strings.
16#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum DidKeyError {
19    #[error("DID must start with 'did:key:z', got: {0}")]
20    InvalidPrefix(String),
21
22    #[error("Base58 decoding failed: {0}")]
23    Base58DecodeFailed(String),
24
25    #[error("Unsupported multicodec: expected Ed25519 [0xED, 0x01] or P-256 [0x80, 0x24]")]
26    UnsupportedMulticodec,
27
28    #[error("Invalid key length: got {0} bytes")]
29    InvalidKeyLength(usize),
30}
31
32impl crate::AuthsErrorInfo for DidKeyError {
33    fn error_code(&self) -> &'static str {
34        match self {
35            Self::InvalidPrefix(_) => "AUTHS-E1101",
36            Self::Base58DecodeFailed(_) => "AUTHS-E1102",
37            Self::UnsupportedMulticodec => "AUTHS-E1103",
38            Self::InvalidKeyLength(_) => "AUTHS-E1104",
39        }
40    }
41
42    fn suggestion(&self) -> Option<&'static str> {
43        match self {
44            Self::InvalidPrefix(_) => Some("DID must start with 'did:key:z'"),
45            Self::UnsupportedMulticodec => Some("Supported key types: Ed25519, P-256 (secp256r1)"),
46            _ => None,
47        }
48    }
49}
50
51/// Encode a raw public key as a `did:keri:` string (base58-encoded).
52///
53/// Args:
54/// * `pk`: Raw public key bytes.
55pub fn ed25519_pubkey_to_did_keri(pk: &[u8]) -> String {
56    format!("did:keri:{}", bs58::encode(pk).into_string())
57}
58
59/// Decode a `did:key:z...` string to a 33-byte compressed P-256 public key.
60///
61/// Args:
62/// * `did`: A DID string in `did:key:z<base58btc>` format with P-256 multicodec.
63///
64/// Usage:
65/// ```ignore
66/// let pk: Vec<u8> = did_key_to_p256("did:key:zDn...")?;
67/// assert_eq!(pk.len(), 33);
68/// ```
69pub fn did_key_to_p256(did: &str) -> Result<Vec<u8>, DidKeyError> {
70    let encoded = strip_did_key_prefix(did)?;
71    let decoded = decode_base58(encoded)?;
72    if decoded.len() < 2 {
73        return Err(DidKeyError::InvalidKeyLength(decoded.len()));
74    }
75    if decoded[0] != P256_MULTICODEC[0] || decoded[1] != P256_MULTICODEC[1] {
76        return Err(DidKeyError::UnsupportedMulticodec);
77    }
78    let key = decoded[2..].to_vec();
79    if key.len() != 33 {
80        return Err(DidKeyError::InvalidKeyLength(key.len()));
81    }
82    Ok(key)
83}
84
85/// Decoded public key from a `did:key` string, with curve identification.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum DecodedDidKey {
88    /// Ed25519 public key (32 bytes).
89    Ed25519([u8; 32]),
90    /// P-256 compressed public key (33 bytes).
91    P256(Vec<u8>),
92}
93
94impl DecodedDidKey {
95    /// Returns the curve of the decoded key.
96    pub fn curve(&self) -> crate::CurveType {
97        match self {
98            Self::Ed25519(_) => crate::CurveType::Ed25519,
99            Self::P256(_) => crate::CurveType::P256,
100        }
101    }
102
103    /// Returns the raw public key bytes.
104    pub fn bytes(&self) -> &[u8] {
105        match self {
106            Self::Ed25519(b) => b,
107            Self::P256(b) => b,
108        }
109    }
110}
111
112/// Decode a `did:key:z...` string, auto-detecting the curve from the multicodec.
113///
114/// Usage:
115/// ```ignore
116/// match did_key_decode("did:key:z...")? {
117///     DecodedDidKey::Ed25519(pk) => { /* 32 bytes */ }
118///     DecodedDidKey::P256(pk) => { /* 33 bytes */ }
119/// }
120/// ```
121pub fn did_key_decode(did: &str) -> Result<DecodedDidKey, DidKeyError> {
122    let encoded = strip_did_key_prefix(did)?;
123    let decoded = decode_base58(encoded)?;
124    if decoded.len() < 2 {
125        return Err(DidKeyError::InvalidKeyLength(decoded.len()));
126    }
127    if decoded[0] == ED25519_MULTICODEC[0] && decoded[1] == ED25519_MULTICODEC[1] {
128        let key = validate_multicodec_and_extract(&decoded)?;
129        Ok(DecodedDidKey::Ed25519(key))
130    } else if decoded[0] == P256_MULTICODEC[0] && decoded[1] == P256_MULTICODEC[1] {
131        let key = decoded[2..].to_vec();
132        if key.len() != 33 {
133            return Err(DidKeyError::InvalidKeyLength(key.len()));
134        }
135        Ok(DecodedDidKey::P256(key))
136    } else {
137        Err(DidKeyError::UnsupportedMulticodec)
138    }
139}
140
141fn strip_did_key_prefix(did: &str) -> Result<&str, DidKeyError> {
142    did.strip_prefix("did:key:z")
143        .ok_or_else(|| DidKeyError::InvalidPrefix(did.to_string()))
144}
145
146fn decode_base58(encoded: &str) -> Result<Vec<u8>, DidKeyError> {
147    bs58::decode(encoded)
148        .into_vec()
149        .map_err(|e| DidKeyError::Base58DecodeFailed(e.to_string()))
150}
151
152fn validate_multicodec_and_extract(decoded: &[u8]) -> Result<[u8; 32], DidKeyError> {
153    if decoded.len() != 34
154        || decoded[0] != ED25519_MULTICODEC[0]
155        || decoded[1] != ED25519_MULTICODEC[1]
156    {
157        if decoded.len() != 34 {
158            return Err(DidKeyError::InvalidKeyLength(
159                decoded.len().saturating_sub(2),
160            ));
161        }
162        return Err(DidKeyError::UnsupportedMulticodec);
163    }
164
165    let mut key = [0u8; 32];
166    key.copy_from_slice(&decoded[2..]);
167    Ok(key)
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn rejects_invalid_prefix() {
176        let err = did_key_decode("did:web:example.com").unwrap_err();
177        assert!(matches!(err, DidKeyError::InvalidPrefix(_)));
178    }
179
180    #[test]
181    fn rejects_invalid_base58() {
182        let err = did_key_decode("did:key:z0OOO").unwrap_err();
183        assert!(matches!(err, DidKeyError::Base58DecodeFailed(_)));
184    }
185}