Skip to main content

rustflexstack/security/
ecdsa_backend.rs

1//! ECDSA backend — signing with NIST P-256 (default), brainpoolP256r1,
2//! brainpoolP384r1 and NIST P-384 keys (the curves of the IEEE 1609.2
3//! PublicVerificationKey choices) and verification on the same curves.
4//!
5//! Uses the `p256` + `ecdsa` crates.  Keys are stored in an in-memory map
6//! keyed by sequential integer identifiers, mirroring the Python
7//! `PythonECDSABackend`.
8//!
9//! All public-key and signature representations use the IEEE 1609.2 /
10//! `security_asn` types so they can be embedded directly into certificates
11//! and signed messages without conversion.
12
13use p256::ecdsa::signature::Signer;
14use p256::ecdsa::signature::Verifier;
15use p256::ecdsa::{Signature, SigningKey, VerifyingKey};
16use sha2::{Digest, Sha256, Sha384};
17use std::collections::HashMap;
18
19use crate::security::security_asn::ieee1609_dot2_base_types::PublicVerificationKey;
20use crate::security::security_asn::ieee1609_dot2_base_types::Signature as Ieee1609Signature;
21use crate::security::security_asn::ieee1609_dot2_base_types::{
22    EccP256CurvePoint, EccP256CurvePointUncompressedP256, EccP384CurvePoint, EcdsaP256Signature,
23    EcdsaP384Signature,
24};
25
26/// Hash used with a verification key: SHA-384 for the 384-bit curves,
27/// SHA-256 otherwise (IEEE 1609.2 clause 5.3.1).
28pub fn key_uses_sha384(pk: &PublicVerificationKey) -> bool {
29    matches!(
30        pk,
31        PublicVerificationKey::ecdsaBrainpoolP384r1(_) | PublicVerificationKey::ecdsaNistP384(_)
32    )
33}
34
35/// SEC1 encoding of a 256-bit curve point (compressed or uncompressed).
36fn p256_sec1(point: &EccP256CurvePoint) -> Option<Vec<u8>> {
37    Some(match point {
38        EccP256CurvePoint::uncompressedP256(u) => [&[0x04], u.x.as_ref(), u.y.as_ref()].concat(),
39        EccP256CurvePoint::compressed_y_0(x) => [&[0x02], x.as_ref()].concat(),
40        EccP256CurvePoint::compressed_y_1(x) => [&[0x03], x.as_ref()].concat(),
41        _ => return None,
42    })
43}
44
45/// SEC1 encoding of a 384-bit curve point (compressed or uncompressed).
46fn p384_sec1(point: &EccP384CurvePoint) -> Option<Vec<u8>> {
47    Some(match point {
48        EccP384CurvePoint::uncompressedP384(u) => [&[0x04], u.x.as_ref(), u.y.as_ref()].concat(),
49        EccP384CurvePoint::compressed_y_0(x) => [&[0x02], x.as_ref()].concat(),
50        EccP384CurvePoint::compressed_y_1(x) => [&[0x03], x.as_ref()].concat(),
51        _ => return None,
52    })
53}
54
55/// r || s of a 256-bit signature; r is the x coordinate of R in any point form.
56fn p256_rs(sig: &EcdsaP256Signature) -> Option<Vec<u8>> {
57    let r = match &sig.r_sig {
58        EccP256CurvePoint::x_only(b)
59        | EccP256CurvePoint::compressed_y_0(b)
60        | EccP256CurvePoint::compressed_y_1(b) => b.as_ref(),
61        EccP256CurvePoint::uncompressedP256(u) => u.x.as_ref(),
62        _ => return None,
63    };
64    Some([r, sig.s_sig.as_ref()].concat())
65}
66
67/// r || s of a 384-bit signature; r is the x coordinate of R in any point form.
68fn p384_rs(sig: &EcdsaP384Signature) -> Option<Vec<u8>> {
69    let r = match &sig.r_sig {
70        EccP384CurvePoint::x_only(b)
71        | EccP384CurvePoint::compressed_y_0(b)
72        | EccP384CurvePoint::compressed_y_1(b) => b.as_ref(),
73        EccP384CurvePoint::uncompressedP384(u) => u.x.as_ref(),
74        _ => return None,
75    };
76    Some([r, sig.s_sig.as_ref()].concat())
77}
78
79/// ECQV public key extraction (SEC 4 v1.0 section 3.5, as profiled by IEEE
80/// Std 1609.2-2016 clause 5.3.2): Q_U = e * P_U + Q_CA on the curve of the
81/// issuer key (NIST P-256 or brainpoolP256r1). `e` is the big-endian integer
82/// hash of the implicit certificate (`Certificate::implicit_hash_integer`).
83pub fn reconstruct_public_key(
84    reconstruction_value: &EccP256CurvePoint,
85    issuer_key: &PublicVerificationKey,
86    e: &[u8; 32],
87) -> Option<PublicVerificationKey> {
88    let rv = p256_sec1(reconstruction_value)?;
89    match issuer_key {
90        PublicVerificationKey::ecdsaNistP256(point) => {
91            use p256::elliptic_curve::ff::PrimeField;
92            use p256::elliptic_curve::sec1::ToEncodedPoint;
93            let p_u = p256::PublicKey::from_sec1_bytes(&rv).ok()?;
94            let q_ca = p256::PublicKey::from_sec1_bytes(&p256_sec1(point)?).ok()?;
95            let e = Option::<p256::Scalar>::from(p256::Scalar::from_repr((*e).into()))?;
96            let q_u = p_u.to_projective() * e + q_ca.to_projective();
97            let encoded = p256::PublicKey::from_affine(q_u.to_affine())
98                .ok()?
99                .to_encoded_point(false);
100            Some(PublicVerificationKey::ecdsaNistP256(
101                EccP256CurvePoint::uncompressedP256(EccP256CurvePointUncompressedP256 {
102                    x: encoded.x()?.to_vec().into(),
103                    y: encoded.y()?.to_vec().into(),
104                }),
105            ))
106        }
107        PublicVerificationKey::ecdsaBrainpoolP256r1(point) => {
108            let q_u = bp256_reconstruct(&rv, &p256_sec1(point)?, e)?;
109            Some(PublicVerificationKey::ecdsaBrainpoolP256r1(
110                EccP256CurvePoint::uncompressedP256(EccP256CurvePointUncompressedP256 {
111                    x: q_u[1..33].to_vec().into(),
112                    y: q_u[33..65].to_vec().into(),
113                }),
114            ))
115        }
116        _ => None,
117    }
118}
119
120/// e * P_U + Q_CA on brainpoolP256r1, as an uncompressed SEC1 point.
121fn bp256_reconstruct(p_u: &[u8], q_ca: &[u8], e: &[u8; 32]) -> Option<Vec<u8>> {
122    use bp256::elliptic_curve::ff::PrimeField;
123    use bp256::elliptic_curve::sec1::{FromSec1Point, ToSec1Point};
124    let decode = |bytes: &[u8]| -> Option<bp256::r1::AffinePoint> {
125        let point = bp256::r1::Sec1Point::from_bytes(bytes).ok()?;
126        Option::from(bp256::r1::AffinePoint::from_sec1_point(&point))
127    };
128    let p_u = bp256::r1::ProjectivePoint::from(decode(p_u)?);
129    let q_ca = bp256::r1::ProjectivePoint::from(decode(q_ca)?);
130    let e = Option::<bp256::r1::Scalar>::from(bp256::r1::Scalar::from_repr((*e).into()))?;
131    let q_u = (p_u * e + q_ca).to_affine();
132    Some(q_u.to_sec1_point(false).as_bytes().to_vec())
133}
134
135/// ECDSA verification of a pre-computed digest on a brainpool curve (RustCrypto
136/// `ecdsa` 0.17 stack).
137macro_rules! brainpool_verify {
138    ($name:ident, $curve:ty) => {
139        fn $name(sec1: &[u8], rs: &[u8], digest: &[u8]) -> bool {
140            use ecdsa_v017::signature::hazmat::PrehashVerifier as _;
141            match (
142                ecdsa_v017::VerifyingKey::<$curve>::from_sec1_bytes(sec1),
143                ecdsa_v017::Signature::<$curve>::from_slice(rs),
144            ) {
145                (Ok(vk), Ok(sig)) => vk.verify_prehash(digest, &sig).is_ok(),
146                _ => false,
147            }
148        }
149    };
150}
151brainpool_verify!(verify_bp256, bp256::BrainpoolP256r1);
152brainpool_verify!(verify_bp384, bp384::BrainpoolP384r1);
153
154/// Curve of an own key pair (an IEEE 1609.2 PublicVerificationKey curve).
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub enum KeyAlgorithm {
157    NistP256,
158    BrainpoolP256r1,
159    BrainpoolP384r1,
160    NistP384,
161}
162
163#[derive(Clone, Debug)]
164enum OwnKey {
165    NistP256(SigningKey),
166    BrainpoolP256r1(ecdsa_v017::elliptic_curve::SecretKey<bp256::BrainpoolP256r1>),
167    BrainpoolP384r1(ecdsa_v017::elliptic_curve::SecretKey<bp384::BrainpoolP384r1>),
168    NistP384(p384::ecdsa::SigningKey),
169}
170
171/// IEEE 1609.2 point of a SEC1 encoding (02/03 || x, or 04 || x || y).
172fn p256_point(sec1: &[u8]) -> EccP256CurvePoint {
173    match sec1[0] {
174        0x02 => EccP256CurvePoint::compressed_y_0(sec1[1..33].to_vec().into()),
175        0x03 => EccP256CurvePoint::compressed_y_1(sec1[1..33].to_vec().into()),
176        _ => EccP256CurvePoint::uncompressedP256(EccP256CurvePointUncompressedP256 {
177            x: sec1[1..33].to_vec().into(),
178            y: sec1[33..65].to_vec().into(),
179        }),
180    }
181}
182
183fn p384_point(sec1: &[u8]) -> EccP384CurvePoint {
184    use crate::security::security_asn::ieee1609_dot2_base_types::EccP384CurvePointUncompressedP384;
185    match sec1[0] {
186        0x02 => EccP384CurvePoint::compressed_y_0(sec1[1..49].to_vec().into()),
187        0x03 => EccP384CurvePoint::compressed_y_1(sec1[1..49].to_vec().into()),
188        _ => EccP384CurvePoint::uncompressedP384(EccP384CurvePointUncompressedP384 {
189            x: sec1[1..49].to_vec().into(),
190            y: sec1[49..97].to_vec().into(),
191        }),
192    }
193}
194
195/// ECDSA backend managing own key pairs.
196#[derive(Clone, Debug)]
197pub struct EcdsaBackend {
198    keys: HashMap<usize, OwnKey>,
199    next_id: usize,
200}
201
202impl EcdsaBackend {
203    pub fn new() -> Self {
204        Self {
205            keys: HashMap::new(),
206            next_id: 0,
207        }
208    }
209
210    /// Generate a new P-256 key pair.  Returns the key identifier.
211    pub fn create_key(&mut self) -> usize {
212        self.create_key_with(KeyAlgorithm::NistP256)
213    }
214
215    /// Generate a new key pair on `algorithm`.  Returns the key identifier.
216    pub fn create_key_with(&mut self, algorithm: KeyAlgorithm) -> usize {
217        let mut rng = rand::thread_rng();
218        let key = match algorithm {
219            KeyAlgorithm::NistP256 => OwnKey::NistP256(SigningKey::random(&mut rng)),
220            KeyAlgorithm::BrainpoolP256r1 => OwnKey::BrainpoolP256r1(random_secret(&mut rng)),
221            KeyAlgorithm::BrainpoolP384r1 => OwnKey::BrainpoolP384r1(random_secret(&mut rng)),
222            KeyAlgorithm::NistP384 => OwnKey::NistP384(p384::ecdsa::SigningKey::random(&mut rng)),
223        };
224        let id = self.next_id;
225        self.keys.insert(id, key);
226        self.next_id += 1;
227        id
228    }
229
230    /// Curve of the key pair `id`.
231    pub fn algorithm(&self, id: usize) -> KeyAlgorithm {
232        match self.keys[&id] {
233            OwnKey::NistP256(_) => KeyAlgorithm::NistP256,
234            OwnKey::BrainpoolP256r1(_) => KeyAlgorithm::BrainpoolP256r1,
235            OwnKey::BrainpoolP384r1(_) => KeyAlgorithm::BrainpoolP384r1,
236            OwnKey::NistP384(_) => KeyAlgorithm::NistP384,
237        }
238    }
239
240    /// Return the public verification key in IEEE 1609.2 format.
241    /// Defaults to compressed format (compressed_y_0/1) per IEEE 1609.2 / ETSI TS 103 097.
242    pub fn get_public_key(&self, id: usize) -> PublicVerificationKey {
243        self.get_public_key_compressed(id, true)
244    }
245
246    /// Return the public verification key in IEEE 1609.2 format, optionally compressed.
247    pub fn get_public_key_compressed(&self, id: usize, compressed: bool) -> PublicVerificationKey {
248        use ecdsa_v017::elliptic_curve::sec1::ToSec1Point;
249        match &self.keys[&id] {
250            OwnKey::NistP256(sk) => PublicVerificationKey::ecdsaNistP256(p256_point(
251                sk.verifying_key().to_encoded_point(compressed).as_bytes(),
252            )),
253            OwnKey::BrainpoolP256r1(sk) => PublicVerificationKey::ecdsaBrainpoolP256r1(p256_point(
254                sk.public_key().to_sec1_point(compressed).as_bytes(),
255            )),
256            OwnKey::BrainpoolP384r1(sk) => PublicVerificationKey::ecdsaBrainpoolP384r1(p384_point(
257                sk.public_key().to_sec1_point(compressed).as_bytes(),
258            )),
259            OwnKey::NistP384(sk) => PublicVerificationKey::ecdsaNistP384(p384_point(
260                sk.verifying_key().to_encoded_point(compressed).as_bytes(),
261            )),
262        }
263    }
264
265    /// Sign `data` with the hash of the key's curve (SHA-256 for the 256-bit
266    /// curves, SHA-384 for the 384-bit ones); brainpool signatures use a
267    /// fresh random nonce from the thread CSPRNG (FIPS 186-4 ECDSA). Returns
268    /// an IEEE 1609.2 `Signature` with r as x-only.
269    pub fn sign(&self, data: &[u8], id: usize) -> Ieee1609Signature {
270        match &self.keys[&id] {
271            OwnKey::NistP256(sk) => {
272                let sig: Signature = sk.sign(data);
273                let (r, s) = sig.split_bytes();
274                Ieee1609Signature::ecdsaNistP256Signature(EcdsaP256Signature {
275                    r_sig: EccP256CurvePoint::x_only(r.to_vec().into()),
276                    s_sig: s.to_vec().into(),
277                })
278            }
279            OwnKey::NistP384(sk) => {
280                use p384::ecdsa::signature::hazmat::PrehashSigner as _;
281                let sig: p384::ecdsa::Signature = sk
282                    .sign_prehash(&Sha384::digest(data))
283                    .expect("P-384 signature");
284                let (r, s) = sig.split_bytes();
285                Ieee1609Signature::ecdsaNistP384Signature(EcdsaP384Signature {
286                    r_sig: EccP384CurvePoint::x_only(r.to_vec().into()),
287                    s_sig: s.to_vec().into(),
288                })
289            }
290            OwnKey::BrainpoolP256r1(sk) => {
291                let bytes = brainpool_sign(sk, &Sha256::digest(data));
292                Ieee1609Signature::ecdsaBrainpoolP256r1Signature(EcdsaP256Signature {
293                    r_sig: EccP256CurvePoint::x_only(bytes[..32].to_vec().into()),
294                    s_sig: bytes[32..].to_vec().into(),
295                })
296            }
297            OwnKey::BrainpoolP384r1(sk) => {
298                let bytes = brainpool_sign(sk, &Sha384::digest(data));
299                Ieee1609Signature::ecdsaBrainpoolP384r1Signature(EcdsaP384Signature {
300                    r_sig: EccP384CurvePoint::x_only(bytes[..48].to_vec().into()),
301                    s_sig: bytes[48..].to_vec().into(),
302                })
303            }
304        }
305    }
306
307    /// Verify `data` against `signature` with public key `pk`, both in IEEE
308    /// 1609.2 format. `data` is hashed with the hash of the curve (SHA-256 for
309    /// the 256-bit curves, SHA-384 for the 384-bit ones); for messages and
310    /// certificates it is the 1609.2 signing input (see
311    /// `certificate::signing_input`).
312    ///
313    /// Supported: NIST P-256, brainpoolP256r1, brainpoolP384r1 and NIST P-384,
314    /// with r given as x-only, compressed or uncompressed point. A signature
315    /// whose algorithm does not match the key is not valid.
316    pub fn verify_with_pk(
317        &self,
318        data: &[u8],
319        signature: &Ieee1609Signature,
320        pk: &PublicVerificationKey,
321    ) -> bool {
322        match (signature, pk) {
323            (
324                Ieee1609Signature::ecdsaNistP256Signature(sig),
325                PublicVerificationKey::ecdsaNistP256(point),
326            ) => {
327                let (Some(sec1), Some(rs)) = (p256_sec1(point), p256_rs(sig)) else {
328                    return false;
329                };
330                match (
331                    VerifyingKey::from_sec1_bytes(&sec1),
332                    Signature::from_slice(&rs),
333                ) {
334                    (Ok(vk), Ok(sig)) => vk.verify(data, &sig).is_ok(),
335                    _ => false,
336                }
337            }
338            (
339                Ieee1609Signature::ecdsaBrainpoolP256r1Signature(sig),
340                PublicVerificationKey::ecdsaBrainpoolP256r1(point),
341            ) => {
342                let (Some(sec1), Some(rs)) = (p256_sec1(point), p256_rs(sig)) else {
343                    return false;
344                };
345                verify_bp256(&sec1, &rs, &Sha256::digest(data))
346            }
347            (
348                Ieee1609Signature::ecdsaBrainpoolP384r1Signature(sig),
349                PublicVerificationKey::ecdsaBrainpoolP384r1(point),
350            ) => {
351                let (Some(sec1), Some(rs)) = (p384_sec1(point), p384_rs(sig)) else {
352                    return false;
353                };
354                verify_bp384(&sec1, &rs, &Sha384::digest(data))
355            }
356            (
357                Ieee1609Signature::ecdsaNistP384Signature(sig),
358                PublicVerificationKey::ecdsaNistP384(point),
359            ) => {
360                let (Some(sec1), Some(rs)) = (p384_sec1(point), p384_rs(sig)) else {
361                    return false;
362                };
363                use p384::ecdsa::signature::hazmat::PrehashVerifier as _;
364                match (
365                    p384::ecdsa::VerifyingKey::from_sec1_bytes(&sec1),
366                    p384::ecdsa::Signature::from_slice(&rs),
367                ) {
368                    (Ok(vk), Ok(sig)) => vk.verify_prehash(&Sha384::digest(data), &sig).is_ok(),
369                    _ => false,
370                }
371            }
372            _ => false,
373        }
374    }
375
376    /// Export the private scalar of the signing key (big-endian bytes).
377    pub fn export_signing_key(&self, id: usize) -> Vec<u8> {
378        match &self.keys[&id] {
379            OwnKey::NistP256(sk) => sk.to_bytes().to_vec(),
380            OwnKey::BrainpoolP256r1(sk) => sk.to_bytes().to_vec(),
381            OwnKey::BrainpoolP384r1(sk) => sk.to_bytes().to_vec(),
382            OwnKey::NistP384(sk) => sk.to_bytes().to_vec(),
383        }
384    }
385
386    /// Import a signing key on `algorithm` from its private scalar bytes.
387    /// Returns the new key id.
388    pub fn import_signing_key_with(&mut self, algorithm: KeyAlgorithm, key_bytes: &[u8]) -> usize {
389        let key = match algorithm {
390            KeyAlgorithm::NistP256 => {
391                OwnKey::NistP256(SigningKey::from_slice(key_bytes).expect("invalid key bytes"))
392            }
393            KeyAlgorithm::BrainpoolP256r1 => OwnKey::BrainpoolP256r1(
394                ecdsa_v017::elliptic_curve::SecretKey::from_slice(key_bytes)
395                    .expect("invalid key bytes"),
396            ),
397            KeyAlgorithm::BrainpoolP384r1 => OwnKey::BrainpoolP384r1(
398                ecdsa_v017::elliptic_curve::SecretKey::from_slice(key_bytes)
399                    .expect("invalid key bytes"),
400            ),
401            KeyAlgorithm::NistP384 => OwnKey::NistP384(
402                p384::ecdsa::SigningKey::from_slice(key_bytes).expect("invalid key bytes"),
403            ),
404        };
405        let id = self.next_id;
406        self.keys.insert(id, key);
407        self.next_id += 1;
408        id
409    }
410
411    /// Import a signing key from SEC1 DER bytes.  Returns the new key id.
412    pub fn import_signing_key(&mut self, key_bytes: &[u8]) -> usize {
413        self.import_signing_key_with(KeyAlgorithm::NistP256, key_bytes)
414    }
415
416    /// Hash the COER-encoded certificate bytes and return the last 8 bytes (HashedId8).
417    pub fn hash_to_hashedid8(data: &[u8]) -> [u8; 8] {
418        let digest = Sha256::digest(data);
419        let mut out = [0u8; 8];
420        out.copy_from_slice(&digest[24..32]);
421        out
422    }
423}
424
425/// ECDSA signature (r || s) of the prehashed `digest` with a random nonce.
426fn brainpool_sign<C>(sk: &ecdsa_v017::elliptic_curve::SecretKey<C>, digest: &[u8]) -> Vec<u8>
427where
428    C: ecdsa_v017::EcdsaCurve + ecdsa_v017::elliptic_curve::CurveArithmetic,
429    ecdsa_v017::SignatureSize<C>: ecdsa_v017::elliptic_curve::array::ArraySize,
430{
431    let d = sk.to_nonzero_scalar();
432    let mut rng = rand::thread_rng();
433    loop {
434        let k = random_secret::<C>(&mut rng).to_nonzero_scalar();
435        if let Ok((sig, _)) = ecdsa_v017::hazmat::sign_prehashed::<C>(&d, &k, digest) {
436            return sig.to_bytes().to_vec();
437        }
438    }
439}
440
441fn random_secret<C>(rng: &mut impl rand::RngCore) -> ecdsa_v017::elliptic_curve::SecretKey<C>
442where
443    C: ecdsa_v017::elliptic_curve::CurveArithmetic,
444{
445    loop {
446        let mut bytes = vec![0u8; ecdsa_v017::elliptic_curve::FieldBytes::<C>::default().len()];
447        rng.fill_bytes(&mut bytes);
448        if let Ok(key) = ecdsa_v017::elliptic_curve::SecretKey::<C>::from_slice(&bytes) {
449            return key;
450        }
451    }
452}
453
454impl Default for EcdsaBackend {
455    fn default() -> Self {
456        Self::new()
457    }
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463
464    #[test]
465    fn backend_new_empty() {
466        let backend = EcdsaBackend::new();
467        assert_eq!(backend.next_id, 0);
468        assert!(backend.keys.is_empty());
469    }
470
471    #[test]
472    fn backend_default() {
473        let backend = EcdsaBackend::default();
474        assert_eq!(backend.next_id, 0);
475    }
476
477    #[test]
478    fn create_key_returns_sequential_ids() {
479        let mut backend = EcdsaBackend::new();
480        assert_eq!(backend.create_key(), 0);
481        assert_eq!(backend.create_key(), 1);
482        assert_eq!(backend.create_key(), 2);
483    }
484
485    #[test]
486    fn get_public_key_compressed_and_uncompressed() {
487        let mut backend = EcdsaBackend::new();
488        let id = backend.create_key();
489
490        // Default is compressed (compressed_y_0 or compressed_y_1)
491        let pk = backend.get_public_key(id);
492        match pk {
493            PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::compressed_y_0(x))
494            | PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::compressed_y_1(x)) => {
495                assert_eq!(x.as_ref().len(), 32);
496            }
497            _ => panic!("Expected compressed_y_0 or compressed_y_1"),
498        }
499
500        // Explicit uncompressed
501        let pk_uncomp = backend.get_public_key_compressed(id, false);
502        match pk_uncomp {
503            PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::uncompressedP256(u)) => {
504                assert_eq!(u.x.as_ref().len(), 32);
505                assert_eq!(u.y.as_ref().len(), 32);
506            }
507            _ => panic!("Expected uncompressedP256"),
508        }
509    }
510
511    #[test]
512    fn sign_and_verify_both_key_formats() {
513        let mut backend = EcdsaBackend::new();
514        let id = backend.create_key();
515        let data = b"Hello, ETSI C-ITS!";
516        let signature = backend.sign(data, id);
517
518        // Verify with default (compressed) public key
519        let pk_comp = backend.get_public_key(id);
520        assert!(backend.verify_with_pk(data, &signature, &pk_comp));
521        assert!(!backend.verify_with_pk(b"wrong data", &signature, &pk_comp));
522
523        // Verify with uncompressed public key
524        let pk_uncomp = backend.get_public_key_compressed(id, false);
525        assert!(backend.verify_with_pk(data, &signature, &pk_uncomp));
526        assert!(!backend.verify_with_pk(b"wrong data", &signature, &pk_uncomp));
527    }
528
529    #[test]
530    fn verify_with_compressed_r_sig() {
531        let mut backend = EcdsaBackend::new();
532        let id = backend.create_key();
533        let data = b"Test signature with compressed r_sig";
534        let sig = backend.sign(data, id);
535        let pk = backend.get_public_key(id);
536
537        let (r_bytes, s_bytes) = match sig {
538            Ieee1609Signature::ecdsaNistP256Signature(s) => match s.r_sig {
539                EccP256CurvePoint::x_only(b) => (b, s.s_sig),
540                _ => panic!("Expected x_only"),
541            },
542            _ => panic!("Expected ecdsaNistP256Signature"),
543        };
544
545        // Construct signature with compressed_y_0
546        let sig_y0 = Ieee1609Signature::ecdsaNistP256Signature(EcdsaP256Signature {
547            r_sig: EccP256CurvePoint::compressed_y_0(r_bytes.clone()),
548            s_sig: s_bytes.clone(),
549        });
550        assert!(backend.verify_with_pk(data, &sig_y0, &pk));
551
552        // Construct signature with compressed_y_1
553        let sig_y1 = Ieee1609Signature::ecdsaNistP256Signature(EcdsaP256Signature {
554            r_sig: EccP256CurvePoint::compressed_y_1(r_bytes),
555            s_sig: s_bytes,
556        });
557        assert!(backend.verify_with_pk(data, &sig_y1, &pk));
558    }
559
560    /// Own keys on NIST P-256/P-384 and brainpoolP256r1/P384r1: signature
561    /// choice and sizes follow the curve; a signature verifies with its key
562    /// (compressed or uncompressed) only.
563    #[test]
564    fn sign_and_verify_on_every_curve() {
565        let mut backend = EcdsaBackend::new();
566        for algorithm in [
567            KeyAlgorithm::NistP256,
568            KeyAlgorithm::BrainpoolP256r1,
569            KeyAlgorithm::BrainpoolP384r1,
570            KeyAlgorithm::NistP384,
571        ] {
572            let id = backend.create_key_with(algorithm);
573            assert_eq!(backend.algorithm(id), algorithm);
574            let sig = backend.sign(b"data", id);
575            let size = match (&sig, algorithm) {
576                (Ieee1609Signature::ecdsaNistP256Signature(s), KeyAlgorithm::NistP256)
577                | (
578                    Ieee1609Signature::ecdsaBrainpoolP256r1Signature(s),
579                    KeyAlgorithm::BrainpoolP256r1,
580                ) => s.s_sig.len(),
581                (
582                    Ieee1609Signature::ecdsaBrainpoolP384r1Signature(s),
583                    KeyAlgorithm::BrainpoolP384r1,
584                )
585                | (Ieee1609Signature::ecdsaNistP384Signature(s), KeyAlgorithm::NistP384) => {
586                    s.s_sig.len()
587                }
588                _ => panic!("{algorithm:?}: wrong signature choice"),
589            };
590            let expected = if matches!(
591                algorithm,
592                KeyAlgorithm::NistP256 | KeyAlgorithm::BrainpoolP256r1
593            ) {
594                32
595            } else {
596                48
597            };
598            assert_eq!(size, expected);
599            for compressed in [true, false] {
600                let pk = backend.get_public_key_compressed(id, compressed);
601                assert!(backend.verify_with_pk(b"data", &sig, &pk), "{algorithm:?}");
602                assert!(
603                    !backend.verify_with_pk(b"other", &sig, &pk),
604                    "{algorithm:?}"
605                );
606            }
607            let copy = EcdsaBackend::new()
608                .import_signing_key_with(algorithm, &backend.export_signing_key(id));
609            assert_eq!(copy, 0);
610        }
611    }
612
613    #[test]
614    fn sign_and_verify() {
615        let mut backend = EcdsaBackend::new();
616        let id = backend.create_key();
617        let data = b"Hello, ETSI C-ITS!";
618        let signature = backend.sign(data, id);
619        let pk = backend.get_public_key(id);
620        assert!(backend.verify_with_pk(data, &signature, &pk));
621    }
622
623    #[test]
624    fn sign_wrong_data_fails_verification() {
625        let mut backend = EcdsaBackend::new();
626        let id = backend.create_key();
627        let signature = backend.sign(b"correct data", id);
628        let pk = backend.get_public_key(id);
629        assert!(!backend.verify_with_pk(b"wrong data", &signature, &pk));
630    }
631
632    #[test]
633    fn sign_wrong_key_fails_verification() {
634        let mut backend = EcdsaBackend::new();
635        let id1 = backend.create_key();
636        let id2 = backend.create_key();
637        let data = b"test data";
638        let signature = backend.sign(data, id1);
639        let pk2 = backend.get_public_key(id2);
640        assert!(!backend.verify_with_pk(data, &signature, &pk2));
641    }
642
643    #[test]
644    fn export_import_key_roundtrip() {
645        let mut backend = EcdsaBackend::new();
646        let id = backend.create_key();
647        let exported = backend.export_signing_key(id);
648        assert_eq!(exported.len(), 32);
649
650        let mut backend2 = EcdsaBackend::new();
651        let id2 = backend2.import_signing_key(&exported);
652
653        // Sign with original, verify with imported (same key)
654        let data = b"roundtrip test";
655        let sig = backend.sign(data, id);
656        let pk = backend2.get_public_key(id2);
657        assert!(backend2.verify_with_pk(data, &sig, &pk));
658    }
659
660    #[test]
661    fn hash_to_hashedid8_deterministic() {
662        let data = b"certificate bytes";
663        let h1 = EcdsaBackend::hash_to_hashedid8(data);
664        let h2 = EcdsaBackend::hash_to_hashedid8(data);
665        assert_eq!(h1, h2);
666        assert_eq!(h1.len(), 8);
667    }
668
669    #[test]
670    fn hash_to_hashedid8_different_input() {
671        let h1 = EcdsaBackend::hash_to_hashedid8(b"input1");
672        let h2 = EcdsaBackend::hash_to_hashedid8(b"input2");
673        assert_ne!(h1, h2);
674    }
675
676    #[test]
677    fn hash_to_hashedid8_is_last_8_bytes_of_sha256() {
678        let data = b"test";
679        let digest = Sha256::digest(data);
680        let expected: [u8; 8] = digest[24..32].try_into().unwrap();
681        assert_eq!(EcdsaBackend::hash_to_hashedid8(data), expected);
682    }
683}