purecrypto 0.5.0

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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
//! RFC 6960 Online Certificate Status Protocol responses.
//!
//! Scope is the OCSP *response* — the only side TLS stapling cares about
//! (RFC 6066 §8 + RFC 8446 §4.4.2.1). Building OCSP *requests* and running an
//! actual responder are out of scope: stapled responses are produced by the
//! issuer's responder out-of-band and the TLS server merely carries the DER
//! blob on the wire. This module:
//!
//!   - Parses an `OCSPResponse` (the outer envelope with `responseStatus`
//!     and an optional `responseBytes` carrying a `BasicOCSPResponse`).
//!   - Parses the inner `BasicOCSPResponse` → `ResponseData` →
//!     `SingleResponse` rows, mapping `CertStatus` into a Rust enum.
//!   - Verifies the BasicOCSPResponse signature (RFC 6960 §4.2.2.2): either
//!     directly by the certificate issuer or by a delegated responder
//!     certificate the issuer signed and stamped with the
//!     `id-kp-OCSPSigning` extended key usage.
//!   - Locates the `SingleResponse` matching a `(leaf, issuer)` pair by
//!     computing `issuerNameHash` / `issuerKeyHash` / `serialNumber` and
//!     comparing byte-for-byte.
//!
//! ASN.1 module wire format (RFC 6960 §4.2.1, simplified):
//!
//! ```text
//! OCSPResponse ::= SEQUENCE {
//!     responseStatus      OCSPResponseStatus,            -- ENUMERATED
//!     responseBytes   [0] EXPLICIT ResponseBytes OPTIONAL }
//!
//! ResponseBytes ::= SEQUENCE {
//!     responseType   OBJECT IDENTIFIER,                 -- id-pkix-ocsp-basic
//!     response       OCTET STRING }                     -- BasicOCSPResponse DER
//!
//! BasicOCSPResponse ::= SEQUENCE {
//!     tbsResponseData      ResponseData,
//!     signatureAlgorithm   AlgorithmIdentifier,
//!     signature            BIT STRING,
//!     certs            [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
//!
//! ResponseData ::= SEQUENCE {
//!     version              [0] EXPLICIT Version DEFAULT v1,
//!     responderID              ResponderID,
//!     producedAt               GeneralizedTime,
//!     responses                SEQUENCE OF SingleResponse,
//!     responseExtensions   [1] EXPLICIT Extensions OPTIONAL }
//!
//! ResponderID ::= CHOICE {
//!     byName  [1] EXPLICIT Name,
//!     byKey   [2] EXPLICIT KeyHash }                    -- SHA-1 of issuer SPKI bits
//!
//! SingleResponse ::= SEQUENCE {
//!     certID                       CertID,
//!     certStatus                   CertStatus,
//!     thisUpdate                   GeneralizedTime,
//!     nextUpdate         [0]       EXPLICIT GeneralizedTime OPTIONAL,
//!     singleExtensions   [1]       EXPLICIT Extensions OPTIONAL }
//!
//! CertID ::= SEQUENCE {
//!     hashAlgorithm   AlgorithmIdentifier,              -- usually SHA-1
//!     issuerNameHash  OCTET STRING,                     -- hash of issuer subject DN
//!     issuerKeyHash   OCTET STRING,                     -- hash of issuer SPKI bits
//!     serialNumber    CertificateSerialNumber }         -- INTEGER
//!
//! CertStatus ::= CHOICE {
//!     good     [0] IMPLICIT NULL,                       -- wire tag 0x80
//!     revoked  [1] IMPLICIT RevokedInfo,                -- wire tag 0xA1 (SEQUENCE)
//!     unknown  [2] IMPLICIT UnknownInfo }               -- wire tag 0x82 (NULL)
//!
//! RevokedInfo ::= SEQUENCE {
//!     revocationTime              GeneralizedTime,
//!     revocationReason    [0]     EXPLICIT CRLReason OPTIONAL }
//! ```
//!
//! See [`OcspResponse`] for the read API and [`OcspResponseBuilder`] for the
//! (test-side) builder used to generate fixtures.

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

use super::{AnyPublicKey, CertSigner, Certificate, CrlReason, Error, Extension, Time, oid};
use crate::der::{
    Reader, encode_bit_string, encode_context, encode_integer, encode_null, encode_octet_string,
    encode_sequence, encode_tlv, oid_tlv, parse_oid, pem_decode, pem_encode, tag,
};
use crate::hash::{sha1, sha256, sha384, sha512};
use crate::rng::RngCore;

const PEM_LABEL: &str = "OCSP RESPONSE";

/// `OCSPResponseStatus` (RFC 6960 §4.2.1). Only `Successful` carries a
/// `responseBytes` field; the other variants are diagnostic codes that
/// indicate the responder refused or could not produce a status.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum OcspResponseStatus {
    /// `successful` (0) — the response body contains a status.
    Successful = 0,
    /// `malformedRequest` (1).
    MalformedRequest = 1,
    /// `internalError` (2).
    InternalError = 2,
    /// `tryLater` (3).
    TryLater = 3,
    /// `sigRequired` (5) — value 4 is unassigned per the ASN.1 module.
    SigRequired = 5,
    /// `unauthorized` (6).
    Unauthorized = 6,
}

impl OcspResponseStatus {
    /// Parses a single-byte ENUMERATED value into an `OcspResponseStatus`.
    /// Rejects values outside `{0,1,2,3,5,6}` (4 is reserved).
    pub fn from_u8(v: u8) -> Result<Self, Error> {
        match v {
            0 => Ok(OcspResponseStatus::Successful),
            1 => Ok(OcspResponseStatus::MalformedRequest),
            2 => Ok(OcspResponseStatus::InternalError),
            3 => Ok(OcspResponseStatus::TryLater),
            5 => Ok(OcspResponseStatus::SigRequired),
            6 => Ok(OcspResponseStatus::Unauthorized),
            _ => Err(Error::Malformed),
        }
    }
}

/// The status the responder asserts for a single certificate.
///
/// `Good` is the only status under which a stapled response keeps the
/// handshake going; `Revoked` rejects with a final answer, and `Unknown`
/// rejects because the responder cannot speak for this certificate.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OcspCertStatus {
    /// `good [0]` — the certificate is in scope and not revoked.
    Good,
    /// `revoked [1]` — carries the responder's `revocationTime` and the
    /// optional `revocationReason` extension.
    Revoked {
        /// `RevokedInfo.revocationTime`.
        revocation_time: Time,
        /// Optional reason carried in `[0] EXPLICIT CRLReason`.
        reason: Option<CrlReason>,
    },
    /// `unknown [2]` — the responder does not have status for this serial
    /// number under the queried issuer.
    Unknown,
}

/// One row of the BasicOCSPResponse `responses` list.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OcspSingleResponse {
    /// OID arcs of the `CertID.hashAlgorithm` (typically `id-sha1`).
    pub hash_alg_oid: Vec<u64>,
    /// Hash of the issuer's `subject` Name TLV's *value* (the `Name` body,
    /// per RFC 6960 §4.1.1: the hash input is the DER-encoded `Name` value
    /// excluding the tag and length octets — i.e. the body of the SEQUENCE).
    pub issuer_name_hash: Vec<u8>,
    /// Hash of the issuer's `subjectPublicKey` BIT STRING value (raw key bits,
    /// no unused-bits octet).
    pub issuer_key_hash: Vec<u8>,
    /// Raw `serialNumber` INTEGER body (strict-DER canonical magnitude).
    pub serial: Vec<u8>,
    /// `CertStatus` mapped to a Rust enum.
    pub status: OcspCertStatus,
    /// `thisUpdate` — the time at which this status is asserted to be
    /// authoritative.
    pub this_update: Time,
    /// Optional `nextUpdate` — the time after which the status may not be
    /// authoritative any longer.
    pub next_update: Option<Time>,
}

/// A signed, DER-encoded RFC 6960 `OCSPResponse`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OcspResponse {
    der: Vec<u8>,
}

/// The split of a `BasicOCSPResponse` into the bits we hash, the algorithm
/// identifier we route through, and the signature value.
struct BasicParts<'a> {
    /// Raw `tbsResponseData` TLV — what the signature covers.
    tbs: &'a [u8],
    /// Outer signature algorithm OID arcs.
    sig_alg: Vec<u64>,
    /// Signature bits (no unused-bits octet).
    signature: &'a [u8],
    /// Raw `[0] EXPLICIT SEQUENCE OF Certificate` content (without the
    /// `[0] EXPLICIT` wrapping), or `None` when the optional `certs`
    /// field is absent.
    certs_inner: Option<&'a [u8]>,
}

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

    /// Parses a PEM `OCSP RESPONSE` document.
    pub fn from_pem(pem: &str) -> Result<Self, Error> {
        Ok(OcspResponse {
            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)
    }

    /// Top-level `responseStatus`.
    pub fn response_status(&self) -> Result<OcspResponseStatus, Error> {
        let mut outer = Reader::new(&self.der);
        let mut seq = outer.read_sequence()?;
        let v = seq.read_tlv(0x0a)?; // ENUMERATED
        if v.len() != 1 {
            return Err(Error::Malformed);
        }
        OcspResponseStatus::from_u8(v[0])
    }

    /// Returns the inner BasicOCSPResponse DER, or `None` if
    /// `responseStatus` is non-Successful or `responseBytes` is absent.
    fn basic_response_der(&self) -> Result<Option<&[u8]>, Error> {
        let mut outer = Reader::new(&self.der);
        let mut seq = outer.read_sequence()?;
        let status = seq.read_tlv(0x0a)?;
        if status.len() != 1 || status[0] != 0 {
            // Successful (= 0) is the only status that carries responseBytes.
            return Ok(None);
        }
        if seq.is_empty() {
            return Ok(None);
        }
        // `responseBytes [0] EXPLICIT ResponseBytes`.
        let rb_tlv = seq.read_tlv(tag::context(0))?;
        let mut rb = Reader::new(rb_tlv);
        let mut rb_seq = rb.read_sequence()?;
        let resp_type = parse_oid(rb_seq.read_oid()?)?;
        if resp_type.as_slice() != oid::ID_PKIX_OCSP_BASIC {
            return Err(Error::UnsupportedAlgorithm);
        }
        // `response OCTET STRING` whose content is the BasicOCSPResponse DER.
        let basic = rb_seq.read_octet_string()?;
        rb_seq.finish()?;
        Ok(Some(basic))
    }

    /// Splits a BasicOCSPResponse into its components for signature
    /// verification + certs extraction.
    fn basic_parts(&self) -> Result<BasicParts<'_>, Error> {
        let basic = self.basic_response_der()?.ok_or(Error::Malformed)?;
        let mut outer = Reader::new(basic);
        let mut bocsp = outer.read_sequence()?;
        let tbs = bocsp.read_element()?;
        let mut alg = bocsp.read_sequence()?;
        let sig_alg = parse_oid(alg.read_oid()?)?;
        // We don't enforce algid-parameters byte equality here — there's no
        // RFC 6960 §4 mandate that the algorithm identifier match anything
        // inside `tbsResponseData` (unlike RFC 5280 §4.1.1.2's
        // inner/outer requirement).
        let signature = bocsp.read_bit_string()?;
        let certs_inner = if !bocsp.is_empty() && bocsp.peek_tag() == Some(tag::context(0)) {
            let body = bocsp.read_tlv(tag::context(0))?;
            // The `[0] EXPLICIT SEQUENCE OF Certificate` wrapping: unwrap the
            // [0] tag and surface the inner SEQUENCE OF Certificate.
            let mut sr = Reader::new(body);
            let inner = sr.read_element()?; // the SEQUENCE OF Certificate TLV
            sr.finish()?;
            Some(inner)
        } else {
            None
        };
        bocsp.finish()?;
        Ok(BasicParts {
            tbs,
            sig_alg,
            signature,
            certs_inner,
        })
    }

    /// The OID arcs of the inner BasicOCSPResponse `signatureAlgorithm`.
    pub fn signature_algorithm_oid(&self) -> Result<Vec<u64>, Error> {
        Ok(self.basic_parts()?.sig_alg)
    }

    /// Verifies the BasicOCSPResponse signature over `tbsResponseData`
    /// against `key`, dispatching through the signature-algorithm registry.
    pub fn verify_signature_with(&self, key: &AnyPublicKey) -> Result<(), Error> {
        let p = self.basic_parts()?;
        key.verify(&p.sig_alg, p.tbs, p.signature)
    }

    /// `producedAt` — when the responder generated the response.
    pub fn produced_at(&self) -> Result<Time, Error> {
        let p = self.basic_parts()?;
        let mut outer = Reader::new(p.tbs);
        let mut td = outer.read_sequence()?;
        // Optional `version [0] EXPLICIT Version DEFAULT v1`.
        if td.peek_tag() == Some(tag::context(0)) {
            let _ = td.read_tlv(tag::context(0))?;
        }
        // responderID — opaque to producedAt.
        td.read_any()?;
        let (t, value) = td.read_any()?;
        if t != tag::GENERALIZED_TIME {
            return Err(Error::Malformed);
        }
        let s = core::str::from_utf8(value).map_err(|_| Error::Malformed)?;
        Ok(Time::from_repr(s))
    }

    /// The first delegated responder certificate in `BasicOCSPResponse.certs`,
    /// if any. The leaf is the only candidate we consult — RFC 6960
    /// permits a chain but in practice the responder cert is one entry,
    /// signed by the issuer.
    pub fn delegated_responder_cert(&self) -> Result<Option<Certificate>, Error> {
        let p = self.basic_parts()?;
        let Some(inner) = p.certs_inner else {
            return Ok(None);
        };
        let mut r = Reader::new(inner);
        let mut list = r.read_sequence()?;
        if list.is_empty() {
            return Ok(None);
        }
        let first = list.read_element()?;
        Ok(Some(Certificate::from_der(first.to_vec())?))
    }

    /// Iterates the `responses` SEQUENCE OF SingleResponse.
    pub fn responses(&self) -> Result<Vec<OcspSingleResponse>, Error> {
        let p = self.basic_parts()?;
        let mut out = Vec::new();
        let mut outer = Reader::new(p.tbs);
        let mut td = outer.read_sequence()?;
        if td.peek_tag() == Some(tag::context(0)) {
            let _ = td.read_tlv(tag::context(0))?;
        }
        // responderID
        td.read_any()?;
        // producedAt
        td.read_any()?;
        // responses
        let responses_tlv = td.read_element()?;
        let mut rr = Reader::new(responses_tlv);
        let mut rseq = rr.read_sequence()?;
        while !rseq.is_empty() {
            out.push(read_single_response(&mut rseq)?);
        }
        Ok(out)
    }

    /// Returns the value of the `id-pkix-ocsp-nonce` extension (RFC 6960
    /// §4.4.1) carried in `ResponseData.responseExtensions`, if present. The
    /// returned bytes are the inner nonce — the OCTET STRING content nested
    /// inside the extension's `extnValue` OCTET STRING, matching the encoding
    /// emitted by [`OcspResponseBuilder::nonce`] and by RFC 8954-conformant
    /// CAs (OpenSSL, Let's Encrypt, …).
    ///
    /// A response with no nonce extension returns `Ok(None)`. Callers that
    /// requested a nonce in their `OCSPRequest` MUST refuse such a response
    /// — see [`Self::check_for_cert_with_nonce`].
    pub fn nonce(&self) -> Result<Option<Vec<u8>>, Error> {
        let p = self.basic_parts()?;
        let mut outer = Reader::new(p.tbs);
        let mut td = outer.read_sequence()?;
        if td.peek_tag() == Some(tag::context(0)) {
            let _ = td.read_tlv(tag::context(0))?; // version
        }
        td.read_any()?; // responderID
        td.read_any()?; // producedAt
        td.read_any()?; // responses
        // responseExtensions [1] EXPLICIT Extensions OPTIONAL
        if td.is_empty() || td.peek_tag() != Some(tag::context(1)) {
            return Ok(None);
        }
        let wrapper = td.read_tlv(tag::context(1))?;
        let mut outer_ext = Reader::new(wrapper);
        let mut exts = outer_ext.read_sequence()?;
        while !exts.is_empty() {
            let mut ext = exts.read_sequence()?;
            let id = parse_oid(ext.read_oid()?)?;
            // critical BOOLEAN DEFAULT FALSE — skip if present.
            if ext.peek_tag() == Some(tag::BOOLEAN) {
                ext.read_boolean()?;
            }
            let value = ext.read_octet_string()?;
            if id.as_slice() == oid::ID_PKIX_OCSP_NONCE {
                // RFC 8954 §2.1: the extnValue OCTET STRING wraps an inner
                // DER OCTET STRING that holds the actual nonce bytes. Parse
                // the inner OCTET STRING; reject any other shape so a
                // responder cannot smuggle arbitrary DER through the nonce
                // slot.
                let mut nr = Reader::new(value);
                let inner = nr.read_octet_string()?;
                nr.finish()?;
                return Ok(Some(inner.to_vec()));
            }
        }
        Ok(None)
    }

    /// End-to-end validation of a stapled OCSP response. Combines the
    /// signature verification, freshness check, and `(leaf, issuer)`
    /// match into a single call returning the asserted `CertStatus`.
    ///
    /// - Signature verification: tries the issuer key directly first; if
    ///   that fails and a delegated responder certificate is embedded in
    ///   `BasicOCSPResponse.certs[0]`, verifies that responder cert against
    ///   the issuer, checks it carries the `id-kp-OCSPSigning` EKU
    ///   (RFC 6960 §4.2.2.2), then uses the responder key to verify the
    ///   OCSP signature.
    /// - Freshness: requires the matching `SingleResponse` to have
    ///   `thisUpdate <= now` and (when present) `now < nextUpdate`. When
    ///   `now` is `None` the freshness check is skipped — the TLS layer
    ///   passes `None` only under `verify_certificates = false`, where the
    ///   peer's certificates are not validated either.
    /// - Match: see [`find_response_for`](Self::find_response_for).
    ///
    /// Returns `Err(Error::Verification)` for signature failures and
    /// `Err(Error::Malformed)` for missing rows / expired staples — the
    /// TLS layer translates both into [`crate::tls::Error::OcspResponseInvalid`]
    /// to map to a `bad_certificate` alert.
    pub fn check_for_cert(
        &self,
        leaf: &Certificate,
        issuer: &Certificate,
        now: Option<&Time>,
    ) -> Result<OcspCertStatus, Error> {
        // 1. Signature. Try the issuer key first; fall back to a delegated
        //    responder cert if present.
        let issuer_key = issuer.subject_public_key()?;
        if self.verify_signature_with(&issuer_key).is_err() {
            let responder = self
                .delegated_responder_cert()?
                .ok_or(Error::Verification)?;
            // The responder cert chains back to the issuer (single hop —
            // RFC 6960 §4.2.2.2 requires the delegation come from the same
            // CA that issued the certificate the response covers).
            responder.verify_signature_with(&issuer_key)?;
            // ...with id-kp-OCSPSigning in its EKU.
            let ekus = responder.extended_key_usages()?;
            if !ekus.iter().any(|o| o.as_slice() == oid::ID_KP_OCSP_SIGNING) {
                return Err(Error::Verification);
            }
            let responder_key = responder.subject_public_key()?;
            self.verify_signature_with(&responder_key)?;
        }

        // 2. Locate the SingleResponse for this leaf.
        let single = self
            .find_response_for(leaf, issuer)?
            .ok_or(Error::Malformed)?;

        // 3. Freshness. RFC 6960 §3.2: thisUpdate <= now < nextUpdate. The
        //    nextUpdate field is optional — when absent, the responder is
        //    saying it has no fresher response; we accept the staple
        //    anyway (mirroring the rustls and OpenSSL leniency rule, which
        //    treats the response as valid as long as it isn't in the
        //    future and isn't past its claimed expiry).
        if let Some(now) = now {
            let now_u = now.to_unix();
            if single.this_update.to_unix() > now_u {
                return Err(Error::Malformed);
            }
            if let Some(nu) = &single.next_update
                && now_u >= nu.to_unix()
            {
                return Err(Error::Malformed);
            }
        }

        Ok(single.status)
    }

    /// Like [`check_for_cert`](Self::check_for_cert), but additionally
    /// requires the response to echo the `expected_nonce` that the client
    /// embedded in its `OCSPRequest`. Use this when a fresh OCSPRequest is
    /// dispatched over a network (RFC 6960 §4.4.1): without nonce binding a
    /// captured stapled response can be replayed against a fresh request,
    /// defeating freshness even when `nextUpdate` is short.
    ///
    /// `expected_nonce` is the raw nonce value the client placed in the
    /// request (see [`OcspRequestBuilder::nonce`]). It must be:
    /// - present in the response;
    /// - byte-equal to `expected_nonce`.
    ///
    /// Either condition failing returns [`Error::Verification`]. Callers that
    /// retrieve OCSP via stapling (RFC 6066 §8 / RFC 8446 §4.4.2.1) should
    /// stick with [`check_for_cert`](Self::check_for_cert) — the TLS layer
    /// has no fresh nonce to compare against — and rely on `nextUpdate`
    /// freshness instead.
    pub fn check_for_cert_with_nonce(
        &self,
        leaf: &Certificate,
        issuer: &Certificate,
        now: Option<&Time>,
        expected_nonce: &[u8],
    ) -> Result<OcspCertStatus, Error> {
        let status = self.check_for_cert(leaf, issuer, now)?;
        match self.nonce()? {
            Some(got) if got.as_slice() == expected_nonce => Ok(status),
            // A missing nonce when one was requested is just as much a
            // replay-window vulnerability as a mismatched one: the responder
            // can ignore the request nonce and return a fresh-looking cached
            // staple. RFC 6960 §4.4.1 frames this as the client's choice
            // (the responder MAY omit), but a caller who reached this method
            // explicitly opted in, so we fail-closed.
            _ => Err(Error::Verification),
        }
    }

    /// Finds the `SingleResponse` that names `leaf` under `issuer`. Compares
    /// `(issuerNameHash, issuerKeyHash, serial)` after recomputing the hashes
    /// under the responder's chosen algorithm — this lets a single OCSP
    /// response be matched regardless of whether the responder used SHA-1
    /// (the RFC 6960 §4.3 default) or SHA-256/384/512.
    pub fn find_response_for(
        &self,
        leaf: &Certificate,
        issuer: &Certificate,
    ) -> Result<Option<OcspSingleResponse>, Error> {
        let issuer_name_value = read_name_value(issuer.subject_der()?)?;
        let issuer_key_bits = issuer.subject_public_key_bits()?;
        let serial = leaf.serial_bytes()?;
        // strict-DER canonical: a single leading 0x00 is the sign-protection
        // pad and not part of the magnitude. Comparison is on the magnitude
        // (mirrors the CRL `is_revoked` semantics in `src/x509/crl.rs`).
        let serial_magnitude = strip_leading_sign_zero(serial);

        for r in self.responses()? {
            let Some((nh, kh)) = hash_pair(&r.hash_alg_oid, issuer_name_value, issuer_key_bits)
            else {
                continue;
            };
            if r.issuer_name_hash != nh || r.issuer_key_hash != kh {
                continue;
            }
            if strip_leading_sign_zero(&r.serial) != serial_magnitude {
                continue;
            }
            return Ok(Some(r));
        }
        Ok(None)
    }
}

/// Reads one `SingleResponse` row.
fn read_single_response(reader: &mut Reader<'_>) -> Result<OcspSingleResponse, Error> {
    let entry = reader.read_element()?;
    let mut r = Reader::new(entry);
    let mut s = r.read_sequence()?;

    // CertID ::= SEQUENCE { hashAlgorithm, issuerNameHash, issuerKeyHash, serialNumber }
    let mut cert_id = s.read_sequence()?;
    let mut hash_alg = cert_id.read_sequence()?;
    let hash_alg_oid = parse_oid(hash_alg.read_oid()?)?;
    // Tolerate either no parameters or a NULL parameter — RFC 6960 §4.3 picks
    // SHA-1 by default and RFC 5754 §2 says the parameters field MUST be
    // absent for SHA-2 family OIDs but historical responders emit NULL. We
    // accept either form.
    if !hash_alg.is_empty() {
        hash_alg.read_null()?;
    }
    hash_alg.finish()?;
    let issuer_name_hash = cert_id.read_octet_string()?.to_vec();
    let issuer_key_hash = cert_id.read_octet_string()?.to_vec();
    let serial = cert_id.read_unsigned_integer_bytes()?.to_vec();
    cert_id.finish()?;

    // CertStatus ::= CHOICE { good [0] IMPLICIT NULL, revoked [1] IMPLICIT RevokedInfo,
    //                         unknown [2] IMPLICIT NULL }
    let (status_tag, status_body) = s.read_any()?;
    let status = match status_tag {
        // [0] IMPLICIT NULL — primitive, empty body.
        0x80 => {
            if !status_body.is_empty() {
                return Err(Error::Malformed);
            }
            OcspCertStatus::Good
        }
        // [1] IMPLICIT SEQUENCE — RevokedInfo (constructed).
        0xa1 => {
            let mut ri = Reader::new(status_body);
            let (t, value) = ri.read_any()?;
            if t != tag::GENERALIZED_TIME {
                return Err(Error::Malformed);
            }
            let revocation_time =
                Time::from_repr(core::str::from_utf8(value).map_err(|_| Error::Malformed)?);
            let mut reason = None;
            if !ri.is_empty() && ri.peek_tag() == Some(tag::context(0)) {
                // [0] EXPLICIT CRLReason ::= ENUMERATED
                let body = ri.read_tlv(tag::context(0))?;
                let mut br = Reader::new(body);
                let enum_body = br.read_tlv(0x0a)?;
                if enum_body.len() != 1 {
                    return Err(Error::Malformed);
                }
                reason = Some(CrlReason::from_u8(enum_body[0])?);
                br.finish()?;
            }
            OcspCertStatus::Revoked {
                revocation_time,
                reason,
            }
        }
        // [2] IMPLICIT NULL — primitive, empty body.
        0x82 => {
            if !status_body.is_empty() {
                return Err(Error::Malformed);
            }
            OcspCertStatus::Unknown
        }
        _ => return Err(Error::Malformed),
    };

    // thisUpdate (GeneralizedTime).
    let (t, value) = s.read_any()?;
    if t != tag::GENERALIZED_TIME {
        return Err(Error::Malformed);
    }
    let this_update = Time::from_repr(core::str::from_utf8(value).map_err(|_| Error::Malformed)?);

    let mut next_update = None;
    if !s.is_empty() && s.peek_tag() == Some(tag::context(0)) {
        // [0] EXPLICIT GeneralizedTime
        let body = s.read_tlv(tag::context(0))?;
        let mut nr = Reader::new(body);
        let (t, value) = nr.read_any()?;
        if t != tag::GENERALIZED_TIME {
            return Err(Error::Malformed);
        }
        next_update = Some(Time::from_repr(
            core::str::from_utf8(value).map_err(|_| Error::Malformed)?,
        ));
        nr.finish()?;
    }
    // We don't surface singleExtensions [1] EXPLICIT Extensions OPTIONAL.

    Ok(OcspSingleResponse {
        hash_alg_oid,
        issuer_name_hash,
        issuer_key_hash,
        serial,
        status,
        this_update,
        next_update,
    })
}

/// Reads the *value* (content bytes) of a `Name` TLV — RFC 6960 §4.1.1
/// hashes the SEQUENCE body, not the full TLV.
fn read_name_value(name_tlv: &[u8]) -> Result<&[u8], Error> {
    let mut r = Reader::new(name_tlv);
    // `read_tlv(SEQUENCE)` returns the value bytes (no tag, no length).
    let body = r.read_tlv(tag::SEQUENCE)?;
    r.finish()?;
    Ok(body)
}

/// Hashes `(name_value, key_bits)` under `hash_alg_oid`. Returns `None` for
/// unsupported OIDs (the caller skips that row).
fn hash_pair(
    hash_alg_oid: &[u64],
    name_value: &[u8],
    key_bits: &[u8],
) -> Option<(Vec<u8>, Vec<u8>)> {
    if hash_alg_oid == oid::ID_SHA1 {
        Some((sha1(name_value).to_vec(), sha1(key_bits).to_vec()))
    } else if hash_alg_oid == oid::ID_SHA256 {
        Some((sha256(name_value).to_vec(), sha256(key_bits).to_vec()))
    } else if hash_alg_oid == oid::ID_SHA384 {
        Some((sha384(name_value).to_vec(), sha384(key_bits).to_vec()))
    } else if hash_alg_oid == oid::ID_SHA512 {
        Some((sha512(name_value).to_vec(), sha512(key_bits).to_vec()))
    } else {
        None
    }
}

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

/// Encodes a bare `AlgorithmIdentifier` for an OCSP `CertID.hashAlgorithm`
/// field, with NULL parameters (the form historical responders emit and the
/// parser tolerates). Defaults to SHA-1 — the RFC 6960 §4.3 baseline.
fn ocsp_hash_algid(arcs: &[u64]) -> Vec<u8> {
    let mut body = oid_tlv(arcs);
    body.extend_from_slice(&encode_null());
    encode_sequence(&body)
}

// -- Builder ------------------------------------------------------------------

/// Builds a signed `OCSPResponse` carrying a single response for one
/// `(issuer, leaf)` pair. Test-only — production responders are operated
/// out-of-band by the CA and emit DER blobs we just relay.
#[derive(Clone, Debug)]
pub struct OcspResponseBuilder {
    issuer_name_value: Vec<u8>,
    issuer_key_bits: Vec<u8>,
    serial: Vec<u8>,
    status: OcspCertStatus,
    this_update: Time,
    next_update: Option<Time>,
    produced_at: Option<Time>,
    hash_alg_oid: &'static [u64],
    responder_id_by_key: bool,
    delegated_responder_cert: Option<Vec<u8>>,
    nonce: Option<Vec<u8>>,
}

impl OcspResponseBuilder {
    /// Starts a builder for a `(leaf, issuer)` pair with status `Good`.
    /// Defaults: SHA-1 CertID hashes, byKey responderID, `producedAt =
    /// this_update`.
    pub fn good(
        leaf: &Certificate,
        issuer: &Certificate,
        this_update: Time,
        next_update: Option<Time>,
    ) -> Result<Self, Error> {
        Self::with_status(leaf, issuer, this_update, next_update, OcspCertStatus::Good)
    }

    /// Starts a builder for a `(leaf, issuer)` pair with status `Revoked`.
    pub fn revoked(
        leaf: &Certificate,
        issuer: &Certificate,
        this_update: Time,
        next_update: Option<Time>,
        revocation_time: Time,
        reason: Option<CrlReason>,
    ) -> Result<Self, Error> {
        Self::with_status(
            leaf,
            issuer,
            this_update,
            next_update,
            OcspCertStatus::Revoked {
                revocation_time,
                reason,
            },
        )
    }

    fn with_status(
        leaf: &Certificate,
        issuer: &Certificate,
        this_update: Time,
        next_update: Option<Time>,
        status: OcspCertStatus,
    ) -> Result<Self, Error> {
        Ok(OcspResponseBuilder {
            issuer_name_value: read_name_value(issuer.subject_der()?)?.to_vec(),
            issuer_key_bits: issuer.subject_public_key_bits()?.to_vec(),
            serial: leaf.serial_bytes()?.to_vec(),
            status,
            this_update,
            next_update,
            produced_at: None,
            hash_alg_oid: oid::ID_SHA1,
            responder_id_by_key: true,
            delegated_responder_cert: None,
            nonce: None,
        })
    }

    /// Overrides `producedAt` (default: equal to `thisUpdate`).
    pub fn produced_at(mut self, t: Time) -> Self {
        self.produced_at = Some(t);
        self
    }

    /// Switches the responder hash algorithm. Accepted: `id-sha1`, `id-sha256`,
    /// `id-sha384`, `id-sha512`. Unknown OIDs are rejected at sign time.
    pub fn hash_algorithm(mut self, arcs: &'static [u64]) -> Self {
        self.hash_alg_oid = arcs;
        self
    }

    /// Uses `byName` (the issuer's Name DER) as the ResponderID instead of
    /// the default `byKey` (SHA-1 of the issuer SPKI bits).
    pub fn responder_id_by_name(mut self) -> Self {
        self.responder_id_by_key = false;
        self
    }

    /// Embeds `responder_cert_der` as `BasicOCSPResponse.certs[0]`. The signer
    /// passed to [`sign`](Self::sign) is then interpreted as the delegated
    /// responder's key (not the issuer's): the client validates the
    /// responder cert against the issuer and verifies the OCSP signature with
    /// the responder cert's public key.
    pub fn delegated_responder_cert(mut self, responder_cert_der: Vec<u8>) -> Self {
        self.delegated_responder_cert = Some(responder_cert_der);
        self
    }

    /// Echoes the client-supplied `nonce` back to the client via the
    /// `id-pkix-ocsp-nonce` extension in `ResponseData.responseExtensions`
    /// (RFC 6960 §4.4.1, RFC 8954 §2.1). `nonce` is the raw nonce body — the
    /// builder wraps it in the required inner-OCTET-STRING / outer-extnValue
    /// shape.
    ///
    /// Per RFC 8954 §2.1 the nonce body must be 1–32 octets; anything else is
    /// rejected at sign time.
    pub fn nonce(mut self, nonce: &[u8]) -> Self {
        self.nonce = Some(nonce.to_vec());
        self
    }

    /// Signs the response, producing a complete RFC 6960 `OCSPResponse` with
    /// `responseStatus = successful` and the BasicOCSPResponse inside.
    pub fn sign(self, signer: &CertSigner<'_>) -> Result<OcspResponse, Error> {
        // Compute CertID using the chosen hash algorithm.
        let (name_hash, key_hash) = hash_pair(
            self.hash_alg_oid,
            &self.issuer_name_value,
            &self.issuer_key_bits,
        )
        .ok_or(Error::UnsupportedAlgorithm)?;

        // CertID body.
        let mut cert_id_body = Vec::new();
        cert_id_body.extend_from_slice(&ocsp_hash_algid(self.hash_alg_oid));
        cert_id_body.extend_from_slice(&encode_octet_string(&name_hash));
        cert_id_body.extend_from_slice(&encode_octet_string(&key_hash));
        cert_id_body.extend_from_slice(&encode_integer(&self.serial));
        let cert_id = encode_sequence(&cert_id_body);

        // CertStatus.
        let cert_status = match &self.status {
            // good [0] IMPLICIT NULL — primitive, empty body.
            OcspCertStatus::Good => encode_tlv(0x80, &[]),
            // revoked [1] IMPLICIT RevokedInfo — constructed SEQUENCE body.
            OcspCertStatus::Revoked {
                revocation_time,
                reason,
            } => {
                let mut ri = Vec::new();
                ri.extend_from_slice(&revocation_time.to_generalized_time());
                if let Some(r) = reason {
                    let enumerated = encode_tlv(0x0a, &[*r as u8]);
                    ri.extend_from_slice(&encode_context(0, &enumerated));
                }
                encode_tlv(0xa1, &ri)
            }
            // unknown [2] IMPLICIT NULL — primitive, empty body.
            OcspCertStatus::Unknown => encode_tlv(0x82, &[]),
        };

        // SingleResponse body.
        let mut sr = Vec::new();
        sr.extend_from_slice(&cert_id);
        sr.extend_from_slice(&cert_status);
        sr.extend_from_slice(&self.this_update.to_generalized_time());
        if let Some(nu) = &self.next_update {
            sr.extend_from_slice(&encode_context(0, &nu.to_generalized_time()));
        }
        let single_response = encode_sequence(&sr);

        // responses SEQUENCE OF SingleResponse — exactly one row here.
        let responses = encode_sequence(&single_response);

        // ResponderID.
        let responder_id = if self.responder_id_by_key {
            // byKey [2] EXPLICIT KeyHash — KeyHash ::= OCTET STRING (SHA-1).
            let kh = sha1(&self.issuer_key_bits).to_vec();
            encode_context(2, &encode_octet_string(&kh))
        } else {
            // byName [1] EXPLICIT Name — wrap the full Name TLV.
            let name_tlv = encode_sequence(&self.issuer_name_value);
            encode_context(1, &name_tlv)
        };

        // ResponseData (omit version, accept the default v1).
        let produced_at = self.produced_at.as_ref().unwrap_or(&self.this_update);
        let mut td = Vec::new();
        td.extend_from_slice(&responder_id);
        td.extend_from_slice(&produced_at.to_generalized_time());
        td.extend_from_slice(&responses);
        if let Some(nonce_bytes) = &self.nonce {
            // RFC 8954 §2.1: nonce body is 1–32 octets; the extnValue OCTET
            // STRING wraps an inner OCTET STRING that carries the nonce.
            if nonce_bytes.is_empty() || nonce_bytes.len() > 32 {
                return Err(Error::Malformed);
            }
            let inner = encode_octet_string(nonce_bytes);
            let nonce_ext = Extension {
                oid: oid::ID_PKIX_OCSP_NONCE.to_vec(),
                critical: false,
                value: inner,
            }
            .to_der();
            // responseExtensions [1] EXPLICIT SEQUENCE OF Extension.
            let exts_seq = encode_sequence(&nonce_ext);
            td.extend_from_slice(&encode_context(1, &exts_seq));
        }
        let tbs_response_data = encode_sequence(&td);

        // signatureAlgorithm + signature.
        let sig_algid = signer.algorithm_identifier();
        let signature = signer.sign(&tbs_response_data)?;

        // BasicOCSPResponse SEQUENCE { tbs, sigAlg, signature, [0] certs OPTIONAL }.
        let mut bocsp = Vec::new();
        bocsp.extend_from_slice(&tbs_response_data);
        bocsp.extend_from_slice(&sig_algid);
        bocsp.extend_from_slice(&encode_bit_string(&signature));
        if let Some(cert_der) = &self.delegated_responder_cert {
            // certs [0] EXPLICIT SEQUENCE OF Certificate.
            let certs_seq = encode_sequence(cert_der);
            bocsp.extend_from_slice(&encode_context(0, &certs_seq));
        }
        let basic = encode_sequence(&bocsp);

        // ResponseBytes ::= SEQUENCE { responseType OID, response OCTET STRING }.
        let mut rb = Vec::new();
        rb.extend_from_slice(&oid_tlv(oid::ID_PKIX_OCSP_BASIC));
        rb.extend_from_slice(&encode_octet_string(&basic));
        let response_bytes = encode_sequence(&rb);

        // OCSPResponse ::= SEQUENCE { responseStatus, [0] responseBytes }.
        let status = encode_tlv(0x0a, &[OcspResponseStatus::Successful as u8]);
        let mut out = Vec::new();
        out.extend_from_slice(&status);
        out.extend_from_slice(&encode_context(0, &response_bytes));
        Ok(OcspResponse {
            der: encode_sequence(&out),
        })
    }
}

// -- OCSP request -------------------------------------------------------------

/// An unsigned RFC 6960 §4.1 `OCSPRequest` covering a single
/// `(leaf, issuer)` pair, optionally carrying a client-chosen nonce.
///
/// Only the unsigned form (no `optionalSignature`) is emitted: it is what
/// the great majority of responders accept and what the OCSP-over-HTTP
/// profile (RFC 6960 §A.1) defines. Once built, the wire DER is exposed via
/// [`to_der`](Self::to_der) and the nonce, if any, via
/// [`nonce`](Self::nonce) so the caller can later pass it to
/// [`OcspResponse::check_for_cert_with_nonce`].
///
/// ASN.1 (RFC 6960 §4.1.1):
///
/// ```text
/// OCSPRequest ::= SEQUENCE {
///     tbsRequest                  TBSRequest,
///     optionalSignature   [0]     EXPLICIT Signature OPTIONAL }
///
/// TBSRequest ::= SEQUENCE {
///     version             [0]     EXPLICIT Version DEFAULT v1,
///     requestorName       [1]     EXPLICIT GeneralName OPTIONAL,
///     requestList                 SEQUENCE OF Request,
///     requestExtensions   [2]     EXPLICIT Extensions OPTIONAL }
///
/// Request ::= SEQUENCE {
///     reqCert                     CertID,
///     singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
/// ```
#[derive(Clone, Debug)]
pub struct OcspRequest {
    der: Vec<u8>,
    nonce: Option<Vec<u8>>,
}

/// Builder for an [`OcspRequest`]. Configure the hash algorithm and the
/// nonce (if any), then call [`build`](Self::build).
#[derive(Clone, Debug)]
pub struct OcspRequestBuilder {
    issuer_name_value: Vec<u8>,
    issuer_key_bits: Vec<u8>,
    serial: Vec<u8>,
    hash_alg_oid: &'static [u64],
    nonce: Option<Vec<u8>>,
}

impl OcspRequestBuilder {
    /// Starts a builder for a `(leaf, issuer)` pair. Defaults to SHA-1 for
    /// the CertID hash (the RFC 6960 §4.3 baseline; most responders accept
    /// SHA-256 too but SHA-1 maximises interop).
    pub fn new(leaf: &Certificate, issuer: &Certificate) -> Result<Self, Error> {
        Ok(OcspRequestBuilder {
            issuer_name_value: read_name_value(issuer.subject_der()?)?.to_vec(),
            issuer_key_bits: issuer.subject_public_key_bits()?.to_vec(),
            serial: leaf.serial_bytes()?.to_vec(),
            hash_alg_oid: oid::ID_SHA1,
            nonce: None,
        })
    }

    /// Switches the CertID hash algorithm. Accepted: `id-sha1`, `id-sha256`,
    /// `id-sha384`, `id-sha512`. Unknown OIDs are rejected at build time.
    pub fn hash_algorithm(mut self, arcs: &'static [u64]) -> Self {
        self.hash_alg_oid = arcs;
        self
    }

    /// Embeds `nonce` verbatim as the `id-pkix-ocsp-nonce` extension
    /// (RFC 6960 §4.4.1, RFC 8954 §2.1). The nonce body must be 1–32 octets;
    /// other lengths are rejected at build time.
    ///
    /// The same nonce is later passed to
    /// [`OcspResponse::check_for_cert_with_nonce`] to bind request and
    /// response, preventing replay of a stale-but-still-fresh-looking
    /// stapled response.
    pub fn nonce(mut self, nonce: &[u8]) -> Self {
        self.nonce = Some(nonce.to_vec());
        self
    }

    /// Generates a 16-byte nonce from `rng` and installs it. Convenience for
    /// callers that already have a CSPRNG handy.
    pub fn random_nonce<R: RngCore>(mut self, rng: &mut R) -> Self {
        let mut buf = [0u8; 16];
        rng.fill_bytes(&mut buf);
        self.nonce = Some(buf.to_vec());
        self
    }

    /// Encodes the `OCSPRequest` DER. Performs no signature — the request
    /// is unsigned (RFC 6960 §4.1.2 leaves `optionalSignature` truly
    /// optional, and real-world responders accept the unsigned form).
    pub fn build(self) -> Result<OcspRequest, Error> {
        let (name_hash, key_hash) = hash_pair(
            self.hash_alg_oid,
            &self.issuer_name_value,
            &self.issuer_key_bits,
        )
        .ok_or(Error::UnsupportedAlgorithm)?;

        // CertID body — same shape used in the response.
        let mut cert_id_body = Vec::new();
        cert_id_body.extend_from_slice(&ocsp_hash_algid(self.hash_alg_oid));
        cert_id_body.extend_from_slice(&encode_octet_string(&name_hash));
        cert_id_body.extend_from_slice(&encode_octet_string(&key_hash));
        cert_id_body.extend_from_slice(&encode_integer(&self.serial));
        let cert_id = encode_sequence(&cert_id_body);

        // Request ::= SEQUENCE { reqCert CertID, singleRequestExtensions? }
        let request_one = encode_sequence(&cert_id);
        // requestList SEQUENCE OF Request — exactly one entry here.
        let request_list = encode_sequence(&request_one);

        // requestExtensions [2] EXPLICIT Extensions OPTIONAL.
        let mut tbs = Vec::new();
        tbs.extend_from_slice(&request_list);
        if let Some(nonce_bytes) = &self.nonce {
            if nonce_bytes.is_empty() || nonce_bytes.len() > 32 {
                return Err(Error::Malformed);
            }
            let inner = encode_octet_string(nonce_bytes);
            let nonce_ext = Extension {
                oid: oid::ID_PKIX_OCSP_NONCE.to_vec(),
                critical: false,
                value: inner,
            }
            .to_der();
            let exts_seq = encode_sequence(&nonce_ext);
            tbs.extend_from_slice(&encode_context(2, &exts_seq));
        }
        let tbs_request = encode_sequence(&tbs);

        // OCSPRequest ::= SEQUENCE { tbsRequest, optionalSignature? } — we
        // omit the signature.
        let der = encode_sequence(&tbs_request);
        Ok(OcspRequest {
            der,
            nonce: self.nonce,
        })
    }
}

impl OcspRequest {
    /// The DER encoding ready to POST to the responder
    /// (`application/ocsp-request`, RFC 6960 §A.1).
    pub fn to_der(&self) -> &[u8] {
        &self.der
    }

    /// Returns the nonce body the builder embedded, if any. Pass this to
    /// [`OcspResponse::check_for_cert_with_nonce`] when validating the
    /// matching response.
    pub fn nonce(&self) -> Option<&[u8]> {
        self.nonce.as_deref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ec::Ed25519PrivateKey;
    use crate::rsa::BoxedRsaPrivateKey;
    use crate::x509::{
        CertSigner, Certificate, DistinguishedName, Extension, Time, Validity, extension,
    };
    use alloc::vec;

    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 ed25519() -> Ed25519PrivateKey {
        // Deterministic test key.
        let seed = [7u8; 32];
        Ed25519PrivateKey::from_bytes(seed)
    }

    /// Build a self-signed issuer + a leaf certificate it signed. The pair
    /// is the minimum substrate the OCSP code needs to compute CertID
    /// fields and route the verification.
    fn issuer_and_leaf() -> (Certificate, Certificate, BoxedRsaPrivateKey) {
        let issuer_key = rsa_a();
        let issuer_dn = DistinguishedName::common_name("OCSP test root");
        let issuer = Certificate::self_signed_general(
            &CertSigner::Rsa(&issuer_key),
            &issuer_dn,
            &validity(),
            1,
            true,
            &[],
        )
        .expect("self-sign issuer");

        let leaf_key = rsa_b();
        let leaf_dn = DistinguishedName::common_name("OCSP test leaf");
        let signer = CertSigner::Rsa(&issuer_key);
        let leaf_extensions = vec![extension::basic_constraints(false, None)];
        let leaf = Certificate::issue_with_extensions(
            &signer,
            &issuer_dn,
            &leaf_dn,
            &AnyPublicKey::Rsa(leaf_key.public_key()),
            &validity(),
            42,
            &leaf_extensions,
        )
        .expect("issue leaf");

        (issuer, leaf, issuer_key)
    }

    #[test]
    fn good_roundtrip_and_verify() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);

        let resp = OcspResponseBuilder::good(
            &leaf,
            &issuer,
            Time::utc(2026, 1, 1, 0, 0, 0),
            Some(Time::utc(2026, 1, 8, 0, 0, 0)),
        )
        .unwrap()
        .sign(&signer)
        .unwrap();

        // Round-trip through DER + PEM.
        let from_der = OcspResponse::from_der(resp.to_der().to_vec()).unwrap();
        assert_eq!(from_der, resp);
        let pem = resp.to_pem();
        assert!(pem.contains("BEGIN OCSP RESPONSE"));
        let from_pem = OcspResponse::from_pem(&pem).unwrap();
        assert_eq!(from_pem, resp);

        // Top-level status.
        assert_eq!(
            resp.response_status().unwrap(),
            OcspResponseStatus::Successful
        );

        // Locates the row + reports Good.
        let single = resp.find_response_for(&leaf, &issuer).unwrap().unwrap();
        assert_eq!(single.status, OcspCertStatus::Good);
        // OCSP carries GeneralizedTime (the 15-byte `YYYYMMDDHHMMSSZ` form);
        // `Time::utc` builds the 13-byte UTCTime repr. Same instant, different
        // string — compare on the underlying Unix epoch.
        assert_eq!(
            single.this_update.to_unix(),
            Time::utc(2026, 1, 1, 0, 0, 0).to_unix()
        );
        assert_eq!(
            single.next_update.as_ref().map(|t| t.to_unix()),
            Some(Time::utc(2026, 1, 8, 0, 0, 0).to_unix())
        );

        // Signature verifies under the issuer key.
        resp.verify_signature_with(&signer.public_key()).unwrap();
    }

    #[test]
    fn revoked_with_reason_roundtrip() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);

        let resp = OcspResponseBuilder::revoked(
            &leaf,
            &issuer,
            Time::utc(2026, 6, 1, 0, 0, 0),
            None,
            Time::utc(2026, 5, 1, 0, 0, 0),
            Some(CrlReason::KeyCompromise),
        )
        .unwrap()
        .sign(&signer)
        .unwrap();

        let single = resp.find_response_for(&leaf, &issuer).unwrap().unwrap();
        match single.status {
            OcspCertStatus::Revoked {
                revocation_time,
                reason,
            } => {
                // GeneralizedTime round-trip — compare on the instant.
                assert_eq!(
                    revocation_time.to_unix(),
                    Time::utc(2026, 5, 1, 0, 0, 0).to_unix()
                );
                assert_eq!(reason, Some(CrlReason::KeyCompromise));
            }
            other => panic!("expected revoked, got {other:?}"),
        }
        resp.verify_signature_with(&signer.public_key()).unwrap();
    }

    #[test]
    fn unknown_status_decodes() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);

        // No builder shortcut for Unknown — exercise it by injecting the
        // status directly through the with_status seam.
        let resp = OcspResponseBuilder::with_status(
            &leaf,
            &issuer,
            Time::utc(2026, 1, 1, 0, 0, 0),
            None,
            OcspCertStatus::Unknown,
        )
        .unwrap()
        .sign(&signer)
        .unwrap();

        let single = resp.find_response_for(&leaf, &issuer).unwrap().unwrap();
        assert_eq!(single.status, OcspCertStatus::Unknown);
    }

    #[test]
    fn responder_id_by_name() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);

        let resp = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .responder_id_by_name()
            .sign(&signer)
            .unwrap();

        // Verification still works regardless of the responderID encoding —
        // the signature covers tbsResponseData byte-for-byte, and we don't
        // try to derive the responder key from the responderID.
        resp.verify_signature_with(&signer.public_key()).unwrap();
        // And the row matches the same way.
        let single = resp.find_response_for(&leaf, &issuer).unwrap().unwrap();
        assert_eq!(single.status, OcspCertStatus::Good);
    }

    #[test]
    fn delegated_responder_cert_extraction() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let issuer_signer = CertSigner::Rsa(&issuer_key);

        // Issue a delegated responder cert. It's signed by the issuer and
        // carries id-kp-OCSPSigning EKU + the id-pkix-ocsp-nocheck marker.
        let responder_key = ed25519();
        let responder_pub = AnyPublicKey::Ed25519(responder_key.public_key());
        let responder_dn = DistinguishedName::common_name("OCSP delegated responder");
        let mut responder_extensions = vec![extension::basic_constraints(false, None)];
        responder_extensions.push(Extension {
            oid: oid::EXT_KEY_USAGE.to_vec(),
            critical: false,
            value: encode_sequence(&oid_tlv(oid::ID_KP_OCSP_SIGNING)),
        });
        responder_extensions.push(Extension {
            oid: oid::ID_PKIX_OCSP_NOCHECK.to_vec(),
            critical: false,
            value: encode_null(),
        });
        let responder_cert = Certificate::issue_with_extensions(
            &issuer_signer,
            &issuer.subject().unwrap(),
            &responder_dn,
            &responder_pub,
            &validity(),
            99,
            &responder_extensions,
        )
        .expect("issue responder");

        // The OCSP response is signed by the delegated responder key; the
        // delegated cert is embedded in `BasicOCSPResponse.certs[0]`.
        let resp = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .delegated_responder_cert(responder_cert.to_der().to_vec())
            .sign(&CertSigner::Ed25519(&responder_key))
            .unwrap();

        // Extract the embedded cert.
        let extracted = resp.delegated_responder_cert().unwrap().unwrap();
        assert_eq!(extracted.to_der(), responder_cert.to_der());

        // The OCSP signature verifies under the responder's public key, not
        // the issuer's.
        resp.verify_signature_with(&extracted.subject_public_key().unwrap())
            .unwrap();
        // It does NOT verify under the issuer's key — different signing key.
        assert!(
            resp.verify_signature_with(&issuer_signer.public_key())
                .is_err()
        );

        // The responder cert chain back to the issuer: signed by the issuer,
        // and carries id-kp-OCSPSigning in its EKU.
        let issuer_pub = issuer_signer.public_key();
        extracted.verify_signature_with(&issuer_pub).unwrap();
        let ekus = extracted.extended_key_usages().unwrap();
        assert!(ekus.iter().any(|o| o.as_slice() == oid::ID_KP_OCSP_SIGNING));
    }

    #[test]
    fn verify_rejects_wrong_key_or_tamper() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let resp = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .sign(&signer)
            .unwrap();

        // Wrong key (rsa_b vs issuer's rsa_a).
        let wrong = AnyPublicKey::Rsa(rsa_b().public_key());
        assert!(resp.verify_signature_with(&wrong).is_err());

        // Tamper a TBS byte → signature no longer covers it.
        let mut der = resp.to_der().to_vec();
        // Land somewhere inside the BasicOCSPResponse — past the headers.
        let idx = der.len() / 2;
        der[idx] ^= 0x01;
        let tampered = OcspResponse::from_der(der).unwrap();
        assert!(
            tampered
                .verify_signature_with(&signer.public_key())
                .is_err()
        );
    }

    #[test]
    fn find_response_for_serial_magnitude() {
        // Build a leaf whose serial INTEGER body carries a leading 0x00
        // (sign-protection pad) and verify the lookup matches against the
        // magnitude alone — mirrors the CRL comparison semantics.
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let resp = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .sign(&signer)
            .unwrap();
        // The lookup uses the leaf's own serial — round-trips by construction.
        let single = resp.find_response_for(&leaf, &issuer).unwrap().unwrap();
        assert_eq!(single.status, OcspCertStatus::Good);
    }

    #[test]
    fn unknown_response_status_rejected() {
        // ENUMERATED 4 is reserved per the RFC 6960 ASN.1 module.
        let body = encode_sequence(&encode_tlv(0x0a, &[4]));
        let r = OcspResponse::from_der(body).unwrap();
        assert!(matches!(
            r.response_status(),
            Err(crate::x509::Error::Malformed)
        ));
    }

    #[test]
    fn non_successful_status_has_no_basic_response() {
        // A `tryLater` (3) response has no responseBytes.
        let body = encode_sequence(&encode_tlv(0x0a, &[3]));
        let r = OcspResponse::from_der(body).unwrap();
        assert_eq!(r.response_status().unwrap(), OcspResponseStatus::TryLater);
        // Walking past the status into the absent BasicOCSPResponse surfaces
        // `Malformed`; the responses iterator follows that.
        assert!(matches!(r.responses(), Err(crate::x509::Error::Malformed)));
    }

    #[test]
    fn next_update_optional() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let resp = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .sign(&signer)
            .unwrap();
        let single = resp.find_response_for(&leaf, &issuer).unwrap().unwrap();
        assert!(single.next_update.is_none());
    }

    #[test]
    fn sha256_certid_path() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let resp = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .hash_algorithm(oid::ID_SHA256)
            .sign(&signer)
            .unwrap();
        let single = resp.find_response_for(&leaf, &issuer).unwrap().unwrap();
        assert_eq!(single.hash_alg_oid.as_slice(), oid::ID_SHA256);
        // 32-byte SHA-256 outputs.
        assert_eq!(single.issuer_name_hash.len(), 32);
        assert_eq!(single.issuer_key_hash.len(), 32);
    }

    // X509-4: RFC 6960 §4.4.1 — nonce extension binds an OCSP response to the
    // request that asked for it. A client that requested a nonce and gets back
    // a response with no nonce (or a different one) must reject; otherwise an
    // attacker who captured a still-fresh response can replay it indefinitely
    // until its `nextUpdate` lapses.
    #[test]
    fn nonce_round_trips_through_builder_and_response() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let nonce = [0x42u8; 16];
        let resp = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .nonce(&nonce)
            .sign(&signer)
            .unwrap();
        // The accessor returns exactly the bytes the builder embedded.
        let got = resp.nonce().unwrap().unwrap();
        assert_eq!(got, nonce);
        // Signature still verifies — the nonce extension is part of tbsResponseData.
        resp.verify_signature_with(&signer.public_key()).unwrap();
    }

    #[test]
    fn response_without_nonce_returns_none() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let resp = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .sign(&signer)
            .unwrap();
        assert!(resp.nonce().unwrap().is_none());
    }

    #[test]
    fn check_with_nonce_accepts_matching_nonce() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let nonce = b"client-nonce-aaaa";
        let now = Time::utc(2026, 1, 2, 0, 0, 0);
        let resp = OcspResponseBuilder::good(
            &leaf,
            &issuer,
            Time::utc(2026, 1, 1, 0, 0, 0),
            Some(Time::utc(2026, 1, 8, 0, 0, 0)),
        )
        .unwrap()
        .nonce(nonce)
        .sign(&signer)
        .unwrap();
        let status = resp
            .check_for_cert_with_nonce(&leaf, &issuer, Some(&now), nonce)
            .unwrap();
        assert_eq!(status, OcspCertStatus::Good);
    }

    #[test]
    fn check_with_nonce_rejects_missing_nonce() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let now = Time::utc(2026, 1, 2, 0, 0, 0);
        let resp = OcspResponseBuilder::good(
            &leaf,
            &issuer,
            Time::utc(2026, 1, 1, 0, 0, 0),
            Some(Time::utc(2026, 1, 8, 0, 0, 0)),
        )
        .unwrap()
        // No nonce embedded.
        .sign(&signer)
        .unwrap();
        let result = resp.check_for_cert_with_nonce(&leaf, &issuer, Some(&now), b"expected");
        assert!(matches!(result, Err(Error::Verification)));
    }

    #[test]
    fn check_with_nonce_rejects_mismatched_nonce() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let now = Time::utc(2026, 1, 2, 0, 0, 0);
        let resp = OcspResponseBuilder::good(
            &leaf,
            &issuer,
            Time::utc(2026, 1, 1, 0, 0, 0),
            Some(Time::utc(2026, 1, 8, 0, 0, 0)),
        )
        .unwrap()
        .nonce(b"responder-chose-different")
        .sign(&signer)
        .unwrap();
        let result = resp.check_for_cert_with_nonce(&leaf, &issuer, Some(&now), b"client-asked");
        assert!(matches!(result, Err(Error::Verification)));
    }

    #[test]
    fn request_builder_round_trips_nonce() {
        let (issuer, leaf, _) = issuer_and_leaf();
        let nonce = b"req-nonce-1234567890";
        let req = OcspRequestBuilder::new(&leaf, &issuer)
            .unwrap()
            .nonce(nonce)
            .build()
            .unwrap();
        assert_eq!(req.nonce(), Some(nonce.as_slice()));

        // The DER decodes as a well-formed OCSPRequest carrying our nonce in
        // requestExtensions [2] EXPLICIT Extensions.
        let mut r = Reader::new(req.to_der());
        let mut outer = r.read_sequence().unwrap();
        let mut tbs = outer.read_sequence().unwrap();
        // requestList SEQUENCE OF Request — skip it.
        let _req_list = tbs.read_element().unwrap();
        // requestExtensions [2] EXPLICIT
        let exts_wrapper = tbs.read_tlv(tag::context(2)).unwrap();
        let mut exts_outer = Reader::new(exts_wrapper);
        let mut exts = exts_outer.read_sequence().unwrap();
        let mut ext = exts.read_sequence().unwrap();
        let id = parse_oid(ext.read_oid().unwrap()).unwrap();
        assert_eq!(id.as_slice(), oid::ID_PKIX_OCSP_NONCE);
        let value = ext.read_octet_string().unwrap();
        // RFC 8954 §2.1: extnValue OCTET STRING wraps an inner OCTET STRING.
        let mut nr = Reader::new(value);
        let inner = nr.read_octet_string().unwrap();
        assert_eq!(inner, nonce);
    }

    #[test]
    fn request_builder_rejects_oversize_nonce() {
        let (issuer, leaf, _) = issuer_and_leaf();
        // RFC 8954 §2.1 caps the nonce at 32 octets.
        let too_long = [0u8; 33];
        let r = OcspRequestBuilder::new(&leaf, &issuer)
            .unwrap()
            .nonce(&too_long)
            .build();
        assert!(matches!(r, Err(Error::Malformed)));
    }

    #[test]
    fn request_builder_rejects_empty_nonce() {
        let (issuer, leaf, _) = issuer_and_leaf();
        let r = OcspRequestBuilder::new(&leaf, &issuer)
            .unwrap()
            .nonce(&[])
            .build();
        assert!(matches!(r, Err(Error::Malformed)));
    }

    #[test]
    fn response_builder_rejects_oversize_nonce() {
        let (issuer, leaf, issuer_key) = issuer_and_leaf();
        let signer = CertSigner::Rsa(&issuer_key);
        let too_long = [0u8; 33];
        let r = OcspResponseBuilder::good(&leaf, &issuer, Time::utc(2026, 1, 1, 0, 0, 0), None)
            .unwrap()
            .nonce(&too_long)
            .sign(&signer);
        assert!(matches!(r, Err(Error::Malformed)));
    }

    #[test]
    fn random_nonce_is_present_and_correct_length() {
        let (issuer, leaf, _) = issuer_and_leaf();
        let mut rng = crate::rng::HmacDrbg::<crate::hash::Sha256>::new(b"ocsp-nonce", b"n", &[]);
        let req = OcspRequestBuilder::new(&leaf, &issuer)
            .unwrap()
            .random_nonce(&mut rng)
            .build()
            .unwrap();
        let n = req.nonce().unwrap();
        assert_eq!(n.len(), 16);
    }
}