xdid_method_key/keys/
p384.rs

1use jose_jwk::Jwk;
2use p256::{
3    elliptic_curve::{rand_core::OsRng, zeroize::Zeroizing},
4    pkcs8::{DecodePrivateKey, LineEnding},
5};
6use p384::{
7    SecretKey,
8    elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint},
9    pkcs8::EncodePrivateKey,
10};
11use ring::{
12    rand::SystemRandom,
13    signature::{ECDSA_P384_SHA384_ASN1_SIGNING, EcdsaKeyPair},
14};
15
16use super::{DidKeyPair, KeyParser, Multicodec, PublicKey, SignError, Signer, WithMulticodec};
17
18#[derive(Clone, PartialEq, Eq)]
19pub struct P384KeyPair(SecretKey);
20
21impl DidKeyPair for P384KeyPair {
22    fn generate() -> Self {
23        let mut rng = OsRng;
24        let secret = SecretKey::random(&mut rng);
25        Self(secret)
26    }
27
28    fn public(&self) -> impl PublicKey {
29        P384PublicKey(self.0.public_key())
30    }
31
32    fn to_pkcs8_pem(&self) -> anyhow::Result<Zeroizing<String>> {
33        let pem = self.0.to_pkcs8_pem(LineEnding::LF)?;
34        Ok(pem)
35    }
36    fn from_pkcs8_pem(pem: &str) -> anyhow::Result<Self> {
37        let key = SecretKey::from_pkcs8_pem(pem)?;
38        Ok(Self(key))
39    }
40}
41
42impl Signer for P384KeyPair {
43    fn sign(&self, message: &[u8]) -> Result<Vec<u8>, SignError> {
44        let rng = SystemRandom::new();
45
46        let signer = EcdsaKeyPair::from_private_key_and_public_key(
47            &ECDSA_P384_SHA384_ASN1_SIGNING,
48            &self.0.to_bytes(),
49            &self.0.public_key().to_sec1_bytes(),
50            &rng,
51        )
52        .unwrap();
53
54        signer
55            .sign(&rng, message)
56            .map(|v| v.as_ref().to_vec())
57            .map_err(|_| SignError::SigningFailed)
58    }
59}
60
61#[derive(Clone, PartialEq, Eq)]
62struct P384PublicKey(p384::PublicKey);
63
64impl PublicKey for P384PublicKey {
65    fn to_sec1_bytes(&self) -> Box<[u8]> {
66        self.0.to_sec1_bytes()
67    }
68    fn to_encoded_point_bytes(&self) -> Box<[u8]> {
69        self.0.to_encoded_point(true).as_bytes().into()
70    }
71
72    fn to_jwk(&self) -> Jwk {
73        let jwk_str = self.0.to_jwk_string();
74        serde_json::from_str(&jwk_str).unwrap()
75    }
76}
77
78impl WithMulticodec for P384PublicKey {
79    fn codec(&self) -> Box<dyn Multicodec> {
80        Box::new(P384Codec)
81    }
82}
83
84pub(crate) struct P384KeyParser;
85
86impl KeyParser for P384KeyParser {
87    fn parse(&self, public_key: Vec<u8>) -> Box<dyn PublicKey> {
88        let point = p384::EncodedPoint::from_bytes(public_key).unwrap();
89        let key = p384::PublicKey::from_encoded_point(&point).unwrap();
90        Box::new(P384PublicKey(key))
91    }
92}
93
94impl WithMulticodec for P384KeyParser {
95    fn codec(&self) -> Box<dyn Multicodec> {
96        Box::new(P384Codec)
97    }
98}
99
100struct P384Codec;
101
102impl Multicodec for P384Codec {
103    fn code_u64(&self) -> u64 {
104        0x1201
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use ring::signature::{ECDSA_P384_SHA384_ASN1, VerificationAlgorithm};
111
112    use crate::parser::DidKeyParser;
113
114    use super::*;
115
116    #[test]
117    fn test_display() {
118        let pair = P384KeyPair::generate();
119        let did = pair.public().to_did();
120
121        let did_str = did.to_string();
122        println!("{}", did_str);
123        assert!(did_str.starts_with("did:key:z82"));
124    }
125
126    #[test]
127    fn test_jwk() {
128        let pair = P384KeyPair::generate();
129        let _ = pair.public().to_jwk();
130    }
131
132    #[test]
133    fn test_parse() {
134        let pair = P384KeyPair::generate();
135        let did = pair.public().to_did();
136
137        let parser = DidKeyParser::default();
138        let _ = parser.parse(&did).unwrap();
139    }
140
141    #[test]
142    fn test_sign() {
143        let pair = P384KeyPair::generate();
144
145        let msg = vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
146        let signature = pair.sign(&msg).unwrap();
147
148        assert!(
149            ECDSA_P384_SHA384_ASN1
150                .verify(
151                    pair.public().to_sec1_bytes().as_ref().into(),
152                    msg.as_slice().into(),
153                    signature.as_slice().into()
154                )
155                .is_ok()
156        );
157    }
158}