Skip to main content

ecdsa/
sign.rs

1//! ECDSA signing key.
2
3// TODO(tarcieri): support for hardware crypto accelerators
4
5use crate::{
6    hazmat::{DigestPrimitive, FromDigest, SignPrimitive},
7    rfc6979, Error, Result, Signature, SignatureSize,
8};
9use core::{
10    convert::TryFrom,
11    fmt::{self, Debug},
12};
13use elliptic_curve::{
14    generic_array::ArrayLength,
15    group::ff::PrimeField,
16    ops::Invert,
17    subtle::{Choice, ConstantTimeEq},
18    weierstrass::Curve,
19    zeroize::Zeroize,
20    FieldBytes, FieldSize, NonZeroScalar, ProjectiveArithmetic, Scalar, SecretKey,
21};
22use signature::{
23    digest::{BlockInput, Digest, FixedOutput, Reset, Update},
24    rand_core::{CryptoRng, RngCore},
25    DigestSigner, RandomizedDigestSigner, RandomizedSigner, Signer,
26};
27
28#[cfg(feature = "verify")]
29use {
30    crate::verify::VerifyingKey,
31    elliptic_curve::{AffinePoint, PublicKey},
32};
33
34#[cfg(feature = "pkcs8")]
35use crate::elliptic_curve::{
36    consts::U1,
37    ops::Add,
38    pkcs8::{self, FromPrivateKey},
39    sec1::{FromEncodedPoint, ToEncodedPoint, UncompressedPointSize, UntaggedPointSize},
40    AlgorithmParameters,
41};
42
43#[cfg(feature = "pem")]
44use core::str::FromStr;
45
46/// ECDSA signing key. Generic over elliptic curves.
47///
48/// Requires an [`elliptic_curve::ProjectiveArithmetic`] impl on the curve, and a
49/// [`SignPrimitive`] impl on its associated `Scalar` type.
50#[derive(Clone)]
51#[cfg_attr(docsrs, doc(cfg(feature = "sign")))]
52pub struct SigningKey<C>
53where
54    C: Curve + ProjectiveArithmetic,
55    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
56    SignatureSize<C>: ArrayLength<u8>,
57{
58    inner: NonZeroScalar<C>,
59}
60
61impl<C> SigningKey<C>
62where
63    C: Curve + ProjectiveArithmetic,
64    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
65    SignatureSize<C>: ArrayLength<u8>,
66{
67    /// Generate a cryptographically random [`SigningKey`].
68    pub fn random(rng: impl CryptoRng + RngCore) -> Self {
69        Self {
70            inner: NonZeroScalar::random(rng),
71        }
72    }
73
74    /// Initialize signing key from a raw scalar serialized as a byte slice.
75    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
76        let inner = SecretKey::from_bytes(bytes)
77            .map(|sk| sk.to_secret_scalar())
78            .map_err(|_| Error::new())?;
79
80        Ok(Self { inner })
81    }
82
83    /// Get the [`VerifyingKey`] which corresponds to this [`SigningKey`]
84    #[cfg(feature = "verify")]
85    #[cfg_attr(docsrs, doc(cfg(feature = "verify")))]
86    pub fn verifying_key(&self) -> VerifyingKey<C> {
87        VerifyingKey {
88            inner: PublicKey::from_secret_scalar(&self.inner),
89        }
90    }
91
92    /// Serialize this [`SigningKey`] as bytes
93    pub fn to_bytes(&self) -> FieldBytes<C> {
94        self.inner.to_repr()
95    }
96}
97
98impl<C> ConstantTimeEq for SigningKey<C>
99where
100    C: Curve + ProjectiveArithmetic,
101    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
102    SignatureSize<C>: ArrayLength<u8>,
103{
104    fn ct_eq(&self, other: &Self) -> Choice {
105        self.inner.ct_eq(&other.inner)
106    }
107}
108
109impl<C> Debug for SigningKey<C>
110where
111    C: Curve + ProjectiveArithmetic,
112    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
113    SignatureSize<C>: ArrayLength<u8>,
114{
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        // TODO(tarcieri): use `finish_non_exhaustive` when stable
117        f.debug_tuple("SigningKey").field(&"...").finish()
118    }
119}
120
121impl<C> Drop for SigningKey<C>
122where
123    C: Curve + ProjectiveArithmetic,
124    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
125    SignatureSize<C>: ArrayLength<u8>,
126{
127    fn drop(&mut self) {
128        self.inner.zeroize();
129    }
130}
131
132impl<C> Eq for SigningKey<C>
133where
134    C: Curve + ProjectiveArithmetic,
135    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
136    SignatureSize<C>: ArrayLength<u8>,
137{
138}
139
140impl<C> PartialEq for SigningKey<C>
141where
142    C: Curve + ProjectiveArithmetic,
143    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
144    SignatureSize<C>: ArrayLength<u8>,
145{
146    fn eq(&self, other: &SigningKey<C>) -> bool {
147        self.ct_eq(other).into()
148    }
149}
150
151impl<C> From<SecretKey<C>> for SigningKey<C>
152where
153    C: Curve + ProjectiveArithmetic,
154    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
155    SignatureSize<C>: ArrayLength<u8>,
156{
157    fn from(secret_key: SecretKey<C>) -> Self {
158        Self::from(&secret_key)
159    }
160}
161
162impl<C> From<&SecretKey<C>> for SigningKey<C>
163where
164    C: Curve + ProjectiveArithmetic,
165    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
166    SignatureSize<C>: ArrayLength<u8>,
167{
168    fn from(secret_key: &SecretKey<C>) -> Self {
169        Self {
170            inner: secret_key.to_secret_scalar(),
171        }
172    }
173}
174
175impl<C, D> DigestSigner<D, Signature<C>> for SigningKey<C>
176where
177    C: Curve + ProjectiveArithmetic,
178    D: FixedOutput<OutputSize = FieldSize<C>> + BlockInput + Clone + Default + Reset + Update,
179    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
180    SignatureSize<C>: ArrayLength<u8>,
181{
182    /// Sign message prehash using a deterministic ephemeral scalar (`k`)
183    /// computed using the algorithm described in RFC 6979 (Section 3.2):
184    /// <https://tools.ietf.org/html/rfc6979#section-3>
185    fn try_sign_digest(&self, digest: D) -> Result<Signature<C>> {
186        let k = rfc6979::generate_k(&self.inner, digest.clone(), &[]);
187        let msg_scalar = Scalar::<C>::from_digest(digest);
188        self.inner.try_sign_prehashed(&**k, &msg_scalar)
189    }
190}
191
192impl<C> Signer<Signature<C>> for SigningKey<C>
193where
194    Self: DigestSigner<C::Digest, Signature<C>>,
195    C: Curve + ProjectiveArithmetic + DigestPrimitive,
196    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
197    SignatureSize<C>: ArrayLength<u8>,
198{
199    fn try_sign(&self, msg: &[u8]) -> Result<Signature<C>> {
200        self.try_sign_digest(C::Digest::new().chain(msg))
201    }
202}
203
204impl<C, D> RandomizedDigestSigner<D, Signature<C>> for SigningKey<C>
205where
206    C: Curve + ProjectiveArithmetic,
207    D: FixedOutput<OutputSize = FieldSize<C>> + BlockInput + Clone + Default + Reset + Update,
208    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
209    SignatureSize<C>: ArrayLength<u8>,
210{
211    /// Sign message prehash using an ephemeral scalar (`k`) derived according
212    /// to a variant of RFC 6979 (Section 3.6) which supplies additional
213    /// entropy from an RNG.
214    fn try_sign_digest_with_rng(
215        &self,
216        mut rng: impl CryptoRng + RngCore,
217        digest: D,
218    ) -> Result<Signature<C>> {
219        let mut added_entropy = FieldBytes::<C>::default();
220        rng.fill_bytes(&mut added_entropy);
221
222        let k = rfc6979::generate_k(&self.inner, digest.clone(), &added_entropy);
223        let msg_scalar = Scalar::<C>::from_digest(digest);
224        self.inner.try_sign_prehashed(&**k, &msg_scalar)
225    }
226}
227
228impl<C> RandomizedSigner<Signature<C>> for SigningKey<C>
229where
230    Self: RandomizedDigestSigner<C::Digest, Signature<C>>,
231    C: Curve + ProjectiveArithmetic + DigestPrimitive,
232    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
233    SignatureSize<C>: ArrayLength<u8>,
234{
235    fn try_sign_with_rng(&self, rng: impl CryptoRng + RngCore, msg: &[u8]) -> Result<Signature<C>> {
236        self.try_sign_digest_with_rng(rng, C::Digest::new().chain(msg))
237    }
238}
239
240impl<C> From<NonZeroScalar<C>> for SigningKey<C>
241where
242    C: Curve + ProjectiveArithmetic,
243    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
244    SignatureSize<C>: ArrayLength<u8>,
245{
246    fn from(secret_scalar: NonZeroScalar<C>) -> Self {
247        Self {
248            inner: secret_scalar,
249        }
250    }
251}
252
253impl<C> TryFrom<&[u8]> for SigningKey<C>
254where
255    C: Curve + ProjectiveArithmetic,
256    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
257    SignatureSize<C>: ArrayLength<u8>,
258{
259    type Error = Error;
260
261    fn try_from(bytes: &[u8]) -> Result<Self> {
262        Self::from_bytes(bytes)
263    }
264}
265
266#[cfg(feature = "verify")]
267impl<C> From<&SigningKey<C>> for VerifyingKey<C>
268where
269    C: Curve + ProjectiveArithmetic,
270
271    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
272    SignatureSize<C>: ArrayLength<u8>,
273{
274    fn from(signing_key: &SigningKey<C>) -> VerifyingKey<C> {
275        signing_key.verifying_key()
276    }
277}
278
279#[cfg(feature = "pkcs8")]
280#[cfg_attr(docsrs, doc(cfg(feature = "pkcs8")))]
281impl<C> FromPrivateKey for SigningKey<C>
282where
283    C: Curve + AlgorithmParameters + ProjectiveArithmetic,
284    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
285    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
286    SignatureSize<C>: ArrayLength<u8>,
287    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
288    UncompressedPointSize<C>: ArrayLength<u8>,
289{
290    fn from_pkcs8_private_key_info(
291        private_key_info: pkcs8::PrivateKeyInfo<'_>,
292    ) -> pkcs8::Result<Self> {
293        SecretKey::from_pkcs8_private_key_info(private_key_info).map(Into::into)
294    }
295}
296
297#[cfg(feature = "pem")]
298#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
299impl<C> FromStr for SigningKey<C>
300where
301    C: Curve + AlgorithmParameters + ProjectiveArithmetic,
302    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
303    Scalar<C>: FromDigest<C> + Invert<Output = Scalar<C>> + SignPrimitive<C> + Zeroize,
304    SignatureSize<C>: ArrayLength<u8>,
305    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
306    UncompressedPointSize<C>: ArrayLength<u8>,
307{
308    type Err = Error;
309
310    fn from_str(s: &str) -> Result<Self> {
311        Self::from_pkcs8_pem(s).map_err(|_| Error::new())
312    }
313}