Skip to main content

ed25519_dalek/
signing.rs

1// -*- mode: rust; -*-
2//
3// This file is part of ed25519-dalek.
4// Copyright (c) 2017-2019 isis lovecruft
5// See LICENSE for licensing information.
6//
7// Authors:
8// - isis agora lovecruft <isis@patternsinthevoid.net>
9
10//! ed25519 signing keys.
11
12use core::fmt::Debug;
13
14#[cfg(feature = "pkcs8")]
15use ed25519::pkcs8;
16
17#[cfg(feature = "rand_core")]
18use rand_core::CryptoRng;
19
20#[cfg(feature = "serde")]
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22
23#[cfg(feature = "digest")]
24use curve25519_dalek::digest::{
25    common::{InvalidKey, Key, KeySizeUser, TryKeyInit},
26    typenum::U32,
27};
28
29#[cfg(all(feature = "digest", feature = "rand_core"))]
30use curve25519_dalek::digest::common::Generate;
31
32use sha2::Sha512;
33use subtle::{Choice, ConstantTimeEq};
34
35use curve25519_dalek::{
36    digest::{Digest, array::typenum::U64},
37    edwards::{CompressedEdwardsY, EdwardsPoint},
38    scalar::Scalar,
39};
40
41use ed25519::signature::{KeypairRef, MultipartSigner, MultipartVerifier, Signer, Verifier};
42
43#[cfg(feature = "digest")]
44use crate::context::Context;
45#[cfg(feature = "digest")]
46use curve25519_dalek::digest::Update;
47#[cfg(feature = "digest")]
48use signature::DigestSigner;
49
50#[cfg(feature = "zeroize")]
51use zeroize::{Zeroize, ZeroizeOnDrop};
52
53#[cfg(feature = "hazmat")]
54use crate::verifying::StreamVerifier;
55use crate::{
56    Signature,
57    constants::{KEYPAIR_LENGTH, SECRET_KEY_LENGTH},
58    errors::{InternalError, SignatureError},
59    hazmat::ExpandedSecretKey,
60    signature::InternalSignature,
61    verifying::VerifyingKey,
62};
63
64/// ed25519 secret key as defined in [RFC8032 § 5.1.5]:
65///
66/// > The private key is 32 octets (256 bits, corresponding to b) of
67/// > cryptographically secure random data.
68///
69/// [RFC8032 § 5.1.5]: https://www.rfc-editor.org/rfc/rfc8032#section-5.1.5
70pub type SecretKey = [u8; SECRET_KEY_LENGTH];
71
72/// ed25519 signing key which can be used to produce signatures.
73// Invariant: `verifying_key` is always the public key of
74// `secret_key`. This prevents the signing function oracle attack
75// described in https://github.com/MystenLabs/ed25519-unsafe-libs
76#[derive(Clone)]
77pub struct SigningKey {
78    /// The secret half of this signing key.
79    pub(crate) secret_key: SecretKey,
80    /// The public half of this signing key.
81    pub(crate) verifying_key: VerifyingKey,
82}
83
84/// # Example
85///
86/// ```
87/// # extern crate ed25519_dalek;
88/// #
89/// use ed25519_dalek::SigningKey;
90/// use ed25519_dalek::SECRET_KEY_LENGTH;
91/// use ed25519_dalek::SignatureError;
92///
93/// # fn doctest() -> Result<SigningKey, SignatureError> {
94/// let secret_key_bytes: [u8; SECRET_KEY_LENGTH] = [
95///    157, 097, 177, 157, 239, 253, 090, 096,
96///    186, 132, 074, 244, 146, 236, 044, 196,
97///    068, 073, 197, 105, 123, 050, 105, 025,
98///    112, 059, 172, 003, 028, 174, 127, 096, ];
99///
100/// let signing_key: SigningKey = SigningKey::from_bytes(&secret_key_bytes);
101/// assert_eq!(signing_key.to_bytes(), secret_key_bytes);
102///
103/// # Ok(signing_key)
104/// # }
105/// #
106/// # fn main() {
107/// #     let result = doctest();
108/// #     assert!(result.is_ok());
109/// # }
110/// ```
111impl SigningKey {
112    /// Construct a [`SigningKey`] from a [`SecretKey`]
113    ///
114    #[inline]
115    pub fn from_bytes(secret_key: &SecretKey) -> Self {
116        let verifying_key = VerifyingKey::from(&ExpandedSecretKey::from(secret_key));
117        Self {
118            secret_key: *secret_key,
119            verifying_key,
120        }
121    }
122
123    /// Convert this [`SigningKey`] into a [`SecretKey`]
124    #[inline]
125    pub fn to_bytes(&self) -> SecretKey {
126        self.secret_key
127    }
128
129    /// Convert this [`SigningKey`] into a [`SecretKey`] reference
130    #[inline]
131    pub fn as_bytes(&self) -> &SecretKey {
132        &self.secret_key
133    }
134
135    /// Construct a [`SigningKey`] from the bytes of a `VerifyingKey` and `SecretKey`.
136    ///
137    /// # Inputs
138    ///
139    /// * `bytes`: an `&[u8]` of length [`KEYPAIR_LENGTH`], representing the
140    ///   scalar for the secret key, and a compressed Edwards-Y coordinate of a
141    ///   point on curve25519, both as bytes. (As obtained from
142    ///   [`SigningKey::to_bytes`].)
143    ///
144    /// # Returns
145    ///
146    /// A `Result` whose okay value is an EdDSA [`SigningKey`] or whose error value
147    /// is a `SignatureError` describing the error that occurred.
148    #[inline]
149    pub fn from_keypair_bytes(bytes: &[u8; 64]) -> Result<SigningKey, SignatureError> {
150        let (secret_key, verifying_key) = bytes.split_at(SECRET_KEY_LENGTH);
151        let signing_key = SigningKey::try_from(secret_key)?;
152        let verifying_key = VerifyingKey::try_from(verifying_key)?;
153
154        if signing_key.verifying_key() != verifying_key {
155            return Err(InternalError::MismatchedKeypair.into());
156        }
157
158        Ok(signing_key)
159    }
160
161    /// Convert this signing key to a 64-byte keypair.
162    ///
163    /// # Returns
164    ///
165    /// An array of bytes, `[u8; KEYPAIR_LENGTH]`.  The first
166    /// `SECRET_KEY_LENGTH` of bytes is the `SecretKey`, and the next
167    /// `PUBLIC_KEY_LENGTH` bytes is the `VerifyingKey` (the same as other
168    /// libraries, such as [Adam Langley's ed25519 Golang
169    /// implementation](https://github.com/agl/ed25519/)). It is guaranteed that
170    /// the encoded public key is the one derived from the encoded secret key.
171    pub fn to_keypair_bytes(&self) -> [u8; KEYPAIR_LENGTH] {
172        let mut bytes: [u8; KEYPAIR_LENGTH] = [0u8; KEYPAIR_LENGTH];
173
174        bytes[..SECRET_KEY_LENGTH].copy_from_slice(&self.secret_key);
175        bytes[SECRET_KEY_LENGTH..].copy_from_slice(self.verifying_key.as_bytes());
176        bytes
177    }
178
179    /// Get the [`VerifyingKey`] for this [`SigningKey`].
180    pub fn verifying_key(&self) -> VerifyingKey {
181        self.verifying_key
182    }
183
184    /// Create a signing context that can be used for Ed25519ph with
185    /// [`DigestSigner`].
186    #[cfg(feature = "digest")]
187    pub fn with_context<'k, 'v>(
188        &'k self,
189        context_value: &'v [u8],
190    ) -> Result<Context<'k, 'v, Self>, SignatureError> {
191        Context::new(self, context_value)
192    }
193
194    /// Generate an ed25519 signing key.
195    ///
196    /// # Example
197    ///
198    #[cfg_attr(feature = "rand_core", doc = "```")]
199    #[cfg_attr(not(feature = "rand_core"), doc = "```ignore")]
200    /// # fn main() {
201    /// use getrandom::{SysRng, rand_core::{TryRng, UnwrapErr}};
202    /// use ed25519_dalek::{Signature, SigningKey};
203    ///
204    /// let mut csprng = UnwrapErr(SysRng);
205    /// let signing_key: SigningKey = SigningKey::generate(&mut csprng);
206    /// # }
207    /// ```
208    ///
209    /// # Input
210    ///
211    /// A CSPRNG with a `fill_bytes()` method, e.g. `rand_os::SysRng`.
212    #[cfg(feature = "rand_core")]
213    pub fn generate<R: CryptoRng + ?Sized>(csprng: &mut R) -> SigningKey {
214        let mut secret = SecretKey::default();
215        csprng.fill_bytes(&mut secret);
216        Self::from_bytes(&secret)
217    }
218
219    /// Sign a `prehashed_message` with this [`SigningKey`] using the
220    /// Ed25519ph algorithm defined in [RFC8032 §5.1][rfc8032].
221    ///
222    /// # Inputs
223    ///
224    /// * `prehashed_message` is an instantiated hash digest with 512-bits of
225    ///   output which has had the message to be signed previously fed into its
226    ///   state.
227    /// * `context` is an optional context string, up to 255 bytes inclusive,
228    ///   which may be used to provide additional domain separation.  If not
229    ///   set, this will default to an empty string.
230    ///
231    /// # Returns
232    ///
233    /// An Ed25519ph [`Signature`] on the `prehashed_message`.
234    ///
235    /// # Note
236    ///
237    /// The RFC only permits SHA-512 to be used for prehashing, i.e., `MsgDigest = Sha512`. This
238    /// function technically works, and is probably safe to use, with any secure hash function with
239    /// 512-bit digests, but anything outside of SHA-512 is NOT specification-compliant. We expose
240    /// [`crate::Sha512`] for user convenience.
241    ///
242    /// # Examples
243    ///
244    #[cfg_attr(all(feature = "rand_core", feature = "digest"), doc = "```")]
245    #[cfg_attr(
246        any(not(feature = "rand_core"), not(feature = "digest")),
247        doc = "```ignore"
248    )]
249    /// use ed25519_dalek::Digest;
250    /// use ed25519_dalek::SigningKey;
251    /// use ed25519_dalek::Signature;
252    /// use sha2::Sha512;
253    /// use getrandom::{SysRng, rand_core::{TryRng, UnwrapErr}};
254    ///
255    /// # fn main() {
256    /// let mut csprng = UnwrapErr(SysRng);
257    /// let signing_key: SigningKey = SigningKey::generate(&mut csprng);
258    /// let message: &[u8] = b"All I want is to pet all of the dogs.";
259    ///
260    /// // Create a hash digest object which we'll feed the message into:
261    /// let mut prehashed: Sha512 = Sha512::new();
262    ///
263    /// prehashed.update(message);
264    /// # }
265    /// ```
266    ///
267    /// If you want, you can optionally pass a "context".  It is generally a
268    /// good idea to choose a context and try to make it unique to your project
269    /// and this specific usage of signatures.
270    ///
271    /// For example, without this, if you were to [convert your OpenPGP key
272    /// to a Bitcoin key][terrible_idea] (just as an example, and also Don't
273    /// Ever Do That) and someone tricked you into signing an "email" which was
274    /// actually a Bitcoin transaction moving all your magic internet money to
275    /// their address, it'd be a valid transaction.
276    ///
277    /// By adding a context, this trick becomes impossible, because the context
278    /// is concatenated into the hash, which is then signed.  So, going with the
279    /// previous example, if your bitcoin wallet used a context of
280    /// "BitcoinWalletAppTxnSigning" and OpenPGP used a context (this is likely
281    /// the least of their safety problems) of "GPGsCryptoIsntConstantTimeLol",
282    /// then the signatures produced by both could never match the other, even
283    /// if they signed the exact same message with the same key.
284    ///
285    /// Let's add a context for good measure (remember, you'll want to choose
286    /// your own!):
287    ///
288    #[cfg_attr(all(feature = "rand_core", feature = "digest"), doc = "```")]
289    #[cfg_attr(
290        any(not(feature = "rand_core"), not(feature = "digest")),
291        doc = "```ignore"
292    )]
293    /// # use ed25519_dalek::Digest;
294    /// # use ed25519_dalek::SigningKey;
295    /// # use ed25519_dalek::Signature;
296    /// # use ed25519_dalek::SignatureError;
297    /// # use sha2::Sha512;
298    /// # use getrandom::{SysRng, rand_core::{TryRng, UnwrapErr}};
299    /// #
300    /// # fn do_test() -> Result<Signature, SignatureError> {
301    /// # let mut csprng = UnwrapErr(SysRng);
302    /// # let signing_key: SigningKey = SigningKey::generate(&mut csprng);
303    /// # let message: &[u8] = b"All I want is to pet all of the dogs.";
304    /// # let mut prehashed: Sha512 = Sha512::new();
305    /// # prehashed.update(message);
306    /// #
307    /// let context: &[u8] = b"Ed25519DalekSignPrehashedDoctest";
308    ///
309    /// let sig: Signature = signing_key.sign_prehashed(prehashed, Some(context))?;
310    /// #
311    /// # Ok(sig)
312    /// # }
313    /// # fn main() {
314    /// #     do_test();
315    /// # }
316    /// ```
317    ///
318    /// [rfc8032]: https://tools.ietf.org/html/rfc8032#section-5.1
319    /// [terrible_idea]: https://github.com/isislovecruft/scripts/blob/master/gpgkey2bc.py
320    #[cfg(feature = "digest")]
321    pub fn sign_prehashed<MsgDigest>(
322        &self,
323        prehashed_message: MsgDigest,
324        context: Option<&[u8]>,
325    ) -> Result<Signature, SignatureError>
326    where
327        MsgDigest: Digest<OutputSize = U64>,
328    {
329        ExpandedSecretKey::from(&self.secret_key).raw_sign_prehashed::<Sha512, MsgDigest>(
330            prehashed_message,
331            &self.verifying_key,
332            context,
333        )
334    }
335
336    /// Verify a signature on a message with this signing key's public key.
337    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), SignatureError> {
338        self.verifying_key.verify(message, signature)
339    }
340
341    /// Verify a `signature` on a `prehashed_message` using the Ed25519ph algorithm.
342    ///
343    /// # Inputs
344    ///
345    /// * `prehashed_message` is an instantiated hash digest with 512-bits of
346    ///   output which has had the message to be signed previously fed into its
347    ///   state.
348    /// * `context` is an optional context string, up to 255 bytes inclusive,
349    ///   which may be used to provide additional domain separation.  If not
350    ///   set, this will default to an empty string.
351    /// * `signature` is a purported Ed25519ph [`Signature`] on the `prehashed_message`.
352    ///
353    /// # Returns
354    ///
355    /// Returns `true` if the `signature` was a valid signature created by this
356    /// [`SigningKey`] on the `prehashed_message`.
357    ///
358    /// # Note
359    ///
360    /// The RFC only permits SHA-512 to be used for prehashing, i.e., `MsgDigest = Sha512`. This
361    /// function technically works, and is probably safe to use, with any secure hash function with
362    /// 512-bit digests, but anything outside of SHA-512 is NOT specification-compliant. We expose
363    /// [`crate::Sha512`] for user convenience.
364    ///
365    /// # Examples
366    ///
367    #[cfg_attr(all(feature = "rand_core", feature = "digest"), doc = "```")]
368    #[cfg_attr(
369        any(not(feature = "rand_core"), not(feature = "digest")),
370        doc = "```ignore"
371    )]
372    /// use ed25519_dalek::Digest;
373    /// use ed25519_dalek::SigningKey;
374    /// use ed25519_dalek::Signature;
375    /// use ed25519_dalek::SignatureError;
376    /// use sha2::Sha512;
377    /// use getrandom::{SysRng, rand_core::{TryRng, UnwrapErr}};
378    ///
379    /// # fn do_test() -> Result<(), SignatureError> {
380    /// let mut csprng = UnwrapErr(SysRng);
381    /// let signing_key: SigningKey = SigningKey::generate(&mut csprng);
382    /// let message: &[u8] = b"All I want is to pet all of the dogs.";
383    ///
384    /// let mut prehashed: Sha512 = Sha512::new();
385    /// prehashed.update(message);
386    ///
387    /// let context: &[u8] = b"Ed25519DalekSignPrehashedDoctest";
388    ///
389    /// let sig: Signature = signing_key.sign_prehashed(prehashed, Some(context))?;
390    ///
391    /// // The sha2::Sha512 struct doesn't implement Copy, so we'll have to create a new one:
392    /// let mut prehashed_again: Sha512 = Sha512::default();
393    /// prehashed_again.update(message);
394    ///
395    /// let verified = signing_key.verifying_key().verify_prehashed(prehashed_again, Some(context), &sig);
396    ///
397    /// assert!(verified.is_ok());
398    ///
399    /// # verified
400    /// # }
401    /// #
402    /// # fn main() {
403    /// #     do_test();
404    /// # }
405    /// ```
406    ///
407    /// [rfc8032]: https://tools.ietf.org/html/rfc8032#section-5.1
408    #[cfg(feature = "digest")]
409    pub fn verify_prehashed<MsgDigest>(
410        &self,
411        prehashed_message: MsgDigest,
412        context: Option<&[u8]>,
413        signature: &Signature,
414    ) -> Result<(), SignatureError>
415    where
416        MsgDigest: Digest<OutputSize = U64>,
417    {
418        self.verifying_key
419            .verify_prehashed(prehashed_message, context, signature)
420    }
421
422    /// Strictly verify a signature on a message with this signing key's public key.
423    ///
424    /// # On The (Multiple) Sources of Malleability in Ed25519 Signatures
425    ///
426    /// This version of verification is technically non-RFC8032 compliant.  The
427    /// following explains why.
428    ///
429    /// 1. Scalar Malleability
430    ///
431    /// The authors of the RFC explicitly stated that verification of an ed25519
432    /// signature must fail if the scalar `s` is not properly reduced mod \ell:
433    ///
434    /// > To verify a signature on a message M using public key A, with F
435    /// > being 0 for Ed25519ctx, 1 for Ed25519ph, and if Ed25519ctx or
436    /// > Ed25519ph is being used, C being the context, first split the
437    /// > signature into two 32-octet halves.  Decode the first half as a
438    /// > point R, and the second half as an integer S, in the range
439    /// > 0 <= s < L.  Decode the public key A as point A'.  If any of the
440    /// > decodings fail (including S being out of range), the signature is
441    /// > invalid.)
442    ///
443    /// All `verify_*()` functions within ed25519-dalek perform this check.
444    ///
445    /// 2. Point malleability
446    ///
447    /// The authors of the RFC added in a malleability check to step #3 in
448    /// §5.1.7, for small torsion components in the `R` value of the signature,
449    /// *which is not strictly required*, as they state:
450    ///
451    /// > Check the group equation \[8\]\[S\]B = \[8\]R + \[8\]\[k\]A'.  It's
452    /// > sufficient, but not required, to instead check \[S\]B = R + \[k\]A'.
453    ///
454    /// # History of Malleability Checks
455    ///
456    /// As originally defined (cf. the "Malleability" section in the README of
457    /// this repo), ed25519 signatures didn't consider *any* form of
458    /// malleability to be an issue.  Later the scalar malleability was
459    /// considered important.  Still later, particularly with interests in
460    /// cryptocurrency design and in unique identities (e.g. for Signal users,
461    /// Tor onion services, etc.), the group element malleability became a
462    /// concern.
463    ///
464    /// However, libraries had already been created to conform to the original
465    /// definition.  One well-used library in particular even implemented the
466    /// group element malleability check, *but only for batch verification*!
467    /// Which meant that even using the same library, a single signature could
468    /// verify fine individually, but suddenly, when verifying it with a bunch
469    /// of other signatures, the whole batch would fail!
470    ///
471    /// # "Strict" Verification
472    ///
473    /// This method performs *both* of the above signature malleability checks.
474    ///
475    /// It must be done as a separate method because one doesn't simply get to
476    /// change the definition of a cryptographic primitive ten years
477    /// after-the-fact with zero consideration for backwards compatibility in
478    /// hardware and protocols which have it already have the older definition
479    /// baked in.
480    ///
481    /// # Return
482    ///
483    /// Returns `Ok(())` if the signature is valid, and `Err` otherwise.
484    #[allow(non_snake_case)]
485    pub fn verify_strict(
486        &self,
487        message: &[u8],
488        signature: &Signature,
489    ) -> Result<(), SignatureError> {
490        self.verifying_key.verify_strict(message, signature)
491    }
492
493    /// Constructs stream verifier with candidate `signature`.
494    ///
495    /// See [`VerifyingKey::verify_stream()`] for more details.
496    #[cfg(feature = "hazmat")]
497    pub fn verify_stream(
498        &self,
499        signature: &ed25519::Signature,
500    ) -> Result<StreamVerifier, SignatureError> {
501        self.verifying_key.verify_stream(signature)
502    }
503
504    /// Convert this signing key into a byte representation of an unreduced, unclamped Curve25519
505    /// scalar. This is NOT the same thing as `self.to_scalar().to_bytes()`, since `to_scalar()`
506    /// performs a clamping step, which changes the value of the resulting scalar.
507    ///
508    /// This can be used for performing X25519 Diffie-Hellman using Ed25519 keys. The bytes output
509    /// by this function are a valid corresponding [`StaticSecret`](https://docs.rs/x25519-dalek/2.0.0/x25519_dalek/struct.StaticSecret.html#impl-From%3C%5Bu8;+32%5D%3E-for-StaticSecret)
510    /// for the X25519 public key given by `self.verifying_key().to_montgomery()`.
511    ///
512    /// # Note
513    ///
514    /// We do NOT recommend using a signing/verifying key for encryption. Signing keys are usually
515    /// long-term keys, while keys used for key exchange should rather be ephemeral. If you can
516    /// help it, use a separate key for encryption.
517    ///
518    /// For more information on the security of systems which use the same keys for both signing
519    /// and Diffie-Hellman, see the paper
520    /// [On using the same key pair for Ed25519 and an X25519 based KEM](https://eprint.iacr.org/2021/509).
521    pub fn to_scalar_bytes(&self) -> [u8; 32] {
522        // Per the spec, the ed25519 secret key sk is expanded to
523        //     (scalar_bytes, hash_prefix) = SHA-512(sk)
524        // where the two outputs are both 32 bytes. scalar_bytes is what we return. Its clamped and
525        // reduced form is what we use for signing (see impl ExpandedSecretKey)
526        let mut buf = [0u8; 32];
527        let scalar_and_hash_prefix = Sha512::default().chain_update(self.secret_key).finalize();
528        buf.copy_from_slice(&scalar_and_hash_prefix[..32]);
529        buf
530    }
531
532    /// Convert this signing key into a Curve25519 scalar. This is computed by clamping and
533    /// reducing the output of [`Self::to_scalar_bytes`].
534    ///
535    /// This can be used anywhere where a Curve25519 scalar is used as a private key, e.g., in
536    /// [`crypto_box`](https://docs.rs/crypto_box/0.9.1/crypto_box/struct.SecretKey.html#impl-From%3CScalar%3E-for-SecretKey).
537    ///
538    /// # Note
539    ///
540    /// We do NOT recommend using a signing/verifying key for encryption. Signing keys are usually
541    /// long-term keys, while keys used for key exchange should rather be ephemeral. If you can
542    /// help it, use a separate key for encryption.
543    ///
544    /// For more information on the security of systems which use the same keys for both signing
545    /// and Diffie-Hellman, see the paper
546    /// [On using the same key pair for Ed25519 and an X25519 based KEM](https://eprint.iacr.org/2021/509).
547    pub fn to_scalar(&self) -> Scalar {
548        // Per the spec, the ed25519 secret key sk is expanded to
549        //     (scalar_bytes, hash_prefix) = SHA-512(sk)
550        // where the two outputs are both 32 bytes. To use for signing, scalar_bytes must be
551        // clamped and reduced (see ExpandedSecretKey::from_bytes). We return the clamped and
552        // reduced form.
553        ExpandedSecretKey::from(&self.secret_key).scalar
554    }
555}
556
557#[cfg(feature = "digest")]
558impl KeySizeUser for SigningKey {
559    type KeySize = U32;
560}
561
562#[cfg(feature = "digest")]
563impl TryKeyInit for SigningKey {
564    fn new(key: &Key<Self>) -> Result<Self, InvalidKey> {
565        Ok(Self::from_bytes(key.as_ref()))
566    }
567}
568
569#[cfg(all(feature = "digest", feature = "rand_core"))]
570impl Generate for SigningKey {
571    fn try_generate_from_rng<R: rand_core::TryCryptoRng + ?Sized>(
572        rng: &mut R,
573    ) -> Result<Self, R::Error> {
574        let mut secret = SecretKey::default();
575        rng.try_fill_bytes(&mut secret)?;
576        Ok(Self::from_bytes(&secret))
577    }
578}
579
580impl AsRef<VerifyingKey> for SigningKey {
581    fn as_ref(&self) -> &VerifyingKey {
582        &self.verifying_key
583    }
584}
585
586impl Debug for SigningKey {
587    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
588        f.debug_struct("SigningKey")
589            .field("verifying_key", &self.verifying_key)
590            .finish_non_exhaustive() // avoids printing `secret_key`
591    }
592}
593
594impl KeypairRef for SigningKey {
595    type VerifyingKey = VerifyingKey;
596}
597
598impl Signer<Signature> for SigningKey {
599    /// Sign a message with this signing key's secret key.
600    fn try_sign(&self, message: &[u8]) -> Result<Signature, SignatureError> {
601        self.try_multipart_sign(&[message])
602    }
603}
604
605impl MultipartSigner<Signature> for SigningKey {
606    fn try_multipart_sign(&self, message: &[&[u8]]) -> Result<Signature, SignatureError> {
607        let expanded: ExpandedSecretKey = (&self.secret_key).into();
608        Ok(expanded.raw_sign::<Sha512>(message, &self.verifying_key))
609    }
610}
611
612/// Equivalent to [`SigningKey::sign_prehashed`] with `context` set to [`None`].
613///
614/// # Note
615///
616/// The RFC only permits SHA-512 to be used for prehashing. This function technically works, and is
617/// probably safe to use, with any secure hash function with 512-bit digests, but anything outside
618/// of SHA-512 is NOT specification-compliant. We expose [`crate::Sha512`] for user convenience.
619#[cfg(feature = "digest")]
620impl<D> DigestSigner<D, Signature> for SigningKey
621where
622    D: Digest<OutputSize = U64> + Update,
623{
624    fn try_sign_digest<F: Fn(&mut D) -> Result<(), SignatureError>>(
625        &self,
626        f: F,
627    ) -> Result<Signature, SignatureError> {
628        let mut digest = D::new();
629        f(&mut digest)?;
630        self.sign_prehashed(digest, None)
631    }
632}
633
634/// Equivalent to [`SigningKey::sign_prehashed`] with `context` set to [`Some`]
635/// containing `self.value()`.
636///
637/// # Note
638///
639/// The RFC only permits SHA-512 to be used for prehashing. This function technically works, and is
640/// probably safe to use, with any secure hash function with 512-bit digests, but anything outside
641/// of SHA-512 is NOT specification-compliant. We expose [`crate::Sha512`] for user convenience.
642#[cfg(feature = "digest")]
643impl<D> DigestSigner<D, Signature> for Context<'_, '_, SigningKey>
644where
645    D: Digest<OutputSize = U64> + Update,
646{
647    fn try_sign_digest<F: Fn(&mut D) -> Result<(), SignatureError>>(
648        &self,
649        f: F,
650    ) -> Result<Signature, SignatureError> {
651        let mut digest = D::new();
652        f(&mut digest)?;
653        self.key().sign_prehashed(digest, Some(self.value()))
654    }
655}
656
657impl Verifier<Signature> for SigningKey {
658    /// Verify a signature on a message with this signing key's public key.
659    fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), SignatureError> {
660        self.verifying_key.verify(message, signature)
661    }
662}
663
664impl MultipartVerifier<Signature> for SigningKey {
665    fn multipart_verify(
666        &self,
667        message: &[&[u8]],
668        signature: &Signature,
669    ) -> Result<(), SignatureError> {
670        self.verifying_key.multipart_verify(message, signature)
671    }
672}
673
674impl From<SecretKey> for SigningKey {
675    #[inline]
676    fn from(secret: SecretKey) -> Self {
677        Self::from_bytes(&secret)
678    }
679}
680
681impl From<&SecretKey> for SigningKey {
682    #[inline]
683    fn from(secret: &SecretKey) -> Self {
684        Self::from_bytes(secret)
685    }
686}
687
688impl TryFrom<&[u8]> for SigningKey {
689    type Error = SignatureError;
690
691    fn try_from(bytes: &[u8]) -> Result<SigningKey, SignatureError> {
692        SecretKey::try_from(bytes)
693            .map(|bytes| Self::from_bytes(&bytes))
694            .map_err(|_| {
695                InternalError::BytesLength {
696                    name: "SecretKey",
697                    length: SECRET_KEY_LENGTH,
698                }
699                .into()
700            })
701    }
702}
703
704impl ConstantTimeEq for SigningKey {
705    fn ct_eq(&self, other: &Self) -> Choice {
706        self.secret_key.ct_eq(&other.secret_key)
707    }
708}
709
710impl PartialEq for SigningKey {
711    fn eq(&self, other: &Self) -> bool {
712        self.ct_eq(other).into()
713    }
714}
715
716impl Eq for SigningKey {}
717
718#[cfg(feature = "zeroize")]
719impl Drop for SigningKey {
720    fn drop(&mut self) {
721        self.secret_key.zeroize();
722    }
723}
724
725#[cfg(feature = "zeroize")]
726impl ZeroizeOnDrop for SigningKey {}
727
728#[cfg(all(feature = "alloc", feature = "pkcs8"))]
729impl pkcs8::EncodePrivateKey for SigningKey {
730    fn to_pkcs8_der(&self) -> pkcs8::Result<pkcs8::SecretDocument> {
731        pkcs8::KeypairBytes::from(self).to_pkcs8_der()
732    }
733}
734
735#[cfg(feature = "pkcs8")]
736impl TryFrom<pkcs8::KeypairBytes> for SigningKey {
737    type Error = pkcs8::Error;
738
739    fn try_from(pkcs8_key: pkcs8::KeypairBytes) -> pkcs8::Result<Self> {
740        SigningKey::try_from(&pkcs8_key)
741    }
742}
743
744#[cfg(feature = "pkcs8")]
745impl TryFrom<&pkcs8::KeypairBytes> for SigningKey {
746    type Error = pkcs8::Error;
747
748    fn try_from(pkcs8_key: &pkcs8::KeypairBytes) -> pkcs8::Result<Self> {
749        let signing_key = SigningKey::from_bytes(&pkcs8_key.secret_key);
750
751        // Validate the public key in the PKCS#8 document if present
752        if let Some(public_bytes) = &pkcs8_key.public_key {
753            let expected_verifying_key = VerifyingKey::from_bytes(public_bytes.as_ref())
754                .map_err(|_| pkcs8::Error::KeyMalformed(pkcs8::KeyError::Invalid))?;
755
756            if signing_key.verifying_key() != expected_verifying_key {
757                return Err(pkcs8::Error::KeyMalformed(pkcs8::KeyError::Invalid));
758            }
759        }
760
761        Ok(signing_key)
762    }
763}
764
765#[cfg(feature = "pkcs8")]
766impl pkcs8::spki::SignatureAlgorithmIdentifier for SigningKey {
767    type Params = pkcs8::spki::der::AnyRef<'static>;
768
769    const SIGNATURE_ALGORITHM_IDENTIFIER: pkcs8::spki::AlgorithmIdentifier<Self::Params> =
770        <Signature as pkcs8::spki::AssociatedAlgorithmIdentifier>::ALGORITHM_IDENTIFIER;
771}
772
773#[cfg(feature = "pkcs8")]
774impl From<SigningKey> for pkcs8::KeypairBytes {
775    fn from(signing_key: SigningKey) -> pkcs8::KeypairBytes {
776        pkcs8::KeypairBytes::from(&signing_key)
777    }
778}
779
780#[cfg(feature = "pkcs8")]
781impl From<&SigningKey> for pkcs8::KeypairBytes {
782    fn from(signing_key: &SigningKey) -> pkcs8::KeypairBytes {
783        pkcs8::KeypairBytes {
784            secret_key: signing_key.to_bytes(),
785            public_key: Some(pkcs8::PublicKeyBytes(signing_key.verifying_key.to_bytes())),
786        }
787    }
788}
789
790#[cfg(feature = "pkcs8")]
791impl TryFrom<pkcs8::PrivateKeyInfoRef<'_>> for SigningKey {
792    type Error = pkcs8::Error;
793
794    fn try_from(private_key: pkcs8::PrivateKeyInfoRef<'_>) -> pkcs8::Result<Self> {
795        pkcs8::KeypairBytes::try_from(private_key)?.try_into()
796    }
797}
798
799#[cfg(feature = "serde")]
800impl Serialize for SigningKey {
801    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
802    where
803        S: Serializer,
804    {
805        serializer.serialize_bytes(&self.secret_key)
806    }
807}
808
809#[cfg(feature = "serde")]
810impl<'d> Deserialize<'d> for SigningKey {
811    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
812    where
813        D: Deserializer<'d>,
814    {
815        struct SigningKeyVisitor;
816
817        impl<'de> serde::de::Visitor<'de> for SigningKeyVisitor {
818            type Value = SigningKey;
819
820            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
821                write!(formatter, "An ed25519 signing (private) key")
822            }
823
824            fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
825                SigningKey::try_from(bytes).map_err(E::custom)
826            }
827
828            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
829            where
830                A: serde::de::SeqAccess<'de>,
831            {
832                let mut bytes = [0u8; 32];
833                #[allow(clippy::needless_range_loop)]
834                for i in 0..32 {
835                    bytes[i] = seq
836                        .next_element()?
837                        .ok_or_else(|| serde::de::Error::invalid_length(i, &"expected 32 bytes"))?;
838                }
839
840                let remaining = (0..)
841                    .map(|_| seq.next_element::<u8>())
842                    .take_while(|el| matches!(el, Ok(Some(_))))
843                    .count();
844
845                if remaining > 0 {
846                    return Err(serde::de::Error::invalid_length(
847                        32 + remaining,
848                        &"expected 32 bytes",
849                    ));
850                }
851
852                Ok(SigningKey::from(bytes))
853            }
854        }
855
856        deserializer.deserialize_bytes(SigningKeyVisitor)
857    }
858}
859
860/// The spec-compliant way to define an expanded secret key. This computes `SHA512(sk)`, clamps the
861/// first 32 bytes and uses it as a scalar, and uses the second 32 bytes as a domain separator for
862/// hashing.
863impl From<&SecretKey> for ExpandedSecretKey {
864    #[allow(clippy::unwrap_used)]
865    fn from(secret_key: &SecretKey) -> ExpandedSecretKey {
866        let hash = Sha512::default().chain_update(secret_key).finalize();
867        ExpandedSecretKey::from_bytes(hash.as_ref())
868    }
869}
870
871//
872// Signing functions. These are pub(crate) so that the `hazmat` module can use them
873//
874
875impl ExpandedSecretKey {
876    /// The plain, non-prehashed, signing function for Ed25519. `CtxDigest` is the digest used to
877    /// calculate the pseudorandomness needed for signing. According to the spec, `CtxDigest =
878    /// Sha512`, and `self` is derived via the method defined in `impl From<&SigningKey> for
879    /// ExpandedSecretKey`.
880    ///
881    /// This definition is loose in its parameters so that end-users of the `hazmat` module can
882    /// change how the `ExpandedSecretKey` is calculated and which hash function to use.
883    #[allow(non_snake_case)]
884    #[allow(clippy::unwrap_used)]
885    #[inline(always)]
886    pub(crate) fn raw_sign<CtxDigest>(
887        &self,
888        message: &[&[u8]],
889        verifying_key: &VerifyingKey,
890    ) -> Signature
891    where
892        CtxDigest: Digest<OutputSize = U64>,
893    {
894        // OK unwrap, update can't fail.
895        self.raw_sign_byupdate(
896            |h: &mut CtxDigest| {
897                message.iter().for_each(|slice| h.update(slice));
898                Ok(())
899            },
900            verifying_key,
901        )
902        .unwrap()
903    }
904
905    /// Sign a message provided in parts. The `msg_update` closure will be called twice to hash the
906    /// message parts. This closure MUST leave its hasher in the same state (i.e., must hash the
907    /// same values) after both calls. Otherwise it will produce an invalid signature.
908    #[allow(non_snake_case)]
909    #[inline(always)]
910    pub(crate) fn raw_sign_byupdate<CtxDigest, F>(
911        &self,
912        msg_update: F,
913        verifying_key: &VerifyingKey,
914    ) -> Result<Signature, SignatureError>
915    where
916        CtxDigest: Digest<OutputSize = U64>,
917        F: Fn(&mut CtxDigest) -> Result<(), SignatureError>,
918    {
919        let mut h = CtxDigest::new();
920
921        h.update(self.hash_prefix);
922        msg_update(&mut h)?;
923
924        let r = Scalar::from_hash(h);
925        let R: CompressedEdwardsY = EdwardsPoint::mul_base(&r).compress();
926
927        h = CtxDigest::new();
928        h.update(R.as_bytes());
929        h.update(verifying_key.as_bytes());
930        msg_update(&mut h)?;
931
932        let k = Scalar::from_hash(h);
933        let s: Scalar = (k * self.scalar) + r;
934
935        Ok(InternalSignature { R, s }.into())
936    }
937
938    /// The prehashed signing function for Ed25519 (i.e., Ed25519ph). `CtxDigest` is the digest
939    /// function used to calculate the pseudorandomness needed for signing. `MsgDigest` is the
940    /// digest function used to hash the signed message. According to the spec, `MsgDigest =
941    /// CtxDigest = Sha512`, and `self` is derived via the method defined in `impl
942    /// From<&SigningKey> for ExpandedSecretKey`.
943    ///
944    /// This definition is loose in its parameters so that end-users of the `hazmat` module can
945    /// change how the `ExpandedSecretKey` is calculated and which `CtxDigest` function to use.
946    #[cfg(feature = "digest")]
947    #[allow(non_snake_case)]
948    #[inline(always)]
949    pub(crate) fn raw_sign_prehashed<CtxDigest, MsgDigest>(
950        &self,
951        prehashed_message: MsgDigest,
952        verifying_key: &VerifyingKey,
953        context: Option<&[u8]>,
954    ) -> Result<Signature, SignatureError>
955    where
956        CtxDigest: Digest<OutputSize = U64>,
957        MsgDigest: Digest<OutputSize = U64>,
958    {
959        let mut prehash: [u8; 64] = [0u8; 64];
960
961        let ctx: &[u8] = context.unwrap_or(b""); // By default, the context is an empty string.
962
963        if ctx.len() > 255 {
964            return Err(SignatureError::from(InternalError::PrehashedContextLength));
965        }
966
967        let ctx_len: u8 = ctx.len() as u8;
968
969        // Get the result of the pre-hashed message.
970        prehash.copy_from_slice(prehashed_message.finalize().as_slice());
971
972        // This is the dumbest, ten-years-late, non-admission of fucking up the
973        // domain separation I have ever seen.  Why am I still required to put
974        // the upper half "prefix" of the hashed "secret key" in here?  Why
975        // can't the user just supply their own nonce and decide for themselves
976        // whether or not they want a deterministic signature scheme?  Why does
977        // the message go into what's ostensibly the signature domain separation
978        // hash?  Why wasn't there always a way to provide a context string?
979        //
980        // ...
981        //
982        // This is a really fucking stupid bandaid, and the damned scheme is
983        // still bleeding from malleability, for fuck's sake.
984        let mut h = CtxDigest::new()
985            .chain_update(b"SigEd25519 no Ed25519 collisions")
986            .chain_update([1]) // Ed25519ph
987            .chain_update([ctx_len])
988            .chain_update(ctx)
989            .chain_update(self.hash_prefix)
990            .chain_update(&prehash[..]);
991
992        let r = Scalar::from_hash(h);
993        let R: CompressedEdwardsY = EdwardsPoint::mul_base(&r).compress();
994
995        h = CtxDigest::new()
996            .chain_update(b"SigEd25519 no Ed25519 collisions")
997            .chain_update([1]) // Ed25519ph
998            .chain_update([ctx_len])
999            .chain_update(ctx)
1000            .chain_update(R.as_bytes())
1001            .chain_update(verifying_key.as_bytes())
1002            .chain_update(&prehash[..]);
1003
1004        let k = Scalar::from_hash(h);
1005        let s: Scalar = (k * self.scalar) + r;
1006
1007        Ok(InternalSignature { R, s }.into())
1008    }
1009}