Skip to main content

rustflexstack/security/
certificate.rs

1//! Certificate handling — ETSI TS 103 097 V2.2.1 (2026-03) profiles.
2//!
3//! Provides [`Certificate`] (read-only wrapper) and [`OwnCertificate`]
4//! (includes the private-key identifier for signing).
5
6use sha2::{Digest, Sha256, Sha384};
7
8use crate::security::ecdsa_backend::{
9    key_uses_sha384, reconstruct_public_key, EcdsaBackend, KeyAlgorithm,
10};
11
12/// Input to the ECDSA signing and verification operations (IEEE Std
13/// 1609.2-2016, clause 5.3.1, adopted by ETSI TS 103 097 V2.2.1):
14/// `Hash(Data input) || Hash(Signer identifier input)`, which ECDSA hashes
15/// again. `data` is the COER encoding of the ToBeSignedData or
16/// ToBeSignedCertificate; `signer` is the canonical COER encoding of the
17/// signer's certificate, or empty for self-signed data. `sha384` selects
18/// SHA-384 (384-bit curves) instead of SHA-256.
19pub fn signing_input(data: &[u8], signer: &[u8], sha384: bool) -> Vec<u8> {
20    if sha384 {
21        [
22            Sha384::digest(data).to_vec(),
23            Sha384::digest(signer).to_vec(),
24        ]
25        .concat()
26    } else {
27        [
28            Sha256::digest(data).to_vec(),
29            Sha256::digest(signer).to_vec(),
30        ]
31        .concat()
32    }
33}
34use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
35use crate::security::security_asn::ieee1609_dot2::Certificate as AsnCertificate;
36use crate::security::security_asn::ieee1609_dot2::{
37    CertificateBase, CertificateType, Ieee1609Dot2Data, IssuerIdentifier, ToBeSignedCertificate,
38    ToBeSignedData,
39};
40use crate::security::security_asn::ieee1609_dot2::{SubjectPermissions, VerificationKeyIndicator};
41use crate::security::security_asn::ieee1609_dot2_base_types::Signature as Ieee1609Signature;
42use crate::security::security_asn::ieee1609_dot2_base_types::{
43    BasePublicEncryptionKey, EccP256CurvePoint, EccP384CurvePoint, EcdsaP256Signature,
44    HashAlgorithm, HashedId8, PublicVerificationKey, Uint8,
45};
46
47// ─── COER encode / decode helpers ────────────────────────────────────────
48
49/// COER-encode an `EtsiTs103097Certificate`.
50pub fn encode_certificate(cert: &EtsiTs103097Certificate) -> Vec<u8> {
51    rasn::coer::encode(cert).expect("certificate COER encode failed")
52}
53
54/// COER-decode an `EtsiTs103097Certificate`.
55pub fn decode_certificate(bytes: &[u8]) -> EtsiTs103097Certificate {
56    rasn::coer::decode::<EtsiTs103097Certificate>(bytes).expect("certificate COER decode failed")
57}
58
59/// COER-encode `Ieee1609Dot2Data` (signed message envelope).
60pub fn encode_ieee1609_dot2_data(data: &Ieee1609Dot2Data) -> Vec<u8> {
61    rasn::coer::encode(data).expect("Ieee1609Dot2Data COER encode failed")
62}
63
64/// COER-decode `Ieee1609Dot2Data`.
65/// COER-decode an `Ieee1609Dot2Data`, `None` when malformed (received data).
66pub fn try_decode_ieee1609_dot2_data(bytes: &[u8]) -> Option<Ieee1609Dot2Data> {
67    rasn::coer::decode::<Ieee1609Dot2Data>(bytes).ok()
68}
69
70pub fn decode_ieee1609_dot2_data(bytes: &[u8]) -> Ieee1609Dot2Data {
71    rasn::coer::decode::<Ieee1609Dot2Data>(bytes).expect("Ieee1609Dot2Data COER decode failed")
72}
73
74/// COER-encode `ToBeSignedData` (the data that is actually signed).
75pub fn encode_tbs_data(tbs: &ToBeSignedData) -> Vec<u8> {
76    rasn::coer::encode(tbs).expect("ToBeSignedData COER encode failed")
77}
78
79/// COER-encode `ToBeSignedCertificate`.
80pub fn encode_tbs_certificate(tbs: &ToBeSignedCertificate) -> Vec<u8> {
81    rasn::coer::encode(tbs).expect("ToBeSignedCertificate COER encode failed")
82}
83
84// ─── HashedId8 / HashedId3 helpers ───────────────────────────────────────
85
86/// Compute the HashedId8 of a COER-encoded certificate.
87pub fn compute_hashedid8(cert_bytes: &[u8]) -> [u8; 8] {
88    EcdsaBackend::hash_to_hashedid8(cert_bytes)
89}
90
91// ─── Canonicalization helpers (IEEE 1609.2 clause 6.4.3) ─────────────────
92
93/// A verification key or reconstruction value point in compressed form.
94fn compress_p256(point: &mut EccP256CurvePoint) {
95    if let EccP256CurvePoint::uncompressedP256(u) = point {
96        let even = u.y.as_ref().last().is_some_and(|b| b % 2 == 0);
97        let x = u.x.clone();
98        *point = if even {
99            EccP256CurvePoint::compressed_y_0(x)
100        } else {
101            EccP256CurvePoint::compressed_y_1(x)
102        };
103    }
104}
105
106fn compress_p384(point: &mut EccP384CurvePoint) {
107    if let EccP384CurvePoint::uncompressedP384(u) = point {
108        let even = u.y.as_ref().last().is_some_and(|b| b % 2 == 0);
109        let x = u.x.clone();
110        *point = if even {
111            EccP384CurvePoint::compressed_y_0(x)
112        } else {
113            EccP384CurvePoint::compressed_y_1(x)
114        };
115    }
116}
117
118/// The r of an ECDSA signature in x-only form.
119fn x_only_p256(r: &mut EccP256CurvePoint) {
120    let x = match r {
121        EccP256CurvePoint::compressed_y_0(x) | EccP256CurvePoint::compressed_y_1(x) => x.clone(),
122        EccP256CurvePoint::uncompressedP256(u) => u.x.clone(),
123        _ => return,
124    };
125    *r = EccP256CurvePoint::x_only(x);
126}
127
128fn x_only_p384(r: &mut EccP384CurvePoint) {
129    let x = match r {
130        EccP384CurvePoint::compressed_y_0(x) | EccP384CurvePoint::compressed_y_1(x) => x.clone(),
131        EccP384CurvePoint::uncompressedP384(u) => u.x.clone(),
132        _ => return,
133    };
134    *r = EccP384CurvePoint::x_only(x);
135}
136
137// ─── Certificate (read-only) ─────────────────────────────────────────────
138
139/// Immutable certificate wrapper.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct Certificate {
142    /// The inner ASN.1 certificate.
143    pub inner: EtsiTs103097Certificate,
144    /// Cached COER encoding (for hashing).
145    encoded: Vec<u8>,
146    /// Optional issuer certificate (for chain verification).
147    pub issuer: Option<Box<Certificate>>,
148}
149
150impl Certificate {
151    /// Build from a decoded ASN.1 certificate.
152    pub fn from_asn(asn: EtsiTs103097Certificate, issuer: Option<Certificate>) -> Self {
153        let encoded = encode_certificate(&asn);
154        Self {
155            inner: asn,
156            encoded,
157            issuer: issuer.map(Box::new),
158        }
159    }
160
161    /// Decode from COER bytes.
162    pub fn from_bytes(bytes: &[u8], issuer: Option<Certificate>) -> Self {
163        let asn = decode_certificate(bytes);
164        let encoded = bytes.to_vec();
165        Self {
166            inner: asn,
167            encoded,
168            issuer: issuer.map(Box::new),
169        }
170    }
171
172    /// Access the inner `CertificateBase`.
173    pub fn base(&self) -> &CertificateBase {
174        &(self.inner.0).0
175    }
176
177    /// Access `toBeSigned`.
178    pub fn tbs(&self) -> &ToBeSignedCertificate {
179        &self.base().to_be_signed
180    }
181
182    /// Return the COER encoding.
183    pub fn encode(&self) -> &[u8] {
184        &self.encoded
185    }
186
187    /// Convert certificate to IEEE 1609.2 / ETSI TS 103 097 canonical form:
188    /// - Public verification key compressed (compressed_y_0/1).
189    /// - Signature r_sig as x_only.
190    pub fn to_canonical(&self) -> Certificate {
191        let mut new_base = self.base().clone();
192        let indicator = &mut new_base.to_be_signed.verify_key_indicator;
193        match indicator {
194            VerificationKeyIndicator::verificationKey(
195                PublicVerificationKey::ecdsaNistP256(point)
196                | PublicVerificationKey::ecdsaBrainpoolP256r1(point),
197            )
198            | VerificationKeyIndicator::reconstructionValue(point) => compress_p256(point),
199            VerificationKeyIndicator::verificationKey(
200                PublicVerificationKey::ecdsaBrainpoolP384r1(point)
201                | PublicVerificationKey::ecdsaNistP384(point),
202            ) => compress_p384(point),
203            _ => {}
204        }
205        if let Some(key) = &mut new_base.to_be_signed.encryption_key {
206            match &mut key.public_key {
207                BasePublicEncryptionKey::eciesNistP256(point)
208                | BasePublicEncryptionKey::eciesBrainpoolP256r1(point)
209                | BasePublicEncryptionKey::ecencSm2(point) => compress_p256(point),
210            }
211        }
212        match &mut new_base.signature {
213            Some(
214                Ieee1609Signature::ecdsaNistP256Signature(sig)
215                | Ieee1609Signature::ecdsaBrainpoolP256r1Signature(sig),
216            ) => x_only_p256(&mut sig.r_sig),
217            Some(
218                Ieee1609Signature::ecdsaBrainpoolP384r1Signature(sig)
219                | Ieee1609Signature::ecdsaNistP384Signature(sig),
220            ) => x_only_p384(&mut sig.r_sig),
221            _ => {}
222        }
223        if new_base == *self.base() {
224            return self.clone();
225        }
226        let new_asn = EtsiTs103097Certificate(AsnCertificate(new_base));
227        let issuer = self.issuer.as_ref().map(|i| *i.clone());
228        Certificate::from_asn(new_asn, issuer)
229    }
230
231    /// HashedId8 of the canonical certificate, with the hash for the curve of
232    /// its verification key: SHA-384 for a 384-bit key, SHA-256 otherwise (the
233    /// hashes approved by ETSI TS 103 097 V2.2.1 clause 4.2, paired with the
234    /// curves as in the permutation tables of ETSI TS 103 096-2).
235    pub fn as_hashedid8(&self) -> [u8; 8] {
236        let canon = self.to_canonical();
237        if !self.uses_sha384() {
238            return compute_hashedid8(&canon.encoded);
239        }
240        let digest = Sha384::digest(&canon.encoded);
241        let mut out = [0u8; 8];
242        out.copy_from_slice(&digest[40..48]);
243        out
244    }
245
246    /// SHA-384 is the hash associated with the certificate's verification key
247    /// (384-bit curve), used for its HashedId8, the hashId of data it signs
248    /// and the issuer choice of certificates it issues; SHA-256 otherwise
249    /// (and for implicit certificates).
250    pub fn uses_sha384(&self) -> bool {
251        matches!(&self.tbs().verify_key_indicator,
252            VerificationKeyIndicator::verificationKey(pk) if key_uses_sha384(pk))
253    }
254
255    /// IssuerIdentifier of a certificate issued by this one.
256    pub fn issuer_identifier(&self) -> IssuerIdentifier {
257        let h8 = HashedId8(rasn::types::FixedOctetString::from(self.as_hashedid8()));
258        if self.uses_sha384() {
259            IssuerIdentifier::sha384AndDigest(h8)
260        } else {
261            IssuerIdentifier::sha256AndDigest(h8)
262        }
263    }
264
265    /// Compute the last 3 bytes of HashedId8.
266    pub fn as_hashedid3(&self) -> [u8; 3] {
267        let h8 = self.as_hashedid8();
268        [h8[5], h8[6], h8[7]]
269    }
270
271    /// Return the list of ITS-AID (PSID) values from `appPermissions`.
272    pub fn get_list_of_its_aid(&self) -> Vec<u64> {
273        let mut aids = Vec::new();
274        if let Some(ref perms) = self.tbs().app_permissions {
275            for psid_ssp in perms.0.iter() {
276                // Psid wraps an Integer — convert via i128 then u64.
277                let val = u64::try_from(&psid_ssp.psid.0).unwrap_or(0);
278                aids.push(val);
279            }
280        }
281        aids
282    }
283
284    /// Get issuer HashedId8 stored inside the certificate.
285    /// Returns `None` if self-signed.
286    pub fn get_issuer_hashedid8(&self) -> Option<[u8; 8]> {
287        match &self.base().issuer {
288            IssuerIdentifier::sha256AndDigest(h) => {
289                let mut out = [0u8; 8];
290                out.copy_from_slice(h.0.as_ref());
291                Some(out)
292            }
293            IssuerIdentifier::R_self(_) => None,
294            IssuerIdentifier::sha384AndDigest(h) => {
295                let mut out = [0u8; 8];
296                out.copy_from_slice(h.0.as_ref());
297                Some(out)
298            }
299            _ => None,
300        }
301    }
302
303    /// Check whether the signature uses NIST P-256.
304    pub fn signature_is_nist_p256(&self) -> bool {
305        matches!(
306            self.base().signature,
307            Some(Ieee1609Signature::ecdsaNistP256Signature(_))
308        )
309    }
310
311    /// Check whether the verification key is NIST P-256.
312    pub fn verification_key_is_nist_p256(&self) -> bool {
313        matches!(
314            &self.tbs().verify_key_indicator,
315            VerificationKeyIndicator::verificationKey(PublicVerificationKey::ecdsaNistP256(_))
316        )
317    }
318
319    /// Is the signature NIST P-256/P-384 or brainpoolP256r1/P384r1?
320    pub fn signature_is_supported(&self) -> bool {
321        matches!(
322            self.base().signature,
323            Some(
324                Ieee1609Signature::ecdsaNistP256Signature(_)
325                    | Ieee1609Signature::ecdsaBrainpoolP256r1Signature(_)
326                    | Ieee1609Signature::ecdsaBrainpoolP384r1Signature(_)
327                    | Ieee1609Signature::ecdsaNistP384Signature(_)
328            )
329        )
330    }
331
332    /// Is the verification key NIST P-256/P-384 or brainpoolP256r1/P384r1?
333    pub fn verification_key_is_supported(&self) -> bool {
334        matches!(
335            &self.tbs().verify_key_indicator,
336            VerificationKeyIndicator::verificationKey(
337                PublicVerificationKey::ecdsaNistP256(_)
338                    | PublicVerificationKey::ecdsaBrainpoolP256r1(_)
339                    | PublicVerificationKey::ecdsaBrainpoolP384r1(_)
340                    | PublicVerificationKey::ecdsaNistP384(_)
341            )
342        )
343    }
344
345    /// Is the certificate self-signed?
346    pub fn is_self_signed(&self) -> bool {
347        matches!(
348            &self.base().issuer,
349            IssuerIdentifier::R_self(HashAlgorithm::sha256 | HashAlgorithm::sha384)
350        )
351    }
352
353    /// Is the certificate issued (not self-signed)?
354    pub fn is_issued(&self) -> bool {
355        matches!(
356            &self.base().issuer,
357            IssuerIdentifier::sha256AndDigest(_) | IssuerIdentifier::sha384AndDigest(_)
358        )
359    }
360
361    /// Check whether the issuer's HashedId8 matches the given issuer certificate.
362    pub fn check_corresponding_issuer(&self, issuer: &Certificate) -> bool {
363        let choice_matches = match &self.base().issuer {
364            IssuerIdentifier::sha256AndDigest(_) => !issuer.uses_sha384(),
365            IssuerIdentifier::sha384AndDigest(_) => issuer.uses_sha384(),
366            _ => false,
367        };
368        match self.get_issuer_hashedid8() {
369            Some(h) => choice_matches && h == issuer.as_hashedid8(),
370            None => false,
371        }
372    }
373
374    /// Does `certIssuePermissions` have a subjectPermissions of `all`?
375    pub fn has_all_permissions(&self) -> bool {
376        if let Some(ref cip) = self.tbs().cert_issue_permissions {
377            for perm in cip.0.iter() {
378                if matches!(perm.subject_permissions, SubjectPermissions::all(_)) {
379                    return true;
380                }
381            }
382        }
383        false
384    }
385
386    /// Get the PSID list from `certIssuePermissions.subjectPermissions.explicit`.
387    pub fn get_allowed_permissions(&self) -> Vec<u64> {
388        let mut out = Vec::new();
389        if let Some(ref cip) = self.tbs().cert_issue_permissions {
390            for perm in cip.0.iter() {
391                if let SubjectPermissions::explicit(ref ranges) = perm.subject_permissions {
392                    for r in ranges.0.iter() {
393                        let val = u64::try_from(&r.psid.0).unwrap_or(0);
394                        out.push(val);
395                    }
396                }
397            }
398        }
399        out
400    }
401
402    /// Check whether the issuer has the right permissions to issue this cert.
403    pub fn check_issuer_has_subject_permissions(&self, issuer: &Certificate) -> bool {
404        if issuer.has_all_permissions() {
405            return true;
406        }
407        let needed = self.get_list_of_its_aid();
408        let allowed = issuer.get_allowed_permissions();
409        needed.iter().all(|n| allowed.contains(n))
410    }
411
412    /// Verify the signature of a self-signed certificate: the signer input
413    /// is the empty string (IEEE 1609.2 clause 5.3.1).
414    pub fn verify_signature_with(
415        backend: &EcdsaBackend,
416        tbs: &ToBeSignedCertificate,
417        signature: &Ieee1609Signature,
418        verification_key: &PublicVerificationKey,
419    ) -> bool {
420        let tbs_bytes = encode_tbs_certificate(tbs);
421        let payload = signing_input(&tbs_bytes, &[], key_uses_sha384(verification_key));
422        backend.verify_with_pk(&payload, signature, verification_key)
423    }
424
425    /// Verify an issued certificate (chain to issuer).
426    fn verify_issued(&self, backend: &EcdsaBackend) -> bool {
427        let issuer = match &self.issuer {
428            Some(i) => i,
429            None => return false,
430        };
431        if !self.is_issued() {
432            return false;
433        }
434        if !self.check_corresponding_issuer(issuer) {
435            return false;
436        }
437        if !self.check_issuer_has_subject_permissions(issuer) {
438            return false;
439        }
440        if !self.signature_is_supported() || !self.verification_key_is_supported() {
441            return false;
442        }
443        let sig = match &self.base().signature {
444            Some(s) => s,
445            None => return false,
446        };
447        let Some(issuer_vk_owned) = issuer.verification_key() else {
448            return false;
449        };
450        let issuer_vk = &issuer_vk_owned;
451        // IEEE 1609.2 clause 5.3.1: Hash(Hash(tbs) || Hash(issuer certificate))
452        let tbs_bytes = encode_tbs_certificate(self.tbs());
453        let payload = signing_input(
454            &tbs_bytes,
455            issuer.to_canonical().encode(),
456            key_uses_sha384(issuer_vk),
457        );
458        backend.verify_with_pk(&payload, sig, issuer_vk)
459    }
460
461    /// Verify a self-signed certificate.
462    fn verify_self_signed(&self, backend: &EcdsaBackend) -> bool {
463        if !self.is_self_signed() {
464            return false;
465        }
466        if !self.signature_is_supported() || !self.verification_key_is_supported() {
467            return false;
468        }
469        let sig = match &self.base().signature {
470            Some(s) => s,
471            None => return false,
472        };
473        let pk = match &self.tbs().verify_key_indicator {
474            VerificationKeyIndicator::verificationKey(vk) => vk,
475            _ => return false,
476        };
477        Certificate::verify_signature_with(backend, self.tbs(), sig, pk)
478    }
479
480    /// Full certificate verification (self-signed or chained).
481    pub fn verify(&self, backend: &EcdsaBackend) -> bool {
482        // §6: verifyKeyIndicator must match certificate type
483        match self.base().r_type {
484            CertificateType::explicit => {
485                if !matches!(
486                    self.tbs().verify_key_indicator,
487                    VerificationKeyIndicator::verificationKey(_)
488                ) {
489                    return false;
490                }
491            }
492            CertificateType::implicit => {
493                // IEEE 1609.2 clause 6.4.2: reconstruction value and no
494                // signature (IEEE 1609.2 clause 5.3.2)
495                if !matches!(
496                    self.tbs().verify_key_indicator,
497                    VerificationKeyIndicator::reconstructionValue(_)
498                ) || self.base().signature.is_some()
499                {
500                    return false;
501                }
502                return self.verify_implicit();
503            }
504        }
505        if self.issuer.is_some() && self.is_issued() {
506            return self.verify_issued(backend);
507        }
508        if self.is_self_signed() {
509            return self.verify_self_signed(backend);
510        }
511        false
512    }
513
514    /// An implicit certificate has no signature: it is accepted when it is
515    /// issued by its (known) issuer with the required permissions and its
516    /// public key can be reconstructed. A wrong certificate yields a wrong
517    /// key, so data it signs does not verify (SEC 4 section 3.5).
518    fn verify_implicit(&self) -> bool {
519        let Some(issuer) = &self.issuer else {
520            return false;
521        };
522        self.is_issued()
523            && self.check_corresponding_issuer(issuer)
524            && self.check_issuer_has_subject_permissions(issuer)
525            && self.verification_key().is_some()
526    }
527
528    /// True for an implicit certificate (reconstruction value, no signature).
529    pub fn is_implicit(&self) -> bool {
530        matches!(self.base().r_type, CertificateType::implicit)
531    }
532
533    /// e = Hn(Hash(ToBeSignedCertificate) || Hash(issuer certificate)): the
534    /// leftmost floor(log2 n) = 255 bits of SHA-256 over the 1609.2 hash
535    /// input (IEEE Std 1609.2-2016 clauses 5.3.2 and 6.4.3; SEC 4 section
536    /// 2.3), as a big-endian 32-byte integer. `None` without issuer.
537    pub fn implicit_hash_integer(&self) -> Option<[u8; 32]> {
538        let issuer = self.issuer.as_ref()?;
539        let tbs = encode_tbs_certificate(self.to_canonical().tbs());
540        let digest = Sha256::digest(signing_input(&tbs, issuer.to_canonical().encode(), false));
541        let mut e = [0u8; 32];
542        let mut carry = 0u8;
543        for (i, byte) in digest.iter().enumerate() {
544            e[i] = (byte >> 1) | carry;
545            carry = byte << 7;
546        }
547        Some(e)
548    }
549
550    /// Public verification key: the explicit key, or the key reconstructed
551    /// from the reconstruction value and the issuer key (ECQV, IEEE Std
552    /// 1609.2-2016 clause 5.3.2). `None` when not available.
553    pub fn verification_key(&self) -> Option<PublicVerificationKey> {
554        match &self.tbs().verify_key_indicator {
555            VerificationKeyIndicator::verificationKey(pk) => Some(pk.clone()),
556            VerificationKeyIndicator::reconstructionValue(rv) => {
557                let issuer_key = self.issuer.as_ref()?.verification_key()?;
558                reconstruct_public_key(rv, &issuer_key, &self.implicit_hash_integer()?)
559            }
560        }
561    }
562
563    // ── Profile checks (§7.2) ────────────────────────────────────────────
564
565    /// §7.2.1 Authorization Ticket profile.
566    pub fn is_authorization_ticket(&self) -> bool {
567        if !self.is_issued() {
568            return false;
569        }
570        let tbs = self.tbs();
571        if !matches!(
572            tbs.id,
573            crate::security::security_asn::ieee1609_dot2::CertificateId::none(_)
574        ) {
575            return false;
576        }
577        if tbs.cert_issue_permissions.is_some() {
578            return false;
579        }
580        tbs.app_permissions.is_some()
581    }
582
583    /// §7.2.3 Root CA profile.
584    pub fn is_root_ca(&self) -> bool {
585        if !matches!(self.base().r_type, CertificateType::explicit) {
586            return false;
587        }
588        if !self.is_self_signed() {
589            return false;
590        }
591        let tbs = self.tbs();
592        tbs.cert_issue_permissions.is_some() && tbs.app_permissions.is_some()
593    }
594}
595
596// ─── OwnCertificate ─────────────────────────────────────────────────────
597
598/// A certificate for which we hold the private key.
599#[derive(Debug, Clone, PartialEq, Eq)]
600pub struct OwnCertificate {
601    pub cert: Certificate,
602    pub key_id: usize,
603}
604
605impl OwnCertificate {
606    /// Wrap an existing `Certificate` together with its key id.
607    pub fn new(cert: Certificate, key_id: usize) -> Self {
608        Self { cert, key_id }
609    }
610
611    /// Convert inner certificate to canonical form.
612    pub fn to_canonical(&self) -> Certificate {
613        self.cert.to_canonical()
614    }
615
616    /// Convenience delegations.
617    pub fn as_hashedid8(&self) -> [u8; 8] {
618        self.cert.as_hashedid8()
619    }
620
621    pub fn get_list_of_its_aid(&self) -> Vec<u64> {
622        self.cert.get_list_of_its_aid()
623    }
624
625    pub fn tbs(&self) -> &ToBeSignedCertificate {
626        self.cert.tbs()
627    }
628
629    pub fn base(&self) -> &CertificateBase {
630        self.cert.base()
631    }
632
633    pub fn verify(&self, backend: &EcdsaBackend) -> bool {
634        self.cert.verify(backend)
635    }
636
637    /// Sign `data` (the COER ToBeSignedData) with this certificate's key; the
638    /// signer identifier input is this certificate (IEEE 1609.2 clause 5.3.1).
639    pub fn sign_message(&self, backend: &EcdsaBackend, data: &[u8]) -> Ieee1609Signature {
640        let signer = self.to_canonical().encode().to_vec();
641        backend.sign(
642            &signing_input(data, &signer, self.cert.uses_sha384()),
643            self.key_id,
644        )
645    }
646
647    /// Sign (or re-sign) `target`'s `toBeSigned` and return a new `Certificate`
648    /// with the updated signature.
649    pub fn sign_certificate(&self, backend: &EcdsaBackend, target: &Certificate) -> Certificate {
650        // IEEE 1609.2 clause 5.3.1: Hash(Hash(tbs) || Hash(issuer certificate)),
651        // with the empty string as signer input for a self-signed certificate.
652        let tbs_bytes = encode_tbs_certificate(target.tbs());
653        let signer = if matches!(
654            target.base().issuer,
655            IssuerIdentifier::sha256AndDigest(_) | IssuerIdentifier::sha384AndDigest(_)
656        ) {
657            self.to_canonical().encode().to_vec()
658        } else {
659            Vec::new()
660        };
661        let payload = signing_input(&tbs_bytes, &signer, self.cert.uses_sha384());
662        let sig = backend.sign(&payload, self.key_id);
663
664        let mut new_base = target.base().clone();
665        new_base.signature = Some(sig);
666
667        let new_asn = EtsiTs103097Certificate(AsnCertificate(new_base));
668        Certificate::from_asn(new_asn, Some(self.cert.clone()))
669    }
670
671    /// Build the inner `AsnCertificate` from the wrapper's certificate dict,
672    /// setting the issuer to `self`, signing, and returning the result.
673    pub fn issue_certificate(&self, backend: &EcdsaBackend, target: &Certificate) -> Certificate {
674        // Set issuer to our HashedId8
675        let mut new_base = target.base().clone();
676        new_base.issuer = self.cert.issuer_identifier();
677
678        let target_with_issuer = Certificate::from_asn(
679            EtsiTs103097Certificate(AsnCertificate(new_base)),
680            Some(self.cert.clone()),
681        );
682        self.sign_certificate(backend, &target_with_issuer)
683    }
684
685    /// Create a brand-new self-signed certificate (NIST P-256 key).
686    pub fn initialize_self_signed(backend: &mut EcdsaBackend, tbs: ToBeSignedCertificate) -> Self {
687        Self::initialize_self_signed_with(backend, tbs, KeyAlgorithm::NistP256)
688    }
689
690    /// Create a brand-new self-signed certificate with a key on `algorithm`.
691    pub fn initialize_self_signed_with(
692        backend: &mut EcdsaBackend,
693        tbs: ToBeSignedCertificate,
694        algorithm: KeyAlgorithm,
695    ) -> Self {
696        let key_id = backend.create_key_with(algorithm);
697        let pk = backend.get_public_key(key_id);
698        let sha384 = key_uses_sha384(&pk);
699
700        let mut tbs_owned = tbs;
701        tbs_owned.verify_key_indicator = VerificationKeyIndicator::verificationKey(pk);
702
703        // Placeholder signature — will be replaced below.
704        let placeholder_sig = Ieee1609Signature::ecdsaNistP256Signature(EcdsaP256Signature {
705            r_sig: EccP256CurvePoint::x_only(vec![0u8; 32].into()),
706            s_sig: vec![0u8; 32].into(),
707        });
708
709        let base = CertificateBase::new(
710            Uint8(3),
711            CertificateType::explicit,
712            IssuerIdentifier::R_self(if sha384 {
713                HashAlgorithm::sha384
714            } else {
715                HashAlgorithm::sha256
716            }),
717            tbs_owned,
718            Some(placeholder_sig),
719        );
720
721        // Sign the toBeSigned
722        // IEEE 1609.2 clause 5.3.1: self-signed, the signer input is empty
723        let tbs_bytes = encode_tbs_certificate(&base.to_be_signed);
724        let sig = backend.sign(&signing_input(&tbs_bytes, &[], sha384), key_id);
725
726        let mut final_base = base;
727        final_base.signature = Some(sig);
728
729        let asn = EtsiTs103097Certificate(AsnCertificate(final_base));
730        let cert = Certificate::from_asn(asn, None);
731        OwnCertificate { cert, key_id }
732    }
733
734    /// Create a new certificate issued by `issuer`.
735    /// Issue an implicit certificate with ECQV (SEC 4 sections 3.3 to 3.6,
736    /// as profiled by IEEE Std 1609.2-2016 clause 5.3.2) and return it with
737    /// the reconstructed private key of its holder. The requester and the CA
738    /// role are combined: k_U is the requester key, k the CA ephemeral key,
739    /// P_U = (k_U + k) * G, r = e * k + d_CA and d_U = e * k_U + r.
740    /// Only a NIST P-256 issuer key is supported.
741    pub fn issue_implicit_certificate(
742        &self,
743        backend: &mut EcdsaBackend,
744        tbs: ToBeSignedCertificate,
745    ) -> OwnCertificate {
746        use p256::elliptic_curve::ff::{Field, PrimeField};
747        use p256::elliptic_curve::sec1::ToEncodedPoint;
748        let mut rng = rand::thread_rng();
749        let (k_u, k) = (
750            p256::Scalar::random(&mut rng),
751            p256::Scalar::random(&mut rng),
752        );
753        let p_u = (p256::ProjectivePoint::GENERATOR * (k_u + k)).to_affine();
754        let encoded = p_u.to_encoded_point(true);
755        let x = encoded.x().expect("x").to_vec().into();
756        let rv = if encoded.as_bytes()[0] == 0x02 {
757            EccP256CurvePoint::compressed_y_0(x)
758        } else {
759            EccP256CurvePoint::compressed_y_1(x)
760        };
761        let mut tbs = tbs;
762        tbs.verify_key_indicator = VerificationKeyIndicator::reconstructionValue(rv);
763        let base = CertificateBase::new(
764            Uint8(3),
765            CertificateType::implicit,
766            IssuerIdentifier::sha256AndDigest(HashedId8(rasn::types::FixedOctetString::from(
767                self.as_hashedid8(),
768            ))),
769            tbs,
770            None,
771        );
772        let cert = Certificate::from_asn(
773            EtsiTs103097Certificate(AsnCertificate(base)),
774            Some(self.cert.clone()),
775        );
776        let e_bytes = cert.implicit_hash_integer().expect("issuer set");
777        let e =
778            Option::<p256::Scalar>::from(p256::Scalar::from_repr(e_bytes.into())).expect("e < n");
779        let d_ca_bytes: [u8; 32] = backend
780            .export_signing_key(self.key_id)
781            .try_into()
782            .expect("P-256 key");
783        let d_ca =
784            Option::<p256::Scalar>::from(p256::Scalar::from_repr(d_ca_bytes.into())).expect("key");
785        let d_u = e * k_u + (e * k + d_ca);
786        let key_id = backend.import_signing_key(&d_u.to_repr());
787        OwnCertificate { cert, key_id }
788    }
789
790    pub fn initialize_issued(
791        backend: &mut EcdsaBackend,
792        tbs: ToBeSignedCertificate,
793        issuer: &OwnCertificate,
794    ) -> Self {
795        Self::initialize_issued_with(backend, tbs, issuer, KeyAlgorithm::NistP256)
796    }
797
798    /// Create a new certificate issued by `issuer`, with a key on `algorithm`.
799    pub fn initialize_issued_with(
800        backend: &mut EcdsaBackend,
801        tbs: ToBeSignedCertificate,
802        issuer: &OwnCertificate,
803        algorithm: KeyAlgorithm,
804    ) -> Self {
805        Self::initialize_issued_key(backend, tbs, issuer, algorithm, true)
806    }
807
808    /// Create a new certificate issued by `issuer`, with a key on `algorithm`
809    /// given as a compressed or an uncompressed point.
810    pub fn initialize_issued_key(
811        backend: &mut EcdsaBackend,
812        tbs: ToBeSignedCertificate,
813        issuer: &OwnCertificate,
814        algorithm: KeyAlgorithm,
815        compressed_key: bool,
816    ) -> Self {
817        let key_id = backend.create_key_with(algorithm);
818        let pk = backend.get_public_key_compressed(key_id, compressed_key);
819
820        let mut tbs_owned = tbs;
821        tbs_owned.verify_key_indicator = VerificationKeyIndicator::verificationKey(pk);
822
823        let base = CertificateBase::new(
824            Uint8(3),
825            CertificateType::explicit,
826            issuer.cert.issuer_identifier(),
827            tbs_owned,
828            None, // will be filled by sign
829        );
830
831        let target = Certificate::from_asn(
832            EtsiTs103097Certificate(AsnCertificate(base)),
833            Some(issuer.cert.clone()),
834        );
835        let signed_cert = issuer.sign_certificate(backend, &target);
836        OwnCertificate {
837            cert: signed_cert,
838            key_id,
839        }
840    }
841}
842
843#[cfg(test)]
844mod tests {
845    use super::*;
846
847    use crate::security::ecdsa_backend::EcdsaBackend;
848    use rasn::prelude::*;
849
850    fn make_root_tbs() -> ToBeSignedCertificate {
851        use crate::security::security_asn::ieee1609_dot2::{
852            CertificateId, EndEntityType, PsidGroupPermissions, SequenceOfPsidGroupPermissions,
853        };
854        use crate::security::security_asn::ieee1609_dot2_base_types::{
855            CrlSeries, Duration as AsnDuration, HashedId3, Time32, Uint16, Uint32, ValidityPeriod,
856        };
857
858        let validity = ValidityPeriod::new(Time32(Uint32(0)), AsnDuration::years(Uint16(30)));
859
860        let perms = SequenceOfPsidGroupPermissions(vec![PsidGroupPermissions::new(
861            SubjectPermissions::all(()),
862            Integer::from(1),
863            Integer::from(0),
864            {
865                let mut bits = FixedBitString::<8>::default();
866                bits.set(0, true);
867                EndEntityType(bits)
868            },
869        )]);
870
871        let placeholder_pk =
872            PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::x_only(vec![0u8; 32].into()));
873
874        ToBeSignedCertificate::new(
875            CertificateId::none(()),
876            HashedId3(FixedOctetString::from([0u8; 3])),
877            CrlSeries(Uint16(0)),
878            validity,
879            None,
880            None,
881            None,
882            Some(perms),
883            None,
884            None,
885            None,
886            VerificationKeyIndicator::verificationKey(placeholder_pk),
887            None,
888            None,
889            None,
890            None,
891        )
892    }
893
894    fn make_at_tbs() -> ToBeSignedCertificate {
895        use crate::security::security_asn::ieee1609_dot2::CertificateId;
896        use crate::security::security_asn::ieee1609_dot2_base_types::{
897            CrlSeries, Duration as AsnDuration, HashedId3, Psid, PsidSsp, SequenceOfPsidSsp,
898            Time32, Uint16, Uint32, ValidityPeriod,
899        };
900
901        let validity = ValidityPeriod::new(Time32(Uint32(0)), AsnDuration::years(Uint16(1)));
902
903        let app_perms = SequenceOfPsidSsp(vec![PsidSsp::new(Psid(Integer::from(36_i64)), None)]);
904
905        let placeholder_pk =
906            PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::x_only(vec![0u8; 32].into()));
907
908        ToBeSignedCertificate::new(
909            CertificateId::none(()),
910            HashedId3(FixedOctetString::from([0u8; 3])),
911            CrlSeries(Uint16(0)),
912            validity,
913            None,
914            None,
915            Some(app_perms),
916            None,
917            None,
918            None,
919            None,
920            VerificationKeyIndicator::verificationKey(placeholder_pk),
921            None,
922            None,
923            None,
924            None,
925        )
926    }
927
928    /// IEEE 1609.2 clause 6.4.3: a certificate is hashed with every point of
929    /// toBeSigned compressed and the signature r as x-only, on every curve.
930    #[test]
931    fn uncompressed_points_hash_as_compressed() {
932        use crate::security::ecdsa_backend::KeyAlgorithm;
933        use crate::security::security_asn::ieee1609_dot2_base_types::{
934            EcdsaP384Signature, PublicEncryptionKey, SymmAlgorithm,
935        };
936        let mut backend = EcdsaBackend::new();
937        for algorithm in [
938            KeyAlgorithm::NistP256,
939            KeyAlgorithm::BrainpoolP256r1,
940            KeyAlgorithm::BrainpoolP384r1,
941            KeyAlgorithm::NistP384,
942        ] {
943            let key = backend.create_key_with(algorithm);
944            let encryption = backend.create_key();
945            // r given as a point: reuse the key point (only the encoding matters here)
946            let signature = |compressed_r: bool| -> Ieee1609Signature {
947                let point = backend.get_public_key_compressed(key, true);
948                match point {
949                    PublicVerificationKey::ecdsaNistP256(p)
950                    | PublicVerificationKey::ecdsaBrainpoolP256r1(p) => {
951                        let x = match &p {
952                            EccP256CurvePoint::compressed_y_0(x)
953                            | EccP256CurvePoint::compressed_y_1(x) => x.clone(),
954                            _ => unreachable!(),
955                        };
956                        let r = if compressed_r {
957                            p.clone()
958                        } else {
959                            EccP256CurvePoint::x_only(x)
960                        };
961                        let sig = EcdsaP256Signature {
962                            r_sig: r,
963                            s_sig: vec![1u8; 32].into(),
964                        };
965                        if matches!(algorithm, KeyAlgorithm::NistP256) {
966                            Ieee1609Signature::ecdsaNistP256Signature(sig)
967                        } else {
968                            Ieee1609Signature::ecdsaBrainpoolP256r1Signature(sig)
969                        }
970                    }
971                    PublicVerificationKey::ecdsaBrainpoolP384r1(p)
972                    | PublicVerificationKey::ecdsaNistP384(p) => {
973                        let x = match &p {
974                            EccP384CurvePoint::compressed_y_0(x)
975                            | EccP384CurvePoint::compressed_y_1(x) => x.clone(),
976                            _ => unreachable!(),
977                        };
978                        let r = if compressed_r {
979                            p.clone()
980                        } else {
981                            EccP384CurvePoint::x_only(x)
982                        };
983                        let sig = EcdsaP384Signature {
984                            r_sig: r,
985                            s_sig: vec![1u8; 48].into(),
986                        };
987                        if matches!(algorithm, KeyAlgorithm::NistP384) {
988                            Ieee1609Signature::ecdsaNistP384Signature(sig)
989                        } else {
990                            Ieee1609Signature::ecdsaBrainpoolP384r1Signature(sig)
991                        }
992                    }
993                    _ => unreachable!(),
994                }
995            };
996            let certificate = |compressed: bool, compressed_r: bool| -> Certificate {
997                let mut tbs = make_at_tbs();
998                tbs.verify_key_indicator = VerificationKeyIndicator::verificationKey(
999                    backend.get_public_key_compressed(key, compressed),
1000                );
1001                let PublicVerificationKey::ecdsaNistP256(point) =
1002                    backend.get_public_key_compressed(encryption, compressed)
1003                else {
1004                    unreachable!()
1005                };
1006                tbs.encryption_key = Some(PublicEncryptionKey::new(
1007                    SymmAlgorithm::aes128Ccm,
1008                    BasePublicEncryptionKey::eciesNistP256(point),
1009                ));
1010                let base = CertificateBase::new(
1011                    Uint8(3),
1012                    CertificateType::explicit,
1013                    IssuerIdentifier::R_self(HashAlgorithm::sha256),
1014                    tbs,
1015                    Some(signature(compressed_r)),
1016                );
1017                Certificate::from_asn(EtsiTs103097Certificate(AsnCertificate(base)), None)
1018            };
1019            let reference = certificate(true, false);
1020            for (compressed, compressed_r) in [(false, false), (false, true), (true, true)] {
1021                let variant = certificate(compressed, compressed_r);
1022                assert_eq!(
1023                    variant.as_hashedid8(),
1024                    reference.as_hashedid8(),
1025                    "{algorithm:?}"
1026                );
1027                assert_eq!(
1028                    variant.to_canonical().encode(),
1029                    reference.encode(),
1030                    "{algorithm:?}"
1031                );
1032            }
1033        }
1034    }
1035
1036    #[test]
1037    fn own_certificate_self_signed_roundtrip() {
1038        let mut backend = EcdsaBackend::new();
1039        let own = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1040        assert!(own.verify(&backend));
1041        assert!(own.cert.is_self_signed());
1042        assert!(!own.cert.is_issued());
1043    }
1044
1045    #[test]
1046    fn own_certificate_issued_roundtrip() {
1047        let mut backend = EcdsaBackend::new();
1048        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1049        let at = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(), &root);
1050        assert!(at.verify(&backend));
1051        assert!(at.cert.is_issued());
1052        assert!(!at.cert.is_self_signed());
1053    }
1054
1055    #[test]
1056    fn certificate_hashedid8_and_hashedid3() {
1057        let mut backend = EcdsaBackend::new();
1058        let own = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1059        let h8 = own.as_hashedid8();
1060        let h3 = own.cert.as_hashedid3();
1061        assert_eq!(h3, [h8[5], h8[6], h8[7]]);
1062    }
1063
1064    #[test]
1065    fn certificate_encode_decode_roundtrip() {
1066        let mut backend = EcdsaBackend::new();
1067        let own = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1068        let encoded = own.cert.encode().to_vec();
1069        let decoded = Certificate::from_bytes(&encoded, None);
1070        assert_eq!(decoded.as_hashedid8(), own.as_hashedid8());
1071    }
1072
1073    #[test]
1074    fn certificate_from_asn_and_from_bytes_same_hash() {
1075        let mut backend = EcdsaBackend::new();
1076        let own = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1077        let bytes = own.cert.encode().to_vec();
1078        let c1 = Certificate::from_bytes(&bytes, None);
1079        let c2 = Certificate::from_asn(own.cert.inner.clone(), None);
1080        assert_eq!(c1.as_hashedid8(), c2.as_hashedid8());
1081    }
1082
1083    #[test]
1084    fn certificate_check_corresponding_issuer() {
1085        let mut backend = EcdsaBackend::new();
1086        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1087        let at = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(), &root);
1088        assert!(at.cert.check_corresponding_issuer(&root.cert));
1089    }
1090
1091    #[test]
1092    fn certificate_signature_is_nist_p256() {
1093        let mut backend = EcdsaBackend::new();
1094        let own = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1095        assert!(own.cert.signature_is_nist_p256());
1096        assert!(own.cert.verification_key_is_nist_p256());
1097    }
1098
1099    #[test]
1100    fn certificate_has_all_permissions() {
1101        let mut backend = EcdsaBackend::new();
1102        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1103        assert!(root.cert.has_all_permissions());
1104    }
1105
1106    #[test]
1107    fn certificate_get_list_of_its_aid() {
1108        let mut backend = EcdsaBackend::new();
1109        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1110        let at = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(), &root);
1111        let aids = at.get_list_of_its_aid();
1112        assert!(aids.contains(&36));
1113    }
1114
1115    #[test]
1116    fn certificate_sign_message() {
1117        let mut backend = EcdsaBackend::new();
1118        let own = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1119        let sig = own.sign_message(&backend, b"test data");
1120        let pk = backend.get_public_key(own.key_id);
1121        // IEEE 1609.2 clause 5.3.1: Hash(data) || Hash(signer certificate)
1122        let input = signing_input(b"test data", own.to_canonical().encode(), false);
1123        assert!(backend.verify_with_pk(&input, &sig, &pk));
1124        assert!(!backend.verify_with_pk(b"test data", &sig, &pk));
1125    }
1126
1127    #[test]
1128    fn certificate_verify_type_explicit() {
1129        let mut backend = EcdsaBackend::new();
1130        let own = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1131        assert_eq!(own.cert.base().r_type, CertificateType::explicit);
1132    }
1133
1134    #[test]
1135    fn certificate_at_is_authorization_ticket() {
1136        let mut backend = EcdsaBackend::new();
1137        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1138        let at = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(), &root);
1139        assert!(at.cert.is_authorization_ticket());
1140    }
1141
1142    #[test]
1143    fn certificate_self_signed_get_issuer_hashedid8_none() {
1144        let mut backend = EcdsaBackend::new();
1145        let own = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1146        assert!(own.cert.get_issuer_hashedid8().is_none());
1147    }
1148
1149    #[test]
1150    fn certificate_issued_get_issuer_hashedid8_some() {
1151        let mut backend = EcdsaBackend::new();
1152        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1153        let at = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(), &root);
1154        let issuer_h8 = at.cert.get_issuer_hashedid8();
1155        assert!(issuer_h8.is_some());
1156        assert_eq!(issuer_h8.unwrap(), root.as_hashedid8());
1157    }
1158
1159    #[test]
1160    fn certificate_decode_pythonpki_certs_if_present() {
1161        let rca_path = std::path::Path::new(
1162            "/home/jordimarias/Desktop/IDIADAPKI/pythonpki/rca_data/rca_cert.coer",
1163        );
1164        let ea_path =
1165            std::path::Path::new("/home/jordimarias/Desktop/IDIADAPKI/pythonpki/ea_data/cert.coer");
1166        let aa_path =
1167            std::path::Path::new("/home/jordimarias/Desktop/IDIADAPKI/pythonpki/aa_data/cert.coer");
1168
1169        if rca_path.exists() {
1170            let bytes = std::fs::read(rca_path).expect("read rca");
1171            let cert = Certificate::from_bytes(&bytes, None);
1172            assert_eq!(cert.base().r_type, CertificateType::explicit);
1173        }
1174        if ea_path.exists() {
1175            let bytes = std::fs::read(ea_path).expect("read ea");
1176            let cert = Certificate::from_bytes(&bytes, None);
1177            assert_eq!(cert.base().r_type, CertificateType::explicit);
1178        }
1179        if aa_path.exists() {
1180            let bytes = std::fs::read(aa_path).expect("read aa");
1181            let cert = Certificate::from_bytes(&bytes, None);
1182            assert_eq!(cert.base().r_type, CertificateType::explicit);
1183        }
1184    }
1185
1186    #[test]
1187    fn test_to_canonical() {
1188        use crate::security::security_asn::ieee1609_dot2_base_types::EccP256CurvePointUncompressedP256;
1189
1190        let uncompressed_x = vec![1u8; 32];
1191        let mut uncompressed_y_even = vec![2u8; 31];
1192        uncompressed_y_even.push(2); // even y -> compressed_y_0
1193        let mut uncompressed_y_odd = vec![2u8; 31];
1194        uncompressed_y_odd.push(3); // odd y -> compressed_y_1
1195
1196        // 1. Uncompressed verification key (even) and compressed_y_0 r_sig
1197        let mut tbs_even = make_root_tbs();
1198        tbs_even.verify_key_indicator =
1199            VerificationKeyIndicator::verificationKey(PublicVerificationKey::ecdsaNistP256(
1200                EccP256CurvePoint::uncompressedP256(EccP256CurvePointUncompressedP256 {
1201                    x: uncompressed_x.clone().into(),
1202                    y: uncompressed_y_even.into(),
1203                }),
1204            ));
1205
1206        let sig_even = Ieee1609Signature::ecdsaNistP256Signature(EcdsaP256Signature {
1207            r_sig: EccP256CurvePoint::compressed_y_0(vec![5u8; 32].into()),
1208            s_sig: vec![6u8; 32].into(),
1209        });
1210
1211        let base_even = CertificateBase::new(
1212            Uint8(3),
1213            CertificateType::explicit,
1214            IssuerIdentifier::R_self(HashAlgorithm::sha256),
1215            tbs_even,
1216            Some(sig_even),
1217        );
1218
1219        let cert_even =
1220            Certificate::from_asn(EtsiTs103097Certificate(AsnCertificate(base_even)), None);
1221        let canon_even = cert_even.to_canonical();
1222
1223        // Check key compressed to compressed_y_0
1224        match &canon_even.tbs().verify_key_indicator {
1225            VerificationKeyIndicator::verificationKey(PublicVerificationKey::ecdsaNistP256(
1226                EccP256CurvePoint::compressed_y_0(x),
1227            )) => {
1228                assert_eq!(x.as_ref(), uncompressed_x.as_slice());
1229            }
1230            _ => panic!("Expected compressed_y_0 verification key"),
1231        }
1232
1233        // Check signature r_sig converted to x_only
1234        match &canon_even.base().signature {
1235            Some(Ieee1609Signature::ecdsaNistP256Signature(sig)) => {
1236                match &sig.r_sig {
1237                    EccP256CurvePoint::x_only(x) => {
1238                        assert_eq!(x.as_ref(), vec![5u8; 32].as_slice());
1239                    }
1240                    _ => panic!("Expected x_only r_sig"),
1241                }
1242                assert_eq!(sig.s_sig.as_ref(), vec![6u8; 32].as_slice());
1243            }
1244            _ => panic!("Expected ecdsaNistP256Signature"),
1245        }
1246
1247        // 2. Uncompressed verification key (odd) and compressed_y_1 r_sig
1248        let mut tbs_odd = make_root_tbs();
1249        tbs_odd.verify_key_indicator =
1250            VerificationKeyIndicator::verificationKey(PublicVerificationKey::ecdsaNistP256(
1251                EccP256CurvePoint::uncompressedP256(EccP256CurvePointUncompressedP256 {
1252                    x: uncompressed_x.clone().into(),
1253                    y: uncompressed_y_odd.into(),
1254                }),
1255            ));
1256
1257        let sig_odd = Ieee1609Signature::ecdsaNistP256Signature(EcdsaP256Signature {
1258            r_sig: EccP256CurvePoint::compressed_y_1(vec![7u8; 32].into()),
1259            s_sig: vec![8u8; 32].into(),
1260        });
1261
1262        let base_odd = CertificateBase::new(
1263            Uint8(3),
1264            CertificateType::explicit,
1265            IssuerIdentifier::R_self(HashAlgorithm::sha256),
1266            tbs_odd,
1267            Some(sig_odd),
1268        );
1269
1270        let cert_odd =
1271            Certificate::from_asn(EtsiTs103097Certificate(AsnCertificate(base_odd)), None);
1272        let canon_odd = cert_odd.to_canonical();
1273
1274        match &canon_odd.tbs().verify_key_indicator {
1275            VerificationKeyIndicator::verificationKey(PublicVerificationKey::ecdsaNistP256(
1276                EccP256CurvePoint::compressed_y_1(x),
1277            )) => {
1278                assert_eq!(x.as_ref(), uncompressed_x.as_slice());
1279            }
1280            _ => panic!("Expected compressed_y_1 verification key"),
1281        }
1282
1283        match &canon_odd.base().signature {
1284            Some(Ieee1609Signature::ecdsaNistP256Signature(sig)) => {
1285                match &sig.r_sig {
1286                    EccP256CurvePoint::x_only(x) => {
1287                        assert_eq!(x.as_ref(), vec![7u8; 32].as_slice());
1288                    }
1289                    _ => panic!("Expected x_only r_sig"),
1290                }
1291                assert_eq!(sig.s_sig.as_ref(), vec![8u8; 32].as_slice());
1292            }
1293            _ => panic!("Expected ecdsaNistP256Signature"),
1294        }
1295
1296        // 3. Already canonical remains identical
1297        let canon_again = canon_even.to_canonical();
1298        assert_eq!(canon_even, canon_again);
1299    }
1300
1301    #[test]
1302    fn test_as_hashedid8_canonical_equivalence() {
1303        use crate::security::security_asn::ieee1609_dot2_base_types::EccP256CurvePointUncompressedP256;
1304
1305        let uncompressed_x = vec![1u8; 32];
1306        let mut uncompressed_y = vec![2u8; 31];
1307        uncompressed_y.push(2); // even -> compressed_y_0
1308
1309        let mut tbs_uncomp = make_root_tbs();
1310        tbs_uncomp.verify_key_indicator =
1311            VerificationKeyIndicator::verificationKey(PublicVerificationKey::ecdsaNistP256(
1312                EccP256CurvePoint::uncompressedP256(EccP256CurvePointUncompressedP256 {
1313                    x: uncompressed_x.clone().into(),
1314                    y: uncompressed_y.into(),
1315                }),
1316            ));
1317
1318        let sig = Ieee1609Signature::ecdsaNistP256Signature(EcdsaP256Signature {
1319            r_sig: EccP256CurvePoint::x_only(vec![5u8; 32].into()),
1320            s_sig: vec![6u8; 32].into(),
1321        });
1322
1323        let cert_uncompressed = Certificate::from_asn(
1324            EtsiTs103097Certificate(AsnCertificate(CertificateBase::new(
1325                Uint8(3),
1326                CertificateType::explicit,
1327                IssuerIdentifier::R_self(HashAlgorithm::sha256),
1328                tbs_uncomp,
1329                Some(sig.clone()),
1330            ))),
1331            None,
1332        );
1333
1334        let mut tbs_comp = make_root_tbs();
1335        tbs_comp.verify_key_indicator =
1336            VerificationKeyIndicator::verificationKey(PublicVerificationKey::ecdsaNistP256(
1337                EccP256CurvePoint::compressed_y_0(uncompressed_x.into()),
1338            ));
1339
1340        let cert_compressed = Certificate::from_asn(
1341            EtsiTs103097Certificate(AsnCertificate(CertificateBase::new(
1342                Uint8(3),
1343                CertificateType::explicit,
1344                IssuerIdentifier::R_self(HashAlgorithm::sha256),
1345                tbs_comp,
1346                Some(sig),
1347            ))),
1348            None,
1349        );
1350
1351        assert_eq!(
1352            cert_uncompressed.as_hashedid8(),
1353            cert_compressed.as_hashedid8()
1354        );
1355    }
1356
1357    #[test]
1358    fn test_issued_certificate_digest_verification() {
1359        use crate::security::security_asn::ieee1609_dot2::CertificateId;
1360        use crate::security::security_asn::ieee1609_dot2_base_types::Hostname;
1361
1362        let mut backend = EcdsaBackend::new();
1363        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
1364        assert!(root.verify(&backend));
1365
1366        let child = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(), &root);
1367        assert!(child.verify(&backend));
1368
1369        // Tamper with toBeSigned in child cert
1370        let mut tampered_base = child.cert.base().clone();
1371        tampered_base.to_be_signed.id = CertificateId::name(Hostname("tampered-ee".to_string()));
1372        let tampered_cert = Certificate::from_asn(
1373            EtsiTs103097Certificate(AsnCertificate(tampered_base)),
1374            Some(root.cert.clone()),
1375        );
1376        assert!(!tampered_cert.verify(&backend));
1377    }
1378}