Skip to main content

bitwarden_crypto_primitives/rustcrypto/
p256.rs

1use p256::{
2    elliptic_curve::{Generate, sec1::ToSec1Point},
3    pkcs8::{DecodePrivateKey, EncodePrivateKey},
4};
5use zeroize::Zeroizing;
6
7use crate::{
8    Error,
9    p256::{SCALAR_LEN, SEC1_UNCOMPRESSED_LEN},
10    random::SystemRng,
11};
12
13#[derive(Clone)]
14pub(crate) struct SecretKey(p256::SecretKey);
15
16// The wrapped key wipes itself on drop.
17impl zeroize::ZeroizeOnDrop for SecretKey {}
18const _: fn() = || {
19    fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
20    assert_zeroize_on_drop::<p256::SecretKey>();
21};
22
23impl SecretKey {
24    pub(crate) fn generate() -> Self {
25        Self(p256::SecretKey::generate_from_rng(&mut SystemRng))
26    }
27
28    pub(crate) fn from_bytes(scalar: &[u8; SCALAR_LEN]) -> Result<Self, Error> {
29        p256::SecretKey::from_slice(scalar)
30            .map(Self)
31            .map_err(|_| Error::InvalidKey)
32    }
33
34    pub(crate) fn to_bytes(&self) -> Zeroizing<[u8; SCALAR_LEN]> {
35        Zeroizing::new(self.0.to_bytes().into())
36    }
37
38    pub(crate) fn from_pkcs8_der(der: &[u8]) -> Result<Self, Error> {
39        p256::SecretKey::from_pkcs8_der(der)
40            .map(Self)
41            .map_err(|_| Error::InvalidKey)
42    }
43
44    pub(crate) fn to_pkcs8_der(&self) -> Result<Zeroizing<Vec<u8>>, Error> {
45        let doc = self.0.to_pkcs8_der().map_err(|_| Error::InvalidKey)?;
46        Ok(Zeroizing::new(doc.as_bytes().to_vec()))
47    }
48
49    pub(crate) fn public_key(&self) -> PublicKey {
50        PublicKey(self.0.public_key())
51    }
52
53    pub(crate) fn diffie_hellman(&self, peer: &PublicKey) -> Zeroizing<[u8; SCALAR_LEN]> {
54        let shared = p256::ecdh::diffie_hellman(self.0.to_nonzero_scalar(), peer.0.as_affine());
55        Zeroizing::new((*shared.raw_secret_bytes()).into())
56    }
57}
58
59#[derive(Clone, PartialEq, Eq)]
60pub(crate) struct PublicKey(p256::PublicKey);
61
62impl PublicKey {
63    pub(crate) fn from_sec1_bytes(bytes: &[u8]) -> Result<Self, Error> {
64        p256::PublicKey::from_sec1_bytes(bytes)
65            .map(Self)
66            .map_err(|_| Error::InvalidKey)
67    }
68
69    pub(crate) fn to_sec1_uncompressed(&self) -> [u8; SEC1_UNCOMPRESSED_LEN] {
70        self.0
71            .to_sec1_point(false)
72            .as_bytes()
73            .try_into()
74            .expect("uncompressed P-256 point is 65 bytes")
75    }
76}