Skip to main content

elliptic_curve/
secret_key.rs

1//! Secret keys for elliptic curves (i.e. private scalars).
2//!
3//! The [`SecretKey`] type is a wrapper around a secret scalar value which is
4//! designed to prevent unintentional exposure (e.g. via `Debug` or other
5//! logging).
6//!
7//! When the `zeroize` feature of this crate is enabled, it also handles
8//! zeroing it out of memory securely on drop.
9
10#[cfg(feature = "pkcs8")]
11mod pkcs8;
12
13use crate::{Curve, Error, FieldBytes, Result, ScalarBytes};
14use core::{
15    convert::TryFrom,
16    fmt::{self, Debug},
17};
18use zeroize::Zeroize;
19
20#[cfg(feature = "arithmetic")]
21use crate::{
22    rand_core::{CryptoRng, RngCore},
23    weierstrass, NonZeroScalar, ProjectiveArithmetic, PublicKey, Scalar,
24};
25
26#[cfg(feature = "jwk")]
27use crate::{
28    generic_array::{typenum::U1, ArrayLength},
29    jwk::{JwkEcKey, JwkParameters},
30    ops::Add,
31    sec1::{UncompressedPointSize, UntaggedPointSize, ValidatePublicKey},
32};
33
34#[cfg(all(feature = "arithmetic", feature = "jwk"))]
35use {
36    crate::{
37        sec1::{FromEncodedPoint, ToEncodedPoint},
38        AffinePoint,
39    },
40    alloc::string::{String, ToString},
41};
42
43#[cfg(all(docsrs, feature = "pkcs8"))]
44use {crate::pkcs8::FromPrivateKey, core::str::FromStr};
45
46/// Elliptic curve secret keys.
47///
48/// This type wraps a secret scalar value, helping to prevent accidental
49/// exposure and securely erasing the value from memory when dropped
50/// (when the `zeroize` feature of this crate is enabled).
51///
52/// # Parsing PKCS#8 Keys
53///
54/// PKCS#8 is a commonly used format for encoding secret keys (especially ones
55/// generated by OpenSSL).
56///
57/// Keys in PKCS#8 format are either binary (ASN.1 BER/DER), or PEM encoded
58/// (ASCII) and begin with the following:
59///
60/// ```text
61/// -----BEGIN PRIVATE KEY-----
62/// ```
63///
64/// To decode an elliptic curve private key from PKCS#8, enable the `pkcs8`
65/// feature of this crate (or the `pkcs8` feature of a specific RustCrypto
66/// elliptic curve crate) and use the
67/// [`elliptic_curve::pkcs8::FromPrivateKey`][`FromPrivateKey`]
68/// trait to parse it.
69///
70/// When the `pem` feature of this crate (or a specific RustCrypto elliptic
71/// curve crate) is enabled, a [`FromStr`] impl is also available.
72#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
73#[derive(Clone)]
74pub struct SecretKey<C: Curve> {
75    /// Serialized scalar value
76    inner: ScalarBytes<C>,
77}
78
79impl<C> SecretKey<C>
80where
81    C: Curve,
82{
83    /// Generate a random [`SecretKey`]
84    #[cfg(feature = "arithmetic")]
85    #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
86    pub fn random(rng: impl CryptoRng + RngCore) -> Self
87    where
88        C: ProjectiveArithmetic,
89        Scalar<C>: Zeroize,
90    {
91        Self {
92            inner: NonZeroScalar::<C>::random(rng).into(),
93        }
94    }
95
96    /// Create a new secret key from a serialized scalar value
97    pub fn new(scalar: ScalarBytes<C>) -> Self {
98        Self { inner: scalar }
99    }
100
101    /// Deserialize raw private scalar as a big endian integer
102    pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> {
103        let scalar = ScalarBytes::try_from(bytes.as_ref())?;
104
105        if scalar.is_zero().into() {
106            return Err(Error);
107        }
108
109        Ok(Self { inner: scalar })
110    }
111
112    /// Expose the byte serialization of the value this [`SecretKey`] wraps
113    pub fn to_bytes(&self) -> FieldBytes<C> {
114        self.inner.clone().into()
115    }
116
117    /// Borrow the inner secret [`ScalarBytes`] value.
118    ///
119    /// # Warning
120    ///
121    /// This value is key material.
122    ///
123    /// Please treat it with the care it deserves!
124    pub fn as_scalar_bytes(&self) -> &ScalarBytes<C> {
125        &self.inner
126    }
127
128    /// Get the secret scalar value for this key..
129    #[cfg(feature = "arithmetic")]
130    #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
131    pub fn to_secret_scalar(&self) -> NonZeroScalar<C>
132    where
133        C: Curve + ProjectiveArithmetic,
134        Scalar<C>: Zeroize,
135    {
136        self.into()
137    }
138
139    /// Get the [`PublicKey`] which corresponds to this secret key
140    #[cfg(feature = "arithmetic")]
141    #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
142    pub fn public_key(&self) -> PublicKey<C>
143    where
144        C: weierstrass::Curve + ProjectiveArithmetic,
145        Scalar<C>: Zeroize,
146    {
147        PublicKey::from_secret_scalar(&self.to_secret_scalar())
148    }
149
150    /// Parse a [`JwkEcKey`] JSON Web Key (JWK) into a [`SecretKey`].
151    #[cfg(feature = "jwk")]
152    #[cfg_attr(docsrs, doc(cfg(feature = "jwk")))]
153    pub fn from_jwk(jwk: &JwkEcKey) -> Result<Self>
154    where
155        C: JwkParameters + ValidatePublicKey,
156        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
157        UncompressedPointSize<C>: ArrayLength<u8>,
158    {
159        Self::try_from(jwk)
160    }
161
162    /// Parse a string containing a JSON Web Key (JWK) into a [`SecretKey`].
163    #[cfg(feature = "jwk")]
164    #[cfg_attr(docsrs, doc(cfg(feature = "jwk")))]
165    pub fn from_jwk_str(jwk: &str) -> Result<Self>
166    where
167        C: JwkParameters + ValidatePublicKey,
168        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
169        UncompressedPointSize<C>: ArrayLength<u8>,
170    {
171        jwk.parse::<JwkEcKey>().and_then(|jwk| Self::from_jwk(&jwk))
172    }
173
174    /// Serialize this secret key as [`JwkEcKey`] JSON Web Key (JWK).
175    #[cfg(all(feature = "arithmetic", feature = "jwk"))]
176    #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
177    #[cfg_attr(docsrs, doc(cfg(feature = "jwk")))]
178    pub fn to_jwk(&self) -> JwkEcKey
179    where
180        C: JwkParameters + ProjectiveArithmetic,
181        AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
182        Scalar<C>: Zeroize,
183        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
184        UncompressedPointSize<C>: ArrayLength<u8>,
185    {
186        self.into()
187    }
188
189    /// Serialize this secret key as JSON Web Key (JWK) string.
190    #[cfg(all(feature = "arithmetic", feature = "jwk"))]
191    #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
192    #[cfg_attr(docsrs, doc(cfg(feature = "jwk")))]
193    pub fn to_jwk_string(&self) -> String
194    where
195        C: JwkParameters + ProjectiveArithmetic,
196        AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
197        Scalar<C>: Zeroize,
198        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
199        UncompressedPointSize<C>: ArrayLength<u8>,
200    {
201        self.to_jwk().to_string()
202    }
203}
204
205#[cfg(feature = "arithmetic")]
206#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
207impl<C> From<NonZeroScalar<C>> for SecretKey<C>
208where
209    C: Curve + ProjectiveArithmetic,
210{
211    fn from(scalar: NonZeroScalar<C>) -> SecretKey<C> {
212        SecretKey::from(&scalar)
213    }
214}
215
216#[cfg(feature = "arithmetic")]
217#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
218impl<C> From<&NonZeroScalar<C>> for SecretKey<C>
219where
220    C: Curve + ProjectiveArithmetic,
221{
222    fn from(scalar: &NonZeroScalar<C>) -> SecretKey<C> {
223        SecretKey {
224            inner: scalar.into(),
225        }
226    }
227}
228
229impl<C> TryFrom<&[u8]> for SecretKey<C>
230where
231    C: Curve,
232{
233    type Error = Error;
234
235    fn try_from(slice: &[u8]) -> Result<Self> {
236        Self::from_bytes(slice)
237    }
238}
239
240impl<C> Debug for SecretKey<C>
241where
242    C: Curve,
243{
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        // TODO(tarcieri): use `debug_struct` and `finish_non_exhaustive` when stable
246        write!(f, "SecretKey<{:?}>{{ ... }}", C::default())
247    }
248}
249
250impl<C> Drop for SecretKey<C>
251where
252    C: Curve,
253{
254    fn drop(&mut self) {
255        self.inner.zeroize();
256    }
257}