xdid_method_key/keys/
mod.rs

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