rtci-crypto 0.5.0

Provider-neutral cryptography interface of a sans-I/O WebRTC stack, with ring and aws-lc-rs providers
Documentation
//! Deterministic ECDSA (RFC 6979) for a certificate's signing key.
//!
//! RFC 8446 appendix C.3: "It is RECOMMENDED that implementations implement "deterministic
//! ECDSA" as specified in [RFC6979]." Neither provider signs that way: ring and AWS-LC draw the
//! nonce `k` from their random source, mixed with the private key and the digest (a hedged
//! nonce, as BoringSSL's `crypto/fipsmodule/ecdsa/ecdsa.cc.inc` does). RFC 9846 (Standards
//! Track, July 2026), which obsoletes RFC 8446, keeps the recommendation in its appendix C.3 and
//! adds: "Note that purely deterministic Elliptic Curve Cryptography (ECC) signatures such as
//! deterministic ECDSA and EdDSA may be vulnerable to certain side-channel and fault injection
//! attacks in easily accessible Internet of Things (IoT) devices." The providers' hedged nonce
//! is therefore the
//! default, and the RFC 6979 form is available where it is asked for
//! (`SettingEngineBuilder::with_deterministic_ecdsa` in `rtci`, on in its `StrictRfc` profile).
//!
//! The RFC 6979 signer is RustCrypto's (`p256` / `p384` with `ecdsa`), built only with this
//! crate's `ecdsa-rfc6979` feature, which is off by default. [`deterministic_ecdsa`] exists in
//! every build; without the feature it refuses an ECDSA key with an error that names the
//! feature, so that a configuration asking for RFC 6979 never signs another way unseen.

use std::sync::Arc;

use crate::{CryptoError, SignatureScheme, SigningKey};

/// Whether this build signs ECDSA by RFC 6979 when asked to: the `ecdsa-rfc6979` feature.
pub const DETERMINISTIC_ECDSA: bool = cfg!(feature = "ecdsa-rfc6979");

/// The ECDSA schemes [`deterministic_ecdsa`] signs by RFC 6979: P-256 with SHA-256 and P-384
/// with SHA-384 (TLS 1.3's `ecdsa_secp256r1_sha256` and `ecdsa_secp384r1_sha384`).
pub const DETERMINISTIC_ECDSA_SCHEMES: [SignatureScheme; 2] = [
    SignatureScheme::EcdsaP256Sha256,
    SignatureScheme::EcdsaP384Sha384,
];

/// `key`, made to sign its ECDSA scheme by RFC 6979 (section 3.2: the nonce `k` derived from
/// the private key and the message hash by HMAC_DRBG, no randomness).
///
/// - `Ok(None)`: `key` signs neither of [`DETERMINISTIC_ECDSA_SCHEMES`] (an Ed25519 key, whose
///   signatures are deterministic already, or an RSA key); there is nothing to change.
/// - `Ok(Some(_))`: a key with the same public key that signs P-256 / SHA-256 or P-384 /
///   SHA-384 by RFC 6979 and hands every other scheme to `key`.
/// - `Err(_)`: `key` is an ECDSA key and this build has no RFC 6979 signer (the
///   `ecdsa-rfc6979` feature is off), or `key` does not export its PKCS#8 form (a key held in
///   a hardware module), or that form is not the key `key` says it is.
pub fn deterministic_ecdsa(
    key: Arc<dyn SigningKey>,
) -> Result<Option<Arc<dyn SigningKey>>, CryptoError> {
    let Some(scheme) = DETERMINISTIC_ECDSA_SCHEMES
        .into_iter()
        .find(|scheme| key.supports(*scheme))
    else {
        return Ok(None);
    };
    imp::wrap(key, scheme).map(Some)
}

#[cfg(not(feature = "ecdsa-rfc6979"))]
mod imp {
    use super::*;

    pub(super) fn wrap(
        _key: Arc<dyn SigningKey>,
        _scheme: SignatureScheme,
    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
        Err(CryptoError::Provider(
            "deterministic ECDSA (RFC 6979) needs the `ecdsa-rfc6979` feature of rtci-crypto \
             (`rtci` forwards it)"
                .into(),
        ))
    }
}

#[cfg(feature = "ecdsa-rfc6979")]
pub use imp::DeterministicEcdsaKey;

#[cfg(feature = "ecdsa-rfc6979")]
mod imp {
    use super::*;
    use crate::{CryptoAlgorithm, PublicKey, PublicKeyEncoding, SecretVec};
    use p256::ecdsa::signature::Signer;
    use p256::pkcs8::DecodePrivateKey;

    /// The private scalar, as RustCrypto keeps it: erased when dropped (`ecdsa::SigningKey`
    /// implements `ZeroizeOnDrop`).
    enum Curve {
        P256(p256::ecdsa::SigningKey),
        P384(p384::ecdsa::SigningKey),
    }

    /// A signing key whose ECDSA signatures follow RFC 6979; see [`deterministic_ecdsa`].
    pub struct DeterministicEcdsaKey {
        inner: Arc<dyn SigningKey>,
        curve: Curve,
    }

    pub(super) fn wrap(
        inner: Arc<dyn SigningKey>,
        scheme: SignatureScheme,
    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
        let pkcs8: SecretVec = inner.to_pkcs8_der()?.ok_or_else(|| {
            CryptoError::Provider(
                "deterministic ECDSA (RFC 6979) needs the key's PKCS#8 form; this key does \
                 not export it"
                    .into(),
            )
        })?;
        let (curve, public) = match scheme {
            SignatureScheme::EcdsaP256Sha256 => {
                let key = p256::ecdsa::SigningKey::from_pkcs8_der(pkcs8.as_ref())
                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
                let public = key.verifying_key().to_sec1_point(false).as_bytes().to_vec();
                (Curve::P256(key), public)
            }
            SignatureScheme::EcdsaP384Sha384 => {
                let key = p384::ecdsa::SigningKey::from_pkcs8_der(pkcs8.as_ref())
                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
                let public = key.verifying_key().to_sec1_point(false).as_bytes().to_vec();
                (Curve::P384(key), public)
            }
            _ => {
                return Err(CryptoError::UnsupportedAlgorithm(
                    CryptoAlgorithm::Signature(scheme),
                ));
            }
        };
        // The PKCS#8 form must be the key the provider signs with, or the certificate would
        // name one key and the handshake prove another.
        let PublicKey { encoding, bytes } = inner.public_key();
        if encoding != PublicKeyEncoding::EcUncompressedPoint || bytes != public.as_slice() {
            return Err(CryptoError::InvalidPrivateKey);
        }
        Ok(Arc::new(DeterministicEcdsaKey { inner, curve }))
    }

    impl SigningKey for DeterministicEcdsaKey {
        fn supports(&self, scheme: SignatureScheme) -> bool {
            self.inner.supports(scheme)
        }

        fn public_key(&self) -> PublicKey<'_> {
            self.inner.public_key()
        }

        fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
            let failed = |_| CryptoError::Provider("signature generation failed".into());
            match (&self.curve, scheme) {
                (Curve::P256(key), SignatureScheme::EcdsaP256Sha256) => {
                    let signature: p256::ecdsa::DerSignature =
                        key.try_sign(message).map_err(failed)?;
                    Ok(signature.as_bytes().to_vec())
                }
                (Curve::P384(key), SignatureScheme::EcdsaP384Sha384) => {
                    let signature: p384::ecdsa::DerSignature =
                        key.try_sign(message).map_err(failed)?;
                    Ok(signature.as_bytes().to_vec())
                }
                _ => self.inner.sign(scheme, message),
            }
        }

        fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
            self.inner.to_pkcs8_der()
        }
    }
}

#[cfg(test)]
#[path = "rfc6979_test.rs"]
mod rfc6979_test;