Skip to main content

xdid_method_key/keys/
mod.rs

1use jose_jwk::Jwk;
2use multibase::Base;
3use xdid_core::did::{Did, MethodId, MethodName};
4use zeroize::Zeroizing;
5
6use crate::NAME;
7
8#[cfg(feature = "p256")]
9pub mod p256;
10#[cfg(feature = "p384")]
11pub mod p384;
12
13pub trait Signer {
14    /// Sign a message with the private key.
15    ///
16    /// # Errors
17    ///
18    /// Returns an error if signing fails.
19    fn sign(&self, message: &[u8]) -> anyhow::Result<Vec<u8>>;
20}
21
22pub trait DidKeyPair: Signer + Sized {
23    /// Generate a new pair of keys.
24    fn generate() -> Self;
25
26    fn public(&self) -> impl PublicKey;
27
28    /// Export the key pair as a PKCS#8 PEM string.
29    ///
30    /// # Errors
31    ///
32    /// Returns an error if encoding fails.
33    fn to_pkcs8_pem(&self) -> anyhow::Result<Zeroizing<String>>;
34
35    /// Import a key pair from a PKCS#8 PEM string.
36    ///
37    /// # Errors
38    ///
39    /// Returns an error if the PEM is invalid or cannot be decoded.
40    fn from_pkcs8_pem(pem: &str) -> anyhow::Result<Self>;
41}
42
43pub trait PublicKey: WithMulticodec {
44    fn to_sec1_bytes(&self) -> Box<[u8]>;
45    fn to_encoded_point_bytes(&self) -> Box<[u8]>;
46    fn to_jwk(&self) -> Jwk;
47
48    fn to_did(&self) -> Did {
49        let bytes = self.to_encoded_point_bytes();
50        let code = self.codec().code();
51
52        let mut inner = Vec::with_capacity(code.len() + bytes.len());
53        inner.extend(code);
54        inner.extend(bytes);
55
56        let id = multibase::encode(Base::Base58Btc, inner);
57
58        Did {
59            method_name: MethodName(NAME.into()),
60            method_id: MethodId(id),
61        }
62    }
63}
64
65pub trait Multicodec {
66    fn code_u64(&self) -> u64;
67    fn code(&self) -> Vec<u8> {
68        let mut buffer = unsigned_varint::encode::u64_buffer();
69        unsigned_varint::encode::u64(self.code_u64(), &mut buffer).to_vec()
70    }
71}
72
73pub trait WithMulticodec {
74    fn codec(&self) -> Box<dyn Multicodec>;
75}
76
77pub trait KeyParser: WithMulticodec {
78    /// Parse a public key from raw bytes.
79    ///
80    /// # Errors
81    ///
82    /// Returns an error if the bytes do not represent a valid public key.
83    fn parse(&self, public_key: Vec<u8>) -> Result<Box<dyn PublicKey>, crate::parser::ParseError>;
84}