1#![allow(clippy::disallowed_methods)]
8
9const ED25519_MULTICODEC: [u8; 2] = [0xED, 0x01];
11
12const P256_MULTICODEC: [u8; 2] = [0x80, 0x24];
14
15#[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
51pub fn ed25519_pubkey_to_did_keri(pk: &[u8]) -> String {
56 format!("did:keri:{}", bs58::encode(pk).into_string())
57}
58
59pub 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#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum DecodedDidKey {
88 Ed25519([u8; 32]),
90 P256(Vec<u8>),
92}
93
94impl DecodedDidKey {
95 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 pub fn bytes(&self) -> &[u8] {
105 match self {
106 Self::Ed25519(b) => b,
107 Self::P256(b) => b,
108 }
109 }
110}
111
112pub 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}