Skip to main content

m10_signing/
p256.rs

1use crate::{internal_error, PreparedDigest, PreparedTransaction, Signer, SigningError};
2use core::convert::TryFrom;
3use core::str::FromStr;
4use m10_protos::sdk::signature::Algorithm;
5use p256::ecdsa::signature::hazmat::PrehashSigner;
6use p256::pkcs8::{DecodePrivateKey, EncodePrivateKey};
7use std::fs::File;
8use std::io::{Read, Write};
9
10/// A P256 key-pair
11#[derive(serde::Deserialize)]
12#[serde(try_from = "String", into = "String")]
13pub struct P256 {
14    #[serde(skip)]
15    key: p256::ecdsa::SigningKey,
16    public_key: [u8; 65],
17}
18
19fn make_p256(key: p256::ecdsa::SigningKey) -> P256 {
20    let ep = key.verifying_key().to_encoded_point(false);
21    let public_key: [u8; 65] = ep
22        .as_bytes()
23        .try_into()
24        .expect("P-256 uncompressed point is always 65 bytes");
25    P256 { key, public_key }
26}
27
28impl P256 {
29    /// Generates a P256 key-pair, and if the path is passed writes it to disk as a PKCS8 document
30    pub fn new_key_pair(path: Option<&str>) -> Result<Self, SigningError> {
31        let key = p256::ecdsa::SigningKey::random(&mut rand_core::OsRng);
32        if let Some(p) = path {
33            let doc = key
34                .to_pkcs8_der()
35                .map_err(|e| internal_error(e, "P256::new_key_pair: to_pkcs8_der"))?;
36            let mut key_file = File::create(p)?;
37            key_file.write_all(doc.as_bytes())?;
38        }
39        Ok(make_p256(key))
40    }
41
42    /// Loads a P256 key-pair from a PKCS8 formatted file
43    pub fn load_key_pair(path: &str) -> Result<Self, SigningError> {
44        let mut key_file = File::open(path)?;
45        let mut pkcs8_bytes: Vec<u8> = Vec::new();
46        key_file.read_to_end(&mut pkcs8_bytes)?;
47        P256::from_pkcs8(&pkcs8_bytes)
48    }
49
50    /// Generates a new key-pair, and returns both the key-pair and a PKCS8 document containing the key-pair
51    pub fn new_key_pair_exportable() -> Result<(Vec<u8>, Self), SigningError> {
52        let key = p256::ecdsa::SigningKey::random(&mut rand_core::OsRng);
53        let doc = key
54            .to_pkcs8_der()
55            .map_err(|e| internal_error(e, "P256::new_key_pair_exportable: to_pkcs8_der"))?;
56        let pkcs8_bytes = doc.as_bytes().to_vec();
57        Ok((pkcs8_bytes, make_p256(key)))
58    }
59
60    /// Returns a new [`P256`] key-pair from a PKCS8 document
61    pub fn from_pkcs8(bytes: &[u8]) -> Result<Self, SigningError> {
62        let key = p256::ecdsa::SigningKey::from_pkcs8_der(bytes)
63            .map_err(|e| internal_error(e, "P256::from_pkcs8"))?;
64        Ok(make_p256(key))
65    }
66}
67
68#[async_trait::async_trait]
69impl Signer for P256 {
70    async fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, super::SigningError> {
71        use p256::ecdsa::signature::Signer as _;
72        let sig: p256::ecdsa::Signature = self.key.sign(msg);
73        Ok(sig.to_der().to_bytes().to_vec())
74    }
75
76    fn public_key(&self) -> &[u8] {
77        &self.public_key
78    }
79
80    fn algorithm(&self) -> Algorithm {
81        Algorithm::P256Sha256Asn1
82    }
83
84    async fn sign_prepared_transaction(
85        &self,
86        prepared: &PreparedTransaction,
87    ) -> Result<Vec<u8>, super::SigningError> {
88        let hash = match (prepared.algorithm, &prepared.digest) {
89            (Algorithm::P256Sha256Asn1, PreparedDigest::P256Sha256(h)) => h,
90            _ => {
91                return Err(internal_error(
92                    "algorithm and digest type mismatch or unsupported",
93                    "P256::sign_prepared_transaction",
94                ))
95            }
96        };
97
98        let sig: p256::ecdsa::Signature = self
99            .key
100            .sign_prehash(hash)
101            .map_err(|e| internal_error(e, "P256::sign_prepared_transaction: sign_prehash"))?;
102
103        Ok(sig.to_der().to_bytes().to_vec())
104    }
105}
106
107impl FromStr for P256 {
108    type Err = SigningError;
109    fn from_str(key_pair_enc: &str) -> Result<Self, Self::Err> {
110        let pkcs8_bytes = base64::decode(key_pair_enc).unwrap_or_default();
111        P256::from_pkcs8(&pkcs8_bytes)
112    }
113}
114
115impl TryFrom<String> for P256 {
116    type Error = SigningError;
117    fn try_from(key_pair: String) -> Result<Self, Self::Error> {
118        key_pair.parse()
119    }
120}