chik_secp/secp256r1/
secret_key.rs

1use std::{
2    fmt,
3    hash::{Hash, Hasher},
4};
5
6use p256::ecdsa::{Error, SigningKey};
7
8use super::{R1PublicKey, R1Signature};
9
10#[derive(Clone, PartialEq, Eq)]
11pub struct R1SecretKey(SigningKey);
12
13impl Hash for R1SecretKey {
14    fn hash<H: Hasher>(&self, state: &mut H) {
15        self.to_bytes().hash(state);
16    }
17}
18
19impl fmt::Debug for R1SecretKey {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        write!(f, "R1SecretKey(...)")
22    }
23}
24
25#[cfg(feature = "arbitrary")]
26impl<'a> arbitrary::Arbitrary<'a> for R1SecretKey {
27    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
28        Self::from_bytes(&u.arbitrary()?).map_err(|_| arbitrary::Error::IncorrectFormat)
29    }
30}
31
32impl R1SecretKey {
33    pub fn to_bytes(&self) -> [u8; 32] {
34        self.0.to_bytes().into()
35    }
36
37    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, Error> {
38        Ok(Self(SigningKey::from_bytes(bytes.into())?))
39    }
40
41    pub fn public_key(&self) -> R1PublicKey {
42        R1PublicKey(*self.0.verifying_key())
43    }
44
45    pub fn sign_prehashed(&self, message_hash: &[u8; 32]) -> Result<R1Signature, Error> {
46        Ok(R1Signature(
47            self.0.sign_prehash_recoverable(message_hash)?.0,
48        ))
49    }
50}