rtci-crypto 0.5.0

Provider-neutral cryptography interface of a sans-I/O WebRTC stack, with ring and aws-lc-rs providers
Documentation
//! RFC 8446 appendix C.3 (deterministic ECDSA, RFC 6979): the signer against the RFC 6979
//! appendix A.2.5 and A.2.6 vectors, and the key `deterministic_ecdsa` makes of a provider key.

#[cfg(any(feature = "crypto-ring", feature = "ecdsa-rfc6979"))]
use super::*;

#[cfg(feature = "ecdsa-rfc6979")]
fn unhex(text: &str) -> Vec<u8> {
    let text: String = text.split_whitespace().collect();
    (0..text.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap())
        .collect()
}

#[cfg(feature = "crypto-ring")]
fn provider() -> std::sync::Arc<dyn crate::RTCCryptoProvider> {
    crate::default_provider().unwrap()
}

/// Without the `ecdsa-rfc6979` feature an ECDSA key is refused with an error that names it;
/// a key with no ECDSA scheme is left as it is.
#[cfg(all(not(feature = "ecdsa-rfc6979"), feature = "crypto-ring"))]
#[test]
fn without_the_feature_an_ecdsa_key_is_refused_by_name() {
    const { assert!(!DETERMINISTIC_ECDSA) };
    let crypto = provider();
    let ecdsa = crypto
        .crypto()
        .generate_signing_key(SignatureScheme::EcdsaP256Sha256)
        .unwrap();
    match deterministic_ecdsa(ecdsa) {
        Err(CryptoError::Provider(message)) => assert!(message.contains("ecdsa-rfc6979")),
        Err(other) => panic!("another error: {other:?}"),
        Ok(_) => panic!("an ECDSA key was taken without an RFC 6979 signer"),
    }
    let ed25519 = crypto
        .crypto()
        .generate_signing_key(SignatureScheme::Ed25519)
        .unwrap();
    assert!(deterministic_ecdsa(ed25519).unwrap().is_none());
}

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

    /// RFC 6979 appendix A.2.5: ECDSA, 256 bits (prime field), NIST P-256, SHA-256, messages
    /// "sample" and "test": (r, s) byte for byte.
    #[test]
    fn the_p256_signatures_are_rfc_6979_a_2_5s() {
        let key = p256::ecdsa::SigningKey::from_slice(&unhex(
            "C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721",
        ))
        .unwrap();
        assert_eq!(
            key.verifying_key().to_sec1_point(false).as_bytes(),
            unhex(
                "04 60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6
                    7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299"
            )
            .as_slice()
        );
        for (message, r, s) in [
            (
                "sample",
                "EFD48B2AACB6A8FD1140DD9CD45E81D69D2C877B56AAF991C34D0EA84EAF3716",
                "F7CB1C942D657C41D436C7A1B6E29F65F3E900DBB9AFF4064DC4AB2F843ACDA8",
            ),
            (
                "test",
                "F1ABB023518351CD71D881567B1EA663ED3EFCF6C5132B354F28D3B0B7D38367",
                "019F4113742A2B14BD25926B49C649155F267E60D3814B4C0CC84250E46F0083",
            ),
        ] {
            let signature: p256::ecdsa::Signature = key.sign(message.as_bytes());
            assert_eq!(
                signature.to_bytes().as_slice(),
                [unhex(r), unhex(s)].concat().as_slice(),
                "{message}"
            );
        }
    }

    /// RFC 6979 appendix A.2.6: ECDSA, 384 bits (prime field), NIST P-384, SHA-384, messages
    /// "sample" and "test".
    #[test]
    fn the_p384_signatures_are_rfc_6979_a_2_6s() {
        let key = p384::ecdsa::SigningKey::from_slice(&unhex(
            "6B9D3DAD2E1B8C1C05B19875B6659F4DE23C3B667BF297BA9AA47740787137D8
             96D5724E4C70A825F872C9EA60D2EDF5",
        ))
        .unwrap();
        assert_eq!(
            key.verifying_key().to_sec1_point(false).as_bytes(),
            unhex(
                "04 EC3A4E415B4E19A4568618029F427FA5DA9A8BC4AE92E02E06AAE5286B300C64
                    DEF8F0EA9055866064A254515480BC13
                    8015D9B72D7D57244EA8EF9AC0C621896708A59367F9DFB9F54CA84B3F1C9DB1
                    288B231C3AE0D4FE7344FD2533264720"
            )
            .as_slice()
        );
        for (message, r, s) in [
            (
                "sample",
                "94EDBB92A5ECB8AAD4736E56C691916B3F88140666CE9FA73D64C4EA95AD133C
                 81A648152E44ACF96E36DD1E80FABE46",
                "99EF4AEB15F178CEA1FE40DB2603138F130E740A19624526203B6351D0A3A94F
                 A329C145786E679E7B82C71A38628AC8",
            ),
            (
                "test",
                "8203B63D3C853E8D77227FB377BCF7B7B772E97892A80F36AB775D509D7A5FEB
                 0542A7F0812998DA8F1DD3CA3CF023DB",
                "DDD0760448D42D8A43AF45AF836FCE4DE8BE06B485E9B61B827C2F13173923E0
                 6A739F040649A667BF3B828246BAA5A5",
            ),
        ] {
            let signature: p384::ecdsa::Signature = key.sign(message.as_bytes());
            assert_eq!(
                signature.to_bytes().as_slice(),
                [unhex(r), unhex(s)].concat().as_slice(),
                "{message}"
            );
        }
    }

    /// A key that holds a PKCS#8 document and a public key, and signs nothing itself: what
    /// `deterministic_ecdsa` reads of a provider key, for a curve no provider generates
    /// (P-384).
    struct Pkcs8Only {
        scheme: SignatureScheme,
        pkcs8: SecretVec,
        public: Vec<u8>,
    }

    impl SigningKey for Pkcs8Only {
        fn supports(&self, scheme: SignatureScheme) -> bool {
            scheme == self.scheme
        }
        fn public_key(&self) -> PublicKey<'_> {
            PublicKey {
                encoding: PublicKeyEncoding::EcUncompressedPoint,
                bytes: &self.public,
            }
        }
        fn sign(&self, _: SignatureScheme, _: &[u8]) -> Result<Vec<u8>, CryptoError> {
            Err(CryptoError::Provider("signs nothing".into()))
        }
        fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
            Ok(Some(self.pkcs8.clone()))
        }
    }

    /// The key made of an A.2.6 key in PKCS#8 signs ecdsa_secp384r1_sha384 with the RFC 6979
    /// signature, DER-encoded as TLS carries it.
    #[test]
    fn a_p384_key_in_pkcs8_signs_by_rfc_6979() {
        use p384::pkcs8::EncodePrivateKey;
        let scalar = unhex(
            "6B9D3DAD2E1B8C1C05B19875B6659F4DE23C3B667BF297BA9AA47740787137D8
             96D5724E4C70A825F872C9EA60D2EDF5",
        );
        let reference = p384::ecdsa::SigningKey::from_slice(&scalar).unwrap();
        let key = Pkcs8Only {
            scheme: SignatureScheme::EcdsaP384Sha384,
            pkcs8: SecretVec::new(reference.to_pkcs8_der().unwrap().as_bytes().to_vec()),
            public: reference
                .verifying_key()
                .to_sec1_point(false)
                .as_bytes()
                .to_vec(),
        };
        let deterministic = deterministic_ecdsa(std::sync::Arc::new(key))
            .unwrap()
            .expect("an ECDSA key");
        let signed = deterministic
            .sign(SignatureScheme::EcdsaP384Sha384, b"sample")
            .unwrap();
        let expected: p384::ecdsa::DerSignature = reference.sign(b"sample");
        assert_eq!(signed, expected.as_bytes());
        let fixed = p384::ecdsa::Signature::from_der(&signed).unwrap();
        assert_eq!(
            fixed.to_bytes().as_slice(),
            unhex(
                "94EDBB92A5ECB8AAD4736E56C691916B3F88140666CE9FA73D64C4EA95AD133C
                 81A648152E44ACF96E36DD1E80FABE46
                 99EF4AEB15F178CEA1FE40DB2603138F130E740A19624526203B6351D0A3A94F
                 A329C145786E679E7B82C71A38628AC8"
            )
            .as_slice()
        );
    }

    /// A PKCS#8 document that is not the key the provider key names is refused.
    #[test]
    fn a_pkcs8_form_of_another_key_is_refused() {
        use p384::pkcs8::EncodePrivateKey;
        let one = p384::ecdsa::SigningKey::from_slice(&[1; 48]).unwrap();
        let two = p384::ecdsa::SigningKey::from_slice(&[2; 48]).unwrap();
        let key = Pkcs8Only {
            scheme: SignatureScheme::EcdsaP384Sha384,
            pkcs8: SecretVec::new(one.to_pkcs8_der().unwrap().as_bytes().to_vec()),
            public: two.verifying_key().to_sec1_point(false).as_bytes().to_vec(),
        };
        assert!(matches!(
            deterministic_ecdsa(std::sync::Arc::new(key)),
            Err(CryptoError::InvalidPrivateKey)
        ));
    }

    /// A provider's P-256 key: the provider signs the same message differently each time (its
    /// hedged nonce); the key `deterministic_ecdsa` makes of it signs it the same way each
    /// time, the RFC 6979 signature of the key's scalar, which the provider verifies.
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn a_provider_p256_key_signs_by_rfc_6979_once_wrapped() {
        use p256::pkcs8::DecodePrivateKey;
        let crypto = provider();
        let crypto = crypto.crypto();
        let scheme = SignatureScheme::EcdsaP256Sha256;
        let key = crypto.generate_signing_key(scheme).unwrap();
        let message = b"CertificateVerify content";
        assert_ne!(
            key.sign(scheme, message).unwrap(),
            key.sign(scheme, message).unwrap(),
            "the provider's nonce is not deterministic"
        );
        let reference =
            p256::ecdsa::SigningKey::from_pkcs8_der(key.to_pkcs8_der().unwrap().unwrap().as_ref())
                .unwrap();
        let deterministic = deterministic_ecdsa(key.clone()).unwrap().expect("ECDSA");
        let first = deterministic.sign(scheme, message).unwrap();
        assert_eq!(first, deterministic.sign(scheme, message).unwrap());
        let expected: p256::ecdsa::DerSignature = reference.sign(message);
        assert_eq!(first, expected.as_bytes());
        crypto
            .verify_signature(scheme, deterministic.public_key(), message, &first)
            .unwrap();
        assert_eq!(deterministic.public_key().bytes, key.public_key().bytes);
        // Ed25519 is deterministic already: nothing to wrap.
        let ed25519 = crypto
            .generate_signing_key(SignatureScheme::Ed25519)
            .unwrap();
        assert!(deterministic_ecdsa(ed25519).unwrap().is_none());
        const { assert!(DETERMINISTIC_ECDSA) };
    }
}