xdid_method_key/keys/
mod.rs

1use ::p256::elliptic_curve::zeroize::Zeroizing;
2use jose_jwk::Jwk;
3use multibase::Base;
4use thiserror::Error;
5use xdid_core::did::{Did, MethodId, MethodName};
6
7use crate::NAME;
8
9#[cfg(feature = "p256")]
10pub mod p256;
11#[cfg(feature = "p384")]
12pub mod p384;
13
14pub trait Signer {
15    fn sign(&self, message: &[u8]) -> Result<Vec<u8>, SignError>;
16}
17
18pub trait DidKeyPair: Signer + Sized {
19    /// Generate a new pair of keys.
20    fn generate() -> Self;
21
22    fn public(&self) -> impl PublicKey;
23
24    fn to_pkcs8_pem(&self) -> anyhow::Result<Zeroizing<String>>;
25    fn from_pkcs8_pem(pem: &str) -> anyhow::Result<Self>;
26}
27
28#[derive(Error, Debug)]
29pub enum SignError {
30    #[error("signing failed")]
31    SigningFailed,
32}
33
34pub trait PublicKey: WithMulticodec {
35    fn to_sec1_bytes(&self) -> Box<[u8]>;
36    fn to_encoded_point_bytes(&self) -> Box<[u8]>;
37    fn to_jwk(&self) -> Jwk;
38
39    fn to_did(&self) -> Did {
40        let bytes = self.to_encoded_point_bytes();
41        let code = self.codec().code();
42
43        let mut inner = Vec::with_capacity(code.len() + bytes.len());
44        inner.extend(code);
45        inner.extend(bytes);
46
47        let id = multibase::encode(Base::Base58Btc, inner);
48
49        Did {
50            method_name: MethodName(NAME.to_string()),
51            method_id: MethodId(id),
52        }
53    }
54}
55
56pub trait Multicodec {
57    fn code_u64(&self) -> u64;
58    fn code(&self) -> Vec<u8> {
59        let mut buffer = unsigned_varint::encode::u64_buffer();
60        unsigned_varint::encode::u64(self.code_u64(), &mut buffer).to_vec()
61    }
62}
63
64pub trait WithMulticodec {
65    fn codec(&self) -> Box<dyn Multicodec>;
66}
67
68pub trait KeyParser: WithMulticodec {
69    fn parse(&self, public_key: Vec<u8>) -> Box<dyn PublicKey>;
70}