purecrypto 0.6.1

A pure-Rust cryptography toolkit with no foreign-code dependencies, from constant-time primitives up to keys, X.509 and TLS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! X.509 v2 Certificate Revocation Lists (RFC 5280 §5).
//!
//! A CRL is a signed list of revoked certificate serials, scoped to one
//! issuer. The signer is the same authority that issued the certificates
//! being revoked. `purecrypto`'s `tls::pki` chain validator consults a
//! [`crate::tls::pki::CrlStore`] of these objects to short-circuit any
//! signed-by-the-anchor certificate that appears in a covering CRL.
//!
//! The wire format (RFC 5280 §5.1):
//!
//! ```text
//! CertificateList  ::=  SEQUENCE {
//!     tbsCertList          TBSCertList,
//!     signatureAlgorithm   AlgorithmIdentifier,
//!     signatureValue       BIT STRING
//! }
//!
//! TBSCertList  ::=  SEQUENCE {
//!     version              Version OPTIONAL,         -- v2 = 1 here
//!     signature            AlgorithmIdentifier,      -- inner; MUST equal outer
//!     issuer               Name,
//!     thisUpdate           Time,
//!     nextUpdate           Time OPTIONAL,
//!     revokedCertificates  SEQUENCE OF SEQUENCE {
//!         userCertificate     CertificateSerialNumber,  -- INTEGER
//!         revocationDate      Time,
//!         crlEntryExtensions  Extensions OPTIONAL
//!     } OPTIONAL,
//!     crlExtensions        [0] EXPLICIT Extensions OPTIONAL
//! }
//! ```
//!
//! See [`CertificateRevocationList`] and [`CrlBuilder`] for the read/write APIs.

use alloc::string::String;
use alloc::vec::Vec;

use super::{AnyPublicKey, CertSigner, DistinguishedName, Error, Time, oid};
use crate::der::{
    Reader, encode_bit_string, encode_integer, encode_octet_string, encode_sequence, encode_tlv,
    oid_tlv, parse_oid, pem_decode, pem_encode, tag,
};

const PEM_LABEL: &str = "X509 CRL";

/// Reasons a certificate may be revoked (RFC 5280 §5.3.1).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum CrlReason {
    /// `unspecified` (0). No `crlEntryExtensions` will be emitted when this
    /// is the only reason on an entry.
    Unspecified = 0,
    /// `keyCompromise` (1).
    KeyCompromise = 1,
    /// `cACompromise` (2).
    CACompromise = 2,
    /// `affiliationChanged` (3).
    AffiliationChanged = 3,
    /// `superseded` (4).
    Superseded = 4,
    /// `cessationOfOperation` (5).
    CessationOfOperation = 5,
    /// `certificateHold` (6).
    CertificateHold = 6,
    /// `removeFromCRL` (8). Only meaningful in delta-CRLs.
    RemoveFromCRL = 8,
    /// `privilegeWithdrawn` (9).
    PrivilegeWithdrawn = 9,
    /// `aACompromise` (10).
    AaCompromise = 10,
}

impl CrlReason {
    /// Parses a single-byte ENUMERATED value into a `CrlReason`. Returns
    /// `Err(Error::Malformed)` for values outside the set defined in
    /// RFC 5280 §5.3.1 (value 7 is reserved; values ≥ 11 are unassigned).
    /// Callers that want a permissive mapping can `.unwrap_or(Unspecified)`
    /// explicitly.
    pub fn from_u8(v: u8) -> Result<Self, Error> {
        match v {
            0 => Ok(CrlReason::Unspecified),
            1 => Ok(CrlReason::KeyCompromise),
            2 => Ok(CrlReason::CACompromise),
            3 => Ok(CrlReason::AffiliationChanged),
            4 => Ok(CrlReason::Superseded),
            5 => Ok(CrlReason::CessationOfOperation),
            6 => Ok(CrlReason::CertificateHold),
            8 => Ok(CrlReason::RemoveFromCRL),
            9 => Ok(CrlReason::PrivilegeWithdrawn),
            10 => Ok(CrlReason::AaCompromise),
            _ => Err(Error::Malformed),
        }
    }
}

/// One row in the CRL's `revokedCertificates` list.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RevokedCertificate {
    /// Raw serial INTEGER body, big-endian (strict-DER canonical: at most
    /// one leading `0x00` to keep the value non-negative).
    pub serial: Vec<u8>,
    /// Time at which the certificate was revoked.
    pub revocation_date: Time,
    /// Optional reason code from the `cRLReason` entry extension.
    pub reason: Option<CrlReason>,
}

/// A signed, DER-encoded X.509 v2 CRL.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CertificateRevocationList {
    der: Vec<u8>,
}

/// Builder for a [`CertificateRevocationList`].
pub struct CrlBuilder {
    issuer_der: Vec<u8>,
    this_update: Time,
    next_update: Option<Time>,
    entries: Vec<RevokedCertificate>,
}

impl CrlBuilder {
    /// Starts a new CRL keyed by `issuer`.
    pub fn new(issuer: &DistinguishedName, this_update: Time, next_update: Option<Time>) -> Self {
        CrlBuilder {
            issuer_der: issuer.to_der(),
            this_update,
            next_update,
            entries: Vec::new(),
        }
    }

    /// Adds a revoked entry. `serial_be` is the raw big-endian serial number
    /// (the integer magnitude); it is canonicalized into a strict-DER INTEGER
    /// body at sign time.
    pub fn revoke(
        &mut self,
        serial_be: &[u8],
        revocation_date: Time,
        reason: Option<CrlReason>,
    ) -> &mut Self {
        self.entries.push(RevokedCertificate {
            serial: serial_be.to_vec(),
            revocation_date,
            reason,
        });
        self
    }

    /// Signs the accumulated CRL with `signer`, producing a
    /// [`CertificateRevocationList`].
    pub fn sign(self, signer: &CertSigner<'_>) -> Result<CertificateRevocationList, Error> {
        let algid = signer.algorithm_identifier();
        let tbs = encode_tbs_cert_list(
            &self.issuer_der,
            &self.this_update,
            self.next_update.as_ref(),
            &self.entries,
            &algid,
        );
        let sig = signer.sign(&tbs)?;
        let der = encode_sequence(&[tbs, algid, encode_bit_string(&sig)].concat());
        Ok(CertificateRevocationList { der })
    }
}

/// Encodes a `cRLReason` per-entry extension carrying an ENUMERATED.
fn crl_reason_extension(reason: CrlReason) -> Vec<u8> {
    // ENUMERATED ::= a single-byte body for the reason code.
    let enumerated = encode_tlv(0x0a, &[reason as u8]);
    let mut ext = oid_tlv(oid::CRL_REASON_CODE);
    ext.extend_from_slice(&encode_octet_string(&enumerated));
    encode_sequence(&ext)
}

/// Encodes one row of `revokedCertificates`.
fn encode_revoked(entry: &RevokedCertificate) -> Vec<u8> {
    let serial = encode_integer(&entry.serial);
    let rdate = entry.revocation_date.to_der_choice();
    let mut body = Vec::new();
    body.extend_from_slice(&serial);
    body.extend_from_slice(&rdate);
    if let Some(reason) = entry.reason
        && reason != CrlReason::Unspecified
    {
        // `crlEntryExtensions ::= Extensions ::= SEQUENCE OF Extension`.
        let ext = crl_reason_extension(reason);
        body.extend_from_slice(&encode_sequence(&ext));
    }
    encode_sequence(&body)
}

/// Encodes a `TBSCertList`, with the inner `signature` algid set to `algid`
/// (DER bytes — the outer `signatureAlgorithm` must equal this).
fn encode_tbs_cert_list(
    issuer_der: &[u8],
    this_update: &Time,
    next_update: Option<&Time>,
    entries: &[RevokedCertificate],
    algid: &[u8],
) -> Vec<u8> {
    let mut body = Vec::new();
    // version = v2 (1) — required when extensions or v2 fields are present.
    body.extend_from_slice(&encode_integer(&[1]));
    body.extend_from_slice(algid);
    body.extend_from_slice(issuer_der);
    body.extend_from_slice(&this_update.to_der_choice());
    if let Some(n) = next_update {
        body.extend_from_slice(&n.to_der_choice());
    }
    if !entries.is_empty() {
        let mut list = Vec::new();
        for e in entries {
            list.extend_from_slice(&encode_revoked(e));
        }
        body.extend_from_slice(&encode_sequence(&list));
    }
    // `crlExtensions [0] EXPLICIT Extensions OPTIONAL` — none emitted here.
    encode_sequence(&body)
}

/// The three top-level parts of a `CertificateList`.
struct CrlParts<'a> {
    /// Raw `TBSCertList` TLV (used for signature verification).
    tbs: &'a [u8],
    /// Outer signature algorithm OID arcs.
    sig_alg: Vec<u64>,
    /// Signature bits.
    signature: &'a [u8],
}

impl CertificateRevocationList {
    /// Wraps existing CRL DER. Validates only that it is a single SEQUENCE
    /// with no trailing bytes (strict, matching the certificate parser).
    pub fn from_der(der: Vec<u8>) -> Result<Self, Error> {
        let mut r = Reader::new(&der);
        r.read_sequence()?;
        r.finish()?;
        Ok(CertificateRevocationList { der })
    }

    /// Parses a PEM `X509 CRL` document (RFC 7468 label).
    pub fn from_pem(pem: &str) -> Result<Self, Error> {
        Ok(CertificateRevocationList {
            der: pem_decode(pem, PEM_LABEL)?,
        })
    }

    /// The DER encoding.
    pub fn to_der(&self) -> &[u8] {
        &self.der
    }

    /// The PEM encoding.
    pub fn to_pem(&self) -> String {
        pem_encode(PEM_LABEL, &self.der)
    }

    /// Splits the outer CRL into its three top-level parts.
    fn parts(&self) -> Result<CrlParts<'_>, Error> {
        let mut outer = Reader::new(&self.der);
        let mut crl = outer.read_sequence()?;
        let tbs = crl.read_element()?;
        let mut alg = crl.read_sequence()?;
        let sig_alg = parse_oid(alg.read_oid()?)?;
        let signature = crl.read_bit_string()?;
        // Strict DER (X.690 §11): no trailing bytes inside the outer
        // SEQUENCE.
        crl.finish()?;
        Ok(CrlParts {
            tbs,
            sig_alg,
            signature,
        })
    }

    /// Sub-reader over the `TBSCertList` body, positioned after the inner
    /// signature `AlgorithmIdentifier`.
    fn tbs_after_algid(&self) -> Result<Reader<'_>, Error> {
        let tbs = self.parts()?.tbs;
        let mut outer = Reader::new(tbs);
        let mut seq = outer.read_sequence()?;
        // Optional INTEGER version; v2 = 1. RFC 5280 §5.1 defines only v1
        // (absent) and v2 (1) — anything else is malformed.
        if seq.peek_tag() == Some(tag::INTEGER) {
            let v = seq.read_integer_bytes()?;
            // Single-byte 0 (v1) or 1 (v2); reject everything else.
            if v.len() != 1 || (v[0] != 0 && v[0] != 1) {
                return Err(Error::Malformed);
            }
        }
        seq.read_sequence()?; // inner signature AlgorithmIdentifier
        Ok(seq)
    }

    /// Returns the DER bytes of the inner `signature` AlgorithmIdentifier
    /// inside `TBSCertList`.
    pub(crate) fn inner_signature_algid_der(&self) -> Result<&[u8], Error> {
        let tbs = self.parts()?.tbs;
        let mut outer = Reader::new(tbs);
        let mut seq = outer.read_sequence()?;
        if seq.peek_tag() == Some(tag::INTEGER) {
            let v = seq.read_integer_bytes()?;
            if v.len() != 1 || (v[0] != 0 && v[0] != 1) {
                return Err(Error::Malformed);
            }
        }
        Ok(seq.read_element()?)
    }

    /// Returns the DER bytes of the outer `signatureAlgorithm`
    /// AlgorithmIdentifier (RFC 5280 §5.1.1.2).
    pub(crate) fn outer_signature_algid_der(&self) -> Result<&[u8], Error> {
        let mut outer = Reader::new(&self.der);
        let mut crl = outer.read_sequence()?;
        crl.read_element()?; // skip TBSCertList
        Ok(crl.read_element()?)
    }

    /// RFC 5280 §5.1.1.2: the inner and outer signature AlgorithmIdentifier
    /// fields MUST be identical. Compares raw DER (parameters included),
    /// mirroring `super::Certificate::check_signature_algid_consistent`.
    pub fn check_signature_algid_consistent(&self) -> Result<(), Error> {
        let inner = self.inner_signature_algid_der()?;
        let outer = self.outer_signature_algid_der()?;
        if inner == outer {
            Ok(())
        } else {
            Err(Error::Malformed)
        }
    }

    /// The CRL issuer.
    pub fn issuer(&self) -> Result<DistinguishedName, Error> {
        let mut seq = self.tbs_after_algid()?;
        DistinguishedName::decode(&mut seq)
    }

    /// The raw DER bytes of the CRL's `issuer` field — the full `Name` TLV.
    pub fn issuer_der(&self) -> Result<&[u8], Error> {
        let mut seq = self.tbs_after_algid()?;
        Ok(seq.read_element()?)
    }

    /// `thisUpdate`.
    pub fn this_update(&self) -> Result<Time, Error> {
        let mut seq = self.tbs_after_algid()?;
        seq.read_element()?; // issuer
        read_time(&mut seq)
    }

    /// `nextUpdate`, if present.
    pub fn next_update(&self) -> Result<Option<Time>, Error> {
        let mut seq = self.tbs_after_algid()?;
        seq.read_element()?; // issuer
        read_time(&mut seq)?; // thisUpdate
        if seq.is_empty() {
            return Ok(None);
        }
        match seq.peek_tag() {
            Some(t) if t == tag::UTC_TIME || t == tag::GENERALIZED_TIME => {
                read_time(&mut seq).map(Some)
            }
            _ => Ok(None),
        }
    }

    /// The OID arcs of the CRL's outer `signatureAlgorithm` field.
    pub fn signature_algorithm_oid(&self) -> Result<Vec<u64>, Error> {
        Ok(self.parts()?.sig_alg)
    }

    /// Verifies the CRL signature against `issuer_key`, dispatching on the
    /// CRL's `signatureAlgorithm` through the signature registry.
    ///
    /// As mandated by RFC 5280 §5.1.1.2, this first confirms the outer
    /// `signatureAlgorithm` is byte-identical to the inner
    /// `TBSCertList.signature` AlgorithmIdentifier (returning
    /// [`Error::Malformed`] otherwise), closing the signature-algorithm-
    /// confusion gap. The check is idempotent.
    ///
    /// SECURITY: this method applies **no** signature-algorithm-strength or
    /// key-size policy. A SHA-1- or MD5-based signature, or an undersized RSA
    /// key, will verify **successfully** here. Callers MUST enforce their own
    /// policy (e.g. via `SignaturePolicy::permits`, as the TLS path does in
    /// `tls::pki::verify`). Do not treat a successful return as
    /// evidence the algorithm is acceptable.
    pub fn verify_signature_with(&self, issuer_key: &AnyPublicKey) -> Result<(), Error> {
        self.check_signature_algid_consistent()?;
        let parts = self.parts()?;
        issuer_key.verify(&parts.sig_alg, parts.tbs, parts.signature)
    }

    /// Iterates the `revokedCertificates` entries. Returns an empty list if
    /// the field is absent.
    pub fn entries(&self) -> Result<Vec<RevokedCertificate>, Error> {
        let mut out = Vec::new();
        let mut seq = self.tbs_after_algid()?;
        seq.read_element()?; // issuer
        read_time(&mut seq)?; // thisUpdate

        // Skip nextUpdate when present.
        if let Some(t) = seq.peek_tag()
            && (t == tag::UTC_TIME || t == tag::GENERALIZED_TIME)
        {
            read_time(&mut seq)?;
        }

        // Optional revokedCertificates SEQUENCE OF SEQUENCE.
        if seq.peek_tag() == Some(tag::SEQUENCE) {
            let inner = seq.read_element()?;
            let mut r = Reader::new(inner);
            let mut list = r.read_sequence()?;
            while !list.is_empty() {
                let mut entry = list.read_sequence()?;
                let serial = entry.read_unsigned_integer_bytes()?.to_vec();
                let revocation_date = read_time(&mut entry)?;
                let mut reason = None;
                // Optional crlEntryExtensions (Extensions ::= SEQUENCE OF
                // Extension); scan for the cRLReason entry.
                if !entry.is_empty() {
                    let mut exts = entry.read_sequence()?;
                    while !exts.is_empty() {
                        let mut ext = exts.read_sequence()?;
                        let id = parse_oid(ext.read_oid()?)?;
                        let _critical = if ext.peek_tag() == Some(tag::BOOLEAN) {
                            ext.read_boolean()?
                        } else {
                            false
                        };
                        let value = ext.read_octet_string()?;
                        if id.as_slice() == oid::CRL_REASON_CODE {
                            let mut vr = Reader::new(value);
                            let enum_body = vr.read_tlv(0x0a)?;
                            // ENUMERATED is single-byte in practice for the
                            // values defined by RFC 5280 §5.3.1; reject out-
                            // of-range codes (including the reserved value 7
                            // and any unassigned value ≥ 11).
                            if enum_body.len() != 1 {
                                return Err(Error::Malformed);
                            }
                            reason = Some(CrlReason::from_u8(enum_body[0])?);
                        }
                    }
                }
                out.push(RevokedCertificate {
                    serial,
                    revocation_date,
                    reason,
                });
            }
        }
        Ok(out)
    }

    /// Whether `serial_be` (the raw INTEGER body, with at most one leading
    /// `0x00`) is revoked by this CRL.
    ///
    /// Comparison is on the *magnitude*: a leading sign-protection `0x00`
    /// is stripped from both sides, so `02 02 00 7F` matches `7F`.
    pub fn is_revoked(&self, serial_be: &[u8]) -> Result<bool, Error> {
        let needle = strip_leading_sign_zero(serial_be);
        for e in self.entries()? {
            if strip_leading_sign_zero(&e.serial) == needle {
                return Ok(true);
            }
        }
        Ok(false)
    }
}

/// Strips a single permitted leading `0x00` (the strict-DER positive-sign
/// pad) from `bytes`, leaving the bare magnitude.
fn strip_leading_sign_zero(bytes: &[u8]) -> &[u8] {
    if bytes.len() > 1 && bytes[0] == 0x00 {
        &bytes[1..]
    } else {
        bytes
    }
}

/// Reads one `Time` (`UTCTime` or `GeneralizedTime`) from `reader`.
fn read_time(reader: &mut Reader) -> Result<Time, Error> {
    let (t, value) = reader.read_any()?;
    if t != tag::UTC_TIME && t != tag::GENERALIZED_TIME {
        return Err(Error::Malformed);
    }
    let s = core::str::from_utf8(value).map_err(|_| Error::Malformed)?;
    Ok(Time::from_repr(s))
}

#[cfg(test)]
mod tests {
    use super::super::algorithm_identifier;
    use super::*;
    use crate::rsa::BoxedRsaPrivateKey;
    use crate::x509::{CertSigner, Validity};

    fn rsa_a() -> BoxedRsaPrivateKey {
        BoxedRsaPrivateKey::from_pkcs1_pem(include_str!("../../testdata/rsa2048_test_a.pem"))
            .expect("rsa key A")
    }
    fn rsa_b() -> BoxedRsaPrivateKey {
        BoxedRsaPrivateKey::from_pkcs1_pem(include_str!("../../testdata/rsa2048_test_b.pem"))
            .expect("rsa key B")
    }

    fn validity() -> Validity {
        Validity::new(
            Time::utc(2024, 1, 1, 0, 0, 0),
            Time::utc(2034, 1, 1, 0, 0, 0),
        )
    }

    fn issuer_dn() -> DistinguishedName {
        DistinguishedName::common_name("purecrypto CRL test")
    }

    #[test]
    fn roundtrip_two_entries_and_verify() {
        let key = rsa_a();
        let signer = CertSigner::Rsa(&key);
        let dn = issuer_dn();
        let mut b = CrlBuilder::new(
            &dn,
            Time::utc(2026, 1, 1, 0, 0, 0),
            Some(Time::utc(2026, 12, 31, 0, 0, 0)),
        );
        b.revoke(
            &[0x01],
            Time::utc(2026, 2, 1, 0, 0, 0),
            Some(CrlReason::KeyCompromise),
        );
        b.revoke(
            &[0x02, 0x03],
            Time::utc(2026, 2, 2, 0, 0, 0),
            Some(CrlReason::Superseded),
        );
        let crl = b.sign(&signer).unwrap();

        // Round-trip through DER and PEM.
        let from_der = CertificateRevocationList::from_der(crl.to_der().to_vec()).unwrap();
        assert_eq!(from_der, crl);
        let pem = crl.to_pem();
        assert!(pem.contains("BEGIN X509 CRL"));
        let from_pem = CertificateRevocationList::from_pem(&pem).unwrap();
        assert_eq!(from_pem, crl);

        // Issuer / dates / algid consistency.
        assert_eq!(crl.issuer().unwrap(), dn);
        assert_eq!(crl.this_update().unwrap(), Time::utc(2026, 1, 1, 0, 0, 0));
        assert_eq!(
            crl.next_update().unwrap().unwrap(),
            Time::utc(2026, 12, 31, 0, 0, 0)
        );
        crl.check_signature_algid_consistent().unwrap();

        // Entries decode the way we encoded.
        let entries = crl.entries().unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].serial, alloc::vec![0x01]);
        assert_eq!(entries[0].reason, Some(CrlReason::KeyCompromise));
        assert_eq!(entries[1].serial, alloc::vec![0x02, 0x03]);
        assert_eq!(entries[1].reason, Some(CrlReason::Superseded));

        // Signature verifies against the issuer.
        let issuer_pub = signer.public_key();
        crl.verify_signature_with(&issuer_pub).unwrap();

        // is_revoked matches on the magnitude.
        assert!(crl.is_revoked(&[0x01]).unwrap());
        assert!(crl.is_revoked(&[0x02, 0x03]).unwrap());
        // Strict-DER canonical comparison: a sign-protection 0x00 is
        // transparently stripped.
        assert!(crl.is_revoked(&[0x00, 0x01]).unwrap());
        // A different serial: not revoked.
        assert!(!crl.is_revoked(&[0x07]).unwrap());
    }

    #[test]
    fn verify_signature_rejects_wrong_key() {
        let key_a = rsa_a();
        let key_b = rsa_b();
        let signer = CertSigner::Rsa(&key_a);
        let dn = issuer_dn();
        let b = CrlBuilder::new(&dn, Time::utc(2026, 1, 1, 0, 0, 0), None);
        let crl = b.sign(&signer).unwrap();

        // Signed by A; verifies under A, rejects under B.
        crl.verify_signature_with(&CertSigner::Rsa(&key_a).public_key())
            .unwrap();
        assert!(
            crl.verify_signature_with(&CertSigner::Rsa(&key_b).public_key())
                .is_err()
        );
    }

    #[test]
    fn verify_signature_rejects_tampered_byte() {
        let key = rsa_a();
        let signer = CertSigner::Rsa(&key);
        let dn = issuer_dn();
        let mut b = CrlBuilder::new(&dn, Time::utc(2026, 1, 1, 0, 0, 0), None);
        b.revoke(&[0x05], Time::utc(2026, 1, 2, 0, 0, 0), None);
        let crl = b.sign(&signer).unwrap();

        let mut der = crl.to_der().to_vec();
        // Flip a byte inside the TBS.
        let idx = der.len() / 3;
        der[idx] ^= 1;
        let bad = CertificateRevocationList::from_der(der).unwrap();
        assert!(bad.verify_signature_with(&signer.public_key()).is_err());

        // The unmodified CRL still verifies.
        crl.verify_signature_with(&signer.public_key()).unwrap();
        let _ = validity(); // keep the helper used.
    }

    #[test]
    fn rejects_inner_outer_algid_mismatch() {
        // Construct a CRL whose outer signatureAlgorithm differs from the
        // inner one (RFC 5280 §5.1.1.2 forbids this). The signature itself
        // is over the TBS bytes (with the inner algid), so the *signature*
        // would technically verify — but the consistency check refuses the
        // CRL before that.
        let key = rsa_a();
        let signer = CertSigner::Rsa(&key);
        let dn = issuer_dn();

        // Build a TBS with inner = ECDSA-SHA256 (any non-RSA algid will do).
        // We can't actually *sign* with ECDSA-SHA256 using an RSA key, so we
        // sign with the matching RSA algid for the wire encoding and then
        // splice the outer to a different OID.
        let inner_algid = algorithm_identifier(oid::SHA256_WITH_RSA, true);
        let tbs = encode_tbs_cert_list(
            &dn.to_der(),
            &Time::utc(2026, 1, 1, 0, 0, 0),
            None,
            &[],
            &inner_algid,
        );
        let sig = signer.sign(&tbs).unwrap();
        // Outer = sha1WithRSAEncryption (different OID than inner).
        let outer_algid = algorithm_identifier(oid::SHA1_WITH_RSA, true);
        let der = encode_sequence(&[tbs, outer_algid, encode_bit_string(&sig)].concat());
        let mismatched = CertificateRevocationList::from_der(der).unwrap();
        assert!(matches!(
            mismatched.check_signature_algid_consistent(),
            Err(Error::Malformed)
        ));
        // The public verify entry point must also refuse the mismatch
        // (RFC 5280 §5.1.1.2), even though the raw signature is valid over the
        // TBS. Finding 1: the algid-consistency check is now enforced inside
        // verify_signature_with, not just the standalone comparator.
        assert!(matches!(
            mismatched.verify_signature_with(&signer.public_key()),
            Err(Error::Malformed)
        ));
    }

    #[test]
    fn rejects_unknown_version() {
        // Forge a TBSCertList carrying version=99. RFC 5280 §5.1 only
        // defines v1 (absent) and v2 (1); anything else is malformed.
        let key = rsa_a();
        let signer = CertSigner::Rsa(&key);
        let dn = issuer_dn();
        let algid = algorithm_identifier(oid::SHA256_WITH_RSA, true);

        let mut body = Vec::new();
        body.extend_from_slice(&encode_integer(&[99])); // bogus version
        body.extend_from_slice(&algid);
        body.extend_from_slice(&dn.to_der());
        body.extend_from_slice(&Time::utc(2026, 1, 1, 0, 0, 0).to_der_choice());
        let tbs = encode_sequence(&body);
        let sig = signer.sign(&tbs).unwrap();
        let der = encode_sequence(&[tbs, algid, encode_bit_string(&sig)].concat());

        let crl = CertificateRevocationList::from_der(der).unwrap();
        // Any accessor that walks past the version field surfaces the error.
        assert!(matches!(crl.issuer(), Err(Error::Malformed)));
        assert!(matches!(crl.entries(), Err(Error::Malformed)));
    }

    #[test]
    fn rejects_unknown_revocation_reason() {
        // Forge a CRL entry with reason ENUMERATED = 255 — outside the
        // {0..=6, 8..=10} set defined by RFC 5280 §5.3.1.
        let key = rsa_a();
        let signer = CertSigner::Rsa(&key);
        let dn = issuer_dn();
        let algid = algorithm_identifier(oid::SHA256_WITH_RSA, true);

        // Build a revoked-cert entry by hand.
        let serial = encode_integer(&[0x07]);
        let rdate = Time::utc(2026, 1, 2, 0, 0, 0).to_der_choice();
        let enumerated = encode_tlv(0x0a, &[0xff]);
        let mut ext_body = oid_tlv(oid::CRL_REASON_CODE);
        ext_body.extend_from_slice(&encode_octet_string(&enumerated));
        let ext = encode_sequence(&ext_body);
        let exts = encode_sequence(&ext);
        let mut entry = Vec::new();
        entry.extend_from_slice(&serial);
        entry.extend_from_slice(&rdate);
        entry.extend_from_slice(&exts);
        let revoked = encode_sequence(&entry);
        let revoked_seq = encode_sequence(&revoked);

        let mut tbs_body = Vec::new();
        tbs_body.extend_from_slice(&encode_integer(&[1]));
        tbs_body.extend_from_slice(&algid);
        tbs_body.extend_from_slice(&dn.to_der());
        tbs_body.extend_from_slice(&Time::utc(2026, 1, 1, 0, 0, 0).to_der_choice());
        tbs_body.extend_from_slice(&revoked_seq);
        let tbs = encode_sequence(&tbs_body);
        let sig = signer.sign(&tbs).unwrap();
        let der = encode_sequence(&[tbs, algid, encode_bit_string(&sig)].concat());

        let crl = CertificateRevocationList::from_der(der).unwrap();
        assert!(matches!(crl.entries(), Err(Error::Malformed)));
    }

    #[test]
    fn empty_crl_has_no_entries() {
        let key = rsa_a();
        let signer = CertSigner::Rsa(&key);
        let dn = issuer_dn();
        let b = CrlBuilder::new(&dn, Time::utc(2026, 1, 1, 0, 0, 0), None);
        let crl = b.sign(&signer).unwrap();
        assert!(crl.entries().unwrap().is_empty());
        assert!(!crl.is_revoked(&[0x42]).unwrap());
        assert!(crl.next_update().unwrap().is_none());
    }
}