Skip to main content

rtci_crypto/
rfc6979.rs

1//! Deterministic ECDSA (RFC 6979) for a certificate's signing key.
2//!
3//! RFC 8446 appendix C.3: "It is RECOMMENDED that implementations implement "deterministic
4//! ECDSA" as specified in [RFC6979]." Neither provider signs that way: ring and AWS-LC draw the
5//! nonce `k` from their random source, mixed with the private key and the digest (a hedged
6//! nonce, as BoringSSL's `crypto/fipsmodule/ecdsa/ecdsa.cc.inc` does). RFC 9846 (Standards
7//! Track, July 2026), which obsoletes RFC 8446, keeps the recommendation in its appendix C.3 and
8//! adds: "Note that purely deterministic Elliptic Curve Cryptography (ECC) signatures such as
9//! deterministic ECDSA and EdDSA may be vulnerable to certain side-channel and fault injection
10//! attacks in easily accessible Internet of Things (IoT) devices." The providers' hedged nonce
11//! is therefore the
12//! default, and the RFC 6979 form is available where it is asked for
13//! (`SettingEngineBuilder::with_deterministic_ecdsa` in `rtci`, on in its `StrictRfc` profile).
14//!
15//! The RFC 6979 signer is RustCrypto's (`p256` / `p384` with `ecdsa`), built only with this
16//! crate's `ecdsa-rfc6979` feature, which is off by default. [`deterministic_ecdsa`] exists in
17//! every build; without the feature it refuses an ECDSA key with an error that names the
18//! feature, so that a configuration asking for RFC 6979 never signs another way unseen.
19
20use std::sync::Arc;
21
22use crate::{CryptoError, SignatureScheme, SigningKey};
23
24/// Whether this build signs ECDSA by RFC 6979 when asked to: the `ecdsa-rfc6979` feature.
25pub const DETERMINISTIC_ECDSA: bool = cfg!(feature = "ecdsa-rfc6979");
26
27/// The ECDSA schemes [`deterministic_ecdsa`] signs by RFC 6979: P-256 with SHA-256 and P-384
28/// with SHA-384 (TLS 1.3's `ecdsa_secp256r1_sha256` and `ecdsa_secp384r1_sha384`).
29pub const DETERMINISTIC_ECDSA_SCHEMES: [SignatureScheme; 2] = [
30    SignatureScheme::EcdsaP256Sha256,
31    SignatureScheme::EcdsaP384Sha384,
32];
33
34/// `key`, made to sign its ECDSA scheme by RFC 6979 (section 3.2: the nonce `k` derived from
35/// the private key and the message hash by HMAC_DRBG, no randomness).
36///
37/// - `Ok(None)`: `key` signs neither of [`DETERMINISTIC_ECDSA_SCHEMES`] (an Ed25519 key, whose
38///   signatures are deterministic already, or an RSA key); there is nothing to change.
39/// - `Ok(Some(_))`: a key with the same public key that signs P-256 / SHA-256 or P-384 /
40///   SHA-384 by RFC 6979 and hands every other scheme to `key`.
41/// - `Err(_)`: `key` is an ECDSA key and this build has no RFC 6979 signer (the
42///   `ecdsa-rfc6979` feature is off), or `key` does not export its PKCS#8 form (a key held in
43///   a hardware module), or that form is not the key `key` says it is.
44pub fn deterministic_ecdsa(
45    key: Arc<dyn SigningKey>,
46) -> Result<Option<Arc<dyn SigningKey>>, CryptoError> {
47    let Some(scheme) = DETERMINISTIC_ECDSA_SCHEMES
48        .into_iter()
49        .find(|scheme| key.supports(*scheme))
50    else {
51        return Ok(None);
52    };
53    imp::wrap(key, scheme).map(Some)
54}
55
56#[cfg(not(feature = "ecdsa-rfc6979"))]
57mod imp {
58    use super::*;
59
60    pub(super) fn wrap(
61        _key: Arc<dyn SigningKey>,
62        _scheme: SignatureScheme,
63    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
64        Err(CryptoError::Provider(
65            "deterministic ECDSA (RFC 6979) needs the `ecdsa-rfc6979` feature of rtci-crypto \
66             (`rtci` forwards it)"
67                .into(),
68        ))
69    }
70}
71
72#[cfg(feature = "ecdsa-rfc6979")]
73pub use imp::DeterministicEcdsaKey;
74
75#[cfg(feature = "ecdsa-rfc6979")]
76mod imp {
77    use super::*;
78    use crate::{CryptoAlgorithm, PublicKey, PublicKeyEncoding, SecretVec};
79    use p256::ecdsa::signature::Signer;
80    use p256::pkcs8::DecodePrivateKey;
81
82    /// The private scalar, as RustCrypto keeps it: erased when dropped (`ecdsa::SigningKey`
83    /// implements `ZeroizeOnDrop`).
84    enum Curve {
85        P256(p256::ecdsa::SigningKey),
86        P384(p384::ecdsa::SigningKey),
87    }
88
89    /// A signing key whose ECDSA signatures follow RFC 6979; see [`deterministic_ecdsa`].
90    pub struct DeterministicEcdsaKey {
91        inner: Arc<dyn SigningKey>,
92        curve: Curve,
93    }
94
95    pub(super) fn wrap(
96        inner: Arc<dyn SigningKey>,
97        scheme: SignatureScheme,
98    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
99        let pkcs8: SecretVec = inner.to_pkcs8_der()?.ok_or_else(|| {
100            CryptoError::Provider(
101                "deterministic ECDSA (RFC 6979) needs the key's PKCS#8 form; this key does \
102                 not export it"
103                    .into(),
104            )
105        })?;
106        let (curve, public) = match scheme {
107            SignatureScheme::EcdsaP256Sha256 => {
108                let key = p256::ecdsa::SigningKey::from_pkcs8_der(pkcs8.as_ref())
109                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
110                let public = key.verifying_key().to_sec1_point(false).as_bytes().to_vec();
111                (Curve::P256(key), public)
112            }
113            SignatureScheme::EcdsaP384Sha384 => {
114                let key = p384::ecdsa::SigningKey::from_pkcs8_der(pkcs8.as_ref())
115                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
116                let public = key.verifying_key().to_sec1_point(false).as_bytes().to_vec();
117                (Curve::P384(key), public)
118            }
119            _ => {
120                return Err(CryptoError::UnsupportedAlgorithm(
121                    CryptoAlgorithm::Signature(scheme),
122                ));
123            }
124        };
125        // The PKCS#8 form must be the key the provider signs with, or the certificate would
126        // name one key and the handshake prove another.
127        let PublicKey { encoding, bytes } = inner.public_key();
128        if encoding != PublicKeyEncoding::EcUncompressedPoint || bytes != public.as_slice() {
129            return Err(CryptoError::InvalidPrivateKey);
130        }
131        Ok(Arc::new(DeterministicEcdsaKey { inner, curve }))
132    }
133
134    impl SigningKey for DeterministicEcdsaKey {
135        fn supports(&self, scheme: SignatureScheme) -> bool {
136            self.inner.supports(scheme)
137        }
138
139        fn public_key(&self) -> PublicKey<'_> {
140            self.inner.public_key()
141        }
142
143        fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
144            let failed = |_| CryptoError::Provider("signature generation failed".into());
145            match (&self.curve, scheme) {
146                (Curve::P256(key), SignatureScheme::EcdsaP256Sha256) => {
147                    let signature: p256::ecdsa::DerSignature =
148                        key.try_sign(message).map_err(failed)?;
149                    Ok(signature.as_bytes().to_vec())
150                }
151                (Curve::P384(key), SignatureScheme::EcdsaP384Sha384) => {
152                    let signature: p384::ecdsa::DerSignature =
153                        key.try_sign(message).map_err(failed)?;
154                    Ok(signature.as_bytes().to_vec())
155                }
156                _ => self.inner.sign(scheme, message),
157            }
158        }
159
160        fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
161            self.inner.to_pkcs8_der()
162        }
163    }
164}
165
166#[cfg(test)]
167#[path = "rfc6979_test.rs"]
168mod rfc6979_test;