pkix-path 0.6.1

RFC 5280 X.509 certificate path validation — pure Rust, no_std
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
//! Recognizing an X9.62 `SpecifiedECDomain` as a named curve.
//!
//! # Why this exists
//!
//! RFC 5480 §2.1.1 gives an EC key's `parameters` field two usable
//! forms:
//!
//! > ECParameters ::= CHOICE {
//! >   namedCurve         OBJECT IDENTIFIER
//! >   -- implicitCurve   NULL
//! >   -- specifiedCurve  SpecifiedECDomain
//! > }
//!
//! and requires the first:
//!
//! > The namedCurve field MUST be used [...] specifiedCurve MUST NOT be
//! > used.
//!
//! RFC 3279 §2.3.5, which it supersedes, permitted all three. And ICAO
//! Doc 9303 Part 12 §4.1.6.3 *requires* the form RFC 5480 forbids, for
//! every machine-readable travel document CSCA in the world:
//!
//! > Explicit EC domain parameters MUST be used.
//!
//! So the second form is not a curiosity. Of the 176 EC certificates in
//! `third_party/trust-stores/icao-csca/`, 172 carry explicit
//! parameters, and 79 of those name a curve this crate implements in
//! full.
//!
//! Without this module all 79 were unverifiable, because the curve was
//! read with `decode_as::<ObjectIdentifier>()`: a `SpecifiedECDomain`
//! SEQUENCE is not an OID, the decode failed, and a P-256 key became
//! `UnsupportedKey`. The arithmetic was present and unreachable.
//!
//! # What this module does *not* do
//!
//! It recognizes. It does not implement a curve from its parameters.
//! A certificate carrying brainpoolP384r1 explicitly is still
//! unsupported, because this crate has no brainpool arithmetic -- that
//! is a different gap, and 93 of the corpus certificates are in it.
//!
//! # Comparing every parameter, not just the prime
//!
//! Recognition requires `p`, `a`, `b`, the generator and the order to
//! all match. Matching on the prime alone would be unsound: a
//! certificate could carry P-384's prime with different coefficients,
//! which is a *different curve*, and verifying its signatures with
//! P-384's arithmetic would mean reading a key on a curve nobody
//! specified. The cofactor must be 1 or absent, which is what all three
//! of these curves have.

use der::{
    Reader as _,
    asn1::{AnyRef, BitStringRef, ObjectIdentifier, OctetStringRef, UintRef},
};

/// X9.62 `prime-field`. The only field type recognized here; the three
/// curves below are all over a prime field, so a characteristic-two
/// field is simply not one of them.
const OID_PRIME_FIELD: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.1.1");

/// Decode a hex literal to bytes at compile time.
///
/// The curve constants are written as the hex strings published in
/// FIPS 186-4 Appendix D and SEC 2 §2.4, so they can be compared
/// against those documents by eye. Spelling them as byte arrays would
/// make that audit much harder for no gain.
const fn hex<const N: usize>(s: &[u8]) -> [u8; N] {
    assert!(s.len() == N * 2, "hex literal has the wrong length");
    let mut out = [0u8; N];
    let mut i = 0;
    while i < N {
        out[i] = (nibble(s[i * 2]) << 4) | nibble(s[i * 2 + 1]);
        i += 1;
    }
    out
}

const fn nibble(c: u8) -> u8 {
    match c {
        b'0'..=b'9' => c - b'0',
        b'a'..=b'f' => c - b'a' + 10,
        _ => panic!("curve constants must be lowercase hex"),
    }
}

/// secp256r1 / P-256 / prime256v1, SEC 2 §2.4.2.
const P256_P: [u8; 32] = hex(b"ffffffff00000001000000000000000000000000ffffffffffffffffffffffff");
const P256_A: [u8; 32] = hex(b"ffffffff00000001000000000000000000000000fffffffffffffffffffffffc");
const P256_B: [u8; 32] = hex(b"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");
const P256_G: [u8; 65] = hex(
    b"046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2\
        964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51\
        f5",
);
const P256_N: [u8; 32] = hex(b"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551");

/// secp384r1 / P-384, SEC 2 §2.5.1.
const P384_P: [u8; 48] = hex(
    b"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe\
        ffffffff0000000000000000ffffffff",
);
const P384_A: [u8; 48] = hex(
    b"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe\
        ffffffff0000000000000000fffffffc",
);
const P384_B: [u8; 48] = hex(
    b"b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875a\
        c656398d8a2ed19d2a85c8edd3ec2aef",
);
const P384_G: [u8; 97] = hex(
    b"04aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a\
        385502f25dbf55296c3a545e3872760ab73617de4a96262c6f5d9e98bf9292dc\
        29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e\
        5f",
);
const P384_N: [u8; 48] = hex(
    b"ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf\
        581a0db248b0a77aecec196accc52973",
);

/// secp521r1 / P-521, SEC 2 §2.6.1.
const P521_P: [u8; 66] = hex(
    b"01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
        ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
        ffff",
);
const P521_A: [u8; 66] = hex(
    b"01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
        ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
        fffc",
);
const P521_B: [u8; 66] = hex(
    b"0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef1\
        09e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b50\
        3f00",
);
const P521_G: [u8; 133] = hex(
    b"0400c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b\
        4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2\
        e5bd66011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd\
        17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94\
        769fd16650",
);
const P521_N: [u8; 66] = hex(
    b"01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
        fffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e9138\
        6409",
);

/// brainpoolP256r1 (RFC 5639 §3.4).
#[cfg(feature = "bp256")]
const BP256_P: [u8; 32] = hex(b"a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377");
#[cfg(feature = "bp256")]
const BP256_A: [u8; 32] = hex(b"7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9");
#[cfg(feature = "bp256")]
const BP256_B: [u8; 32] = hex(b"26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6");
#[cfg(feature = "bp256")]
const BP256_G: [u8; 65] = hex(
    b"048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace32\
        62547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469\
        97",
);
#[cfg(feature = "bp256")]
const BP256_N: [u8; 32] = hex(b"a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7");

/// brainpoolP384r1 (RFC 5639 §3.6).
#[cfg(feature = "bp384")]
const BP384_P: [u8; 48] = hex(
    b"8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123\
        acd3a729901d1a71874700133107ec53",
);
#[cfg(feature = "bp384")]
const BP384_A: [u8; 48] = hex(
    b"7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f\
        8aa5814a503ad4eb04a8c7dd22ce2826",
);
#[cfg(feature = "bp384")]
const BP384_B: [u8; 48] = hex(
    b"04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d5\
        7cb4390295dbc9943ab78696fa504c11",
);
#[cfg(feature = "bp384")]
const BP384_G: [u8; 97] = hex(
    b"041d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10\
        e8e826e03436d646aaef87b2e247d4af1e8abe1d7520f9c2a45cb1eb8e95cfd5\
        5262b70b29feec5864e19c054ff99129280e4646217791811142820341263c53\
        15",
);
#[cfg(feature = "bp384")]
const BP384_N: [u8; 48] = hex(
    b"8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7\
        cf3ab6af6b7fc3103b883202e9046565",
);

/// brainpoolP224r1 (RFC 5639 §3.3).
#[cfg(feature = "bp224")]
const BP224_P: [u8; 28] = hex(b"d7c134aa264366862a18302575d1d787b09f075797da89f57ec8c0ff");
#[cfg(feature = "bp224")]
const BP224_A: [u8; 28] = hex(b"68a5e62ca9ce6c1c299803a6c1530b514e182ad8b0042a59cad29f43");
#[cfg(feature = "bp224")]
const BP224_B: [u8; 28] = hex(b"2580f63ccfe44138870713b1a92369e33e2135d266dbb372386c400b");
#[cfg(feature = "bp224")]
const BP224_G: [u8; 57] = hex(
    b"040d9029ad2c7e5cf4340823b2a87dc68c9e4ce3174c1e6efdee12c07d58aa56\
        f772c0726f24c6b89e4ecdac24354b9e99caa3f6d3761402cd",
);
#[cfg(feature = "bp224")]
const BP224_N: [u8; 28] = hex(b"d7c134aa264366862a18302575d0fb98d116bc4b6ddebca3a5a7939f");

/// brainpoolP512r1 (RFC 5639 §3.7).
#[cfg(feature = "bp512")]
const BP512_P: [u8; 64] = hex(
    b"aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330871\
        7d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3",
);
#[cfg(feature = "bp512")]
const BP512_A: [u8; 64] = hex(
    b"7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc\
        2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca",
);
#[cfg(feature = "bp512")]
const BP512_B: [u8; 64] = hex(
    b"3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a7\
        2bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723",
);
#[cfg(feature = "bp512")]
const BP512_G: [u8; 129] = hex(
    b"0481aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d009\
        8eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f8\
        227dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f81\
        11b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad808\
        92",
);
#[cfg(feature = "bp512")]
const BP512_N: [u8; 64] = hex(
    b"aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870\
        553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069",
);

/// One curve recognizable from explicit parameters.
struct KnownCurve {
    /// The `namedCurve` OID callers dispatch on.
    oid: ObjectIdentifier,
    p: &'static [u8],
    a: &'static [u8],
    b: &'static [u8],
    /// Uncompressed generator, `0x04 || X || Y`.
    base: &'static [u8],
    order: &'static [u8],
}

/// The curves recognizable here.
///
/// **Feature-gated on purpose.** An entry is present only when this build
/// has the arithmetic for its curve, so recognition can never name a
/// curve the verifier would then fail to compute on. Without the gate a
/// `bp384`-less build would answer "brainpoolP384r1" and the dispatch
/// would report an unsupported key one layer later, turning a clear
/// "I cannot read this curve" into a confusing "I read it and will not
/// use it".
const KNOWN: &[KnownCurve] = &[
    #[cfg(feature = "bp256")]
    KnownCurve {
        oid: ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.7"),
        p: &BP256_P,
        a: &BP256_A,
        b: &BP256_B,
        base: &BP256_G,
        order: &BP256_N,
    },
    #[cfg(feature = "bp224")]
    KnownCurve {
        oid: ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.5"),
        p: &BP224_P,
        a: &BP224_A,
        b: &BP224_B,
        base: &BP224_G,
        order: &BP224_N,
    },
    #[cfg(feature = "bp512")]
    KnownCurve {
        oid: ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.13"),
        p: &BP512_P,
        a: &BP512_A,
        b: &BP512_B,
        base: &BP512_G,
        order: &BP512_N,
    },
    #[cfg(feature = "bp384")]
    KnownCurve {
        oid: ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.11"),
        p: &BP384_P,
        a: &BP384_A,
        b: &BP384_B,
        base: &BP384_G,
        order: &BP384_N,
    },
    KnownCurve {
        oid: ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7"),
        p: &P256_P,
        a: &P256_A,
        b: &P256_B,
        base: &P256_G,
        order: &P256_N,
    },
    KnownCurve {
        oid: ObjectIdentifier::new_unwrap("1.3.132.0.34"),
        p: &P384_P,
        a: &P384_A,
        b: &P384_B,
        base: &P384_G,
        order: &P384_N,
    },
    KnownCurve {
        oid: ObjectIdentifier::new_unwrap("1.3.132.0.35"),
        p: &P521_P,
        a: &P521_A,
        b: &P521_B,
        base: &P521_G,
        order: &P521_N,
    },
];

/// Compare two big-endian magnitudes, ignoring leading zero octets.
///
/// X9.62 §E.2 fixes a `FieldElement` at `ceil(log2(p)/8)` octets, so a
/// conformant producer pads `a` and `b` to the field width and these
/// comparisons are already length-equal. Stripping anyway costs nothing
/// and accepts a producer that trimmed instead, which changes no value.
fn same_magnitude(x: &[u8], y: &[u8]) -> bool {
    let strip = |v: &[u8]| {
        let n = v.iter().take_while(|&&b| b == 0).count();
        v[n..].to_vec()
    };
    strip(x) == strip(y)
}

/// The `namedCurve` OID for an X9.62 `SpecifiedECDomain`, when its
/// parameters are those of a curve this crate implements.
///
/// `params` is an EC key's `AlgorithmIdentifier.parameters` already
/// known not to decode as an OID.
///
/// Returns `None` when the structure does not parse, the field is not a
/// prime field, the cofactor is present and not 1, or the parameters
/// match no known curve -- the last being the ordinary answer for the
/// brainpool and other curves this crate has no arithmetic for.
///
/// # Structure
///
/// ```text
/// SpecifiedECDomain ::= SEQUENCE {
///   version   INTEGER { ecdpVer1(1), ecdpVer2(2), ecdpVer3(3) },
///   fieldID   FieldID,
///   curve     Curve,
///   base      ECPoint,          -- OCTET STRING
///   order     INTEGER,
///   cofactor  INTEGER OPTIONAL,
///   hash      HashAlgorithm OPTIONAL
/// }
/// FieldID ::= SEQUENCE { fieldType OBJECT IDENTIFIER, parameters ANY }
/// Curve   ::= SEQUENCE { a OCTET STRING, b OCTET STRING,
///                        seed BIT STRING OPTIONAL }
/// ```
///
/// `seed` is read and discarded: X9.62 §E.1 makes it the input that
/// generated `b` verifiably, which is provenance for the curve rather
/// than a parameter of it. Two certificates differing only in `seed`
/// describe the same curve.
///
/// # Known false negative: a compressed generator
///
/// The generator is compared as bytes, so it must be in the
/// uncompressed form `0x04 || X || Y`. X9.62 §E.6 also permits the
/// compressed form, and a certificate using it for an otherwise
/// recognizable curve would come back `None`.
///
/// This is deliberate rather than overlooked. Recognizing it would mean
/// decompressing the point, which is field arithmetic this function has
/// no business doing, and the direction of the error is safe: the
/// answer is "I cannot name this curve", never a wrong name. All 172
/// explicit-parameter certificates in the ICAO corpus use the
/// uncompressed form, so nothing currently needs it; if that changes,
/// the fix is to compare `X` alone against the known generator's `X`
/// and the sign bit against its `Y`, not to start doing arithmetic
/// here.
#[must_use]
pub fn named_curve_from_specified(params: AnyRef<'_>) -> Option<ObjectIdentifier> {
    // `params.value()` is the SEQUENCE content, so the fields are read
    // directly rather than through another `sequence()` layer.
    let mut r = der::SliceReader::new(params.value()).ok()?;

    let version: UintRef<'_> = r.decode().ok()?;
    // ecdpVer1. Versions 2 and 3 add a verifiable-generation field that
    // this function would discard anyway, but accepting them would mean
    // claiming to understand a structure not checked here.
    if version.as_bytes() != [1] {
        return None;
    }

    let prime = r
        .sequence(|r| {
            let field_type: ObjectIdentifier = r.decode()?;
            let prime: UintRef<'_> = r.decode()?;
            Ok::<_, der::Error>((field_type, prime))
        })
        .ok()
        .and_then(|(ty, p)| (ty == OID_PRIME_FIELD).then_some(p))?;

    let (a, b) = r
        .sequence(|r| {
            let a: &OctetStringRef = r.decode()?;
            let b: &OctetStringRef = r.decode()?;
            // `seed` is optional; consume it so the nested reader has no
            // trailing data.
            if !r.is_finished() {
                let _seed: BitStringRef<'_> = r.decode()?;
            }
            Ok::<_, der::Error>((a, b))
        })
        .ok()?;

    let base: &OctetStringRef = r.decode().ok()?;
    let order: UintRef<'_> = r.decode().ok()?;

    // Cofactor is optional. All three curves here have h = 1, so a
    // cofactor that says otherwise describes a different group.
    // Any `hash` field after the cofactor is left unread: this function
    // returns from the parameters it has matched, and the reader is
    // dropped without a `finish()` that would reject the remainder.
    if !r.is_finished()
        && let Ok(cofactor) = r.decode::<UintRef<'_>>()
        && cofactor.as_bytes() != [1]
    {
        return None;
    }

    KNOWN
        .iter()
        .find(|c| {
            same_magnitude(prime.as_bytes(), c.p)
                && same_magnitude(a.as_bytes(), c.a)
                && same_magnitude(b.as_bytes(), c.b)
                && base.as_bytes() == c.base
                && same_magnitude(order.as_bytes(), c.order)
        })
        .map(|c| c.oid)
}

#[cfg(test)]
mod tests {
    use super::*;
    // Explicit, not from std's prelude: this crate is `no_std` unless
    // the `std` feature is on, and these tests build under default
    // features where it is not.
    // `crate::Vec` is the unified alias -- `alloc::vec::Vec` in no_std,
    // `std::vec::Vec` under `std`. Not `alloc::vec::Vec` directly:
    // `extern crate alloc` is gated to no_std mode in this crate, so
    // naming `alloc` fails whenever `std` is on. `vec!` needs no import,
    // coming from the crate-wide `#[macro_use] extern crate alloc` in
    // no_std and from std's prelude otherwise.
    use crate::Vec;

    /// Build a minimal `SpecifiedECDomain` from parts, so a test can
    /// alter one parameter and leave the rest conformant.
    fn domain(p: &[u8], a: &[u8], b: &[u8], base: &[u8], order: &[u8], cofactor: &[u8]) -> Vec<u8> {
        fn tlv(tag: u8, body: &[u8]) -> Vec<u8> {
            let mut out = vec![tag];
            if body.len() < 0x80 {
                out.push(u8::try_from(body.len()).expect("checked above"));
            } else if body.len() < 0x100 {
                out.push(0x81);
                out.push(u8::try_from(body.len()).expect("checked above"));
            } else {
                out.push(0x82);
                out.extend_from_slice(
                    &u16::try_from(body.len())
                        .expect("test inputs are small")
                        .to_be_bytes(),
                );
            }
            out.extend_from_slice(body);
            out
        }
        /// An INTEGER needs a 0x00 prefix when the top bit is set, or
        /// it reads as negative.
        fn int(v: &[u8]) -> Vec<u8> {
            let v = &v[v.iter().take_while(|&&x| x == 0).count()..];
            let mut body = Vec::new();
            if v.first().is_some_and(|&b| b & 0x80 != 0) {
                body.push(0);
            }
            body.extend_from_slice(v);
            tlv(0x02, &body)
        }

        let field_id = {
            let mut s = tlv(0x06, &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01]); // prime-field
            s.extend_from_slice(&int(p));
            tlv(0x30, &s)
        };
        let curve = {
            let mut s = tlv(0x04, a);
            s.extend_from_slice(&tlv(0x04, b));
            tlv(0x30, &s)
        };
        let mut body = int(&[1]); // version
        body.extend_from_slice(&field_id);
        body.extend_from_slice(&curve);
        body.extend_from_slice(&tlv(0x04, base));
        body.extend_from_slice(&int(order));
        body.extend_from_slice(&int(cofactor));
        tlv(0x30, &body)
    }

    fn recognize(der: &[u8]) -> Option<ObjectIdentifier> {
        use der::Decode as _;
        named_curve_from_specified(AnyRef::from_der(der).expect("test DER should parse"))
    }

    /// A conformant P-256 domain is recognized, which is the premise
    /// every negative test below depends on.
    #[test]
    fn conformant_p256_is_recognized() {
        let der = domain(&P256_P, &P256_A, &P256_B, &P256_G, &P256_N, &[1]);
        assert_eq!(
            recognize(&der),
            Some(ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7")),
        );
    }

    /// P-384 and P-521 too, so the table is not just its first row.
    #[test]
    fn conformant_p384_and_p521_are_recognized() {
        let p384 = domain(&P384_P, &P384_A, &P384_B, &P384_G, &P384_N, &[1]);
        assert_eq!(
            recognize(&p384),
            Some(ObjectIdentifier::new_unwrap("1.3.132.0.34")),
        );
        let p521 = domain(&P521_P, &P521_A, &P521_B, &P521_G, &P521_N, &[1]);
        assert_eq!(
            recognize(&p521),
            Some(ObjectIdentifier::new_unwrap("1.3.132.0.35")),
        );
    }

    /// **The soundness test.** P-384's prime with a different `b` is a
    /// different curve, and must not be answered "P-384".
    ///
    /// Matching on the prime alone would pass this and hand a caller
    /// P-384's arithmetic for a key on a curve nobody specified. There
    /// is no certificate in any corpus that does this; the point is
    /// that recognition cannot be made to say otherwise.
    #[test]
    fn a_curve_sharing_only_the_prime_is_not_recognized() {
        let mut b = P384_B;
        b[47] ^= 1;
        let der = domain(&P384_P, &P384_A, &b, &P384_G, &P384_N, &[1]);
        assert_eq!(recognize(&der), None, "b differs, so the curve differs");
    }

    /// Same for the coefficient `a`, the generator and the order: each
    /// alone is enough to make it a different group.
    #[test]
    fn altering_any_single_parameter_prevents_recognition() {
        let mut a = P256_A;
        a[31] ^= 1;
        assert_eq!(
            recognize(&domain(&P256_P, &a, &P256_B, &P256_G, &P256_N, &[1])),
            None,
            "a differs",
        );

        let mut g = P256_G;
        g[64] ^= 1;
        assert_eq!(
            recognize(&domain(&P256_P, &P256_A, &P256_B, &g, &P256_N, &[1])),
            None,
            "generator differs",
        );

        let mut n = P256_N;
        n[31] ^= 1;
        assert_eq!(
            recognize(&domain(&P256_P, &P256_A, &P256_B, &P256_G, &n, &[1])),
            None,
            "order differs",
        );

        let mut p = P256_P;
        p[31] ^= 1;
        assert_eq!(
            recognize(&domain(&p, &P256_A, &P256_B, &P256_G, &P256_N, &[1])),
            None,
            "prime differs",
        );
    }

    /// A cofactor other than 1 describes a different group even with
    /// every other parameter matching.
    #[test]
    fn a_cofactor_other_than_one_prevents_recognition() {
        let der = domain(&P256_P, &P256_A, &P256_B, &P256_G, &P256_N, &[2]);
        assert_eq!(recognize(&der), None);
    }

    /// The brainpool curves this build implements ARE recognized.
    ///
    /// 76 certificates of the ICAO corpus are on one of these two, which
    /// is the plurality among its EC roots -- more than the 79 split
    /// across all three NIST curves, and more than either one of them.
    #[cfg(all(feature = "bp256", feature = "bp384"))]
    #[test]
    fn the_implemented_brainpool_curves_are_recognized() {
        let p256 = domain(&BP256_P, &BP256_A, &BP256_B, &BP256_G, &BP256_N, &[1]);
        assert_eq!(
            recognize(&p256),
            Some(ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.7")),
            "brainpoolP256r1, RFC 5639 §3.4",
        );
        let p384 = domain(&BP384_P, &BP384_A, &BP384_B, &BP384_G, &BP384_N, &[1]);
        assert_eq!(
            recognize(&p384),
            Some(ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.11")),
            "brainpoolP384r1, RFC 5639 §3.6",
        );
    }

    /// brainpoolP512r1 is recognized, on arithmetic this crate wrote
    /// itself.
    ///
    /// There is no `bp512` on crates.io. [`crate::brainpool_p512r1`]
    /// implements the curve from `primefield`'s generic Montgomery
    /// macros, which is why this entry may appear in the table: the rule
    /// is that recognition names only curves the build can compute on,
    /// and this build can.
    ///
    /// It matters because brainpoolP512r1 is every certificate in
    /// Germany's CSCA archive. Six of its eight roots verify their own
    /// signatures because of this entry and that module; before them,
    /// none did.
    ///
    /// Parameters are RFC 5639 §3.7, generated from OpenSSL rather than
    /// transcribed.
    #[cfg(feature = "bp512")]
    #[test]
    fn brainpool_p512r1_is_recognized() {
        let der = domain(&BP512_P, &BP512_A, &BP512_B, &BP512_G, &BP512_N, &[1]);
        assert_eq!(
            recognize(&der),
            Some(ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.13")),
        );
    }

    /// brainpoolP224r1 is recognized too, on arithmetic this crate wrote.
    ///
    /// There is no `bp224` on crates.io any more than a `bp512`.
    /// [`crate::brainpool_p224r1`] implements it the same way, and it
    /// fought harder: at 224 bits the field does not fill a machine
    /// word boundary, `crypto_bigint::U224` exists only on 32-bit
    /// targets, and `primefield`'s own byte-reduction impl is bounded on
    /// the uint's width *equalling* the field's, so two `Reduce` impls
    /// had to be written out by hand. The module says where and why.
    ///
    /// Two of Germany's CSCA document signers use it. At 224 bits it is
    /// below any floor a new deployment should pick, which is a reason
    /// not to issue with it -- not a reason to refuse a signer somebody
    /// already issued and shipped in a signed bundle.
    ///
    /// Parameters are RFC 5639 §3.3, generated from OpenSSL.
    #[cfg(feature = "bp224")]
    #[test]
    fn brainpool_p224r1_is_recognized() {
        let der = domain(&BP224_P, &BP224_A, &BP224_B, &BP224_G, &BP224_N, &[1]);
        assert_eq!(
            recognize(&der),
            Some(ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.5")),
        );
    }

    /// **brainpoolP320r1 is NOT recognized, and the invariant holds.**
    ///
    /// Recognition names only curves the build can compute on. RFC 5639
    /// defines seven r1 curves; this build now has four of them (224,
    /// 256, 384, 512) and not P160r1, P192r1 or P320r1. None appears in
    /// any vendored corpus, so they are absent rather than refused, and
    /// this test keeps the table honest about the difference.
    ///
    /// Uses brainpoolP320r1's real RFC 5639 §3.5 parameters.
    #[test]
    fn brainpool_p320r1_is_not_recognized_because_it_is_not_implemented() {
        let p: [u8; 40] = hex(
            b"d35e472036bc4fb7e13c785ed201e065f98fcfa6f6f40def4f92b9ec7893ec28\
            fcd412b1f1b32e27",
        );
        let a: [u8; 40] = hex(
            b"3ee30b568fbab0f883ccebd46d3f3bb8a2a73513f5eb79da66190eb085ffa9f4\
            92f375a97d860eb4",
        );
        let b: [u8; 40] = hex(
            b"520883949dfdbc42d3ad198640688a6fe13f41349554b49acc31dccd88453981\
            6f5eb4ac8fb1f1a6",
        );
        let g: [u8; 81] = hex(
            b"0443bd7e9afb53d8b85289bcc48ee5bfe6f20137d10a087eb6e7871e2a10a599\
            c710af8d0d39e2061114fdd05545ec1cc8ab4093247f77275e0743ffed117182\
            eaa9c77877aaac6ac7d35245d1692e8ee1",
        );
        let n: [u8; 40] = hex(
            b"d35e472036bc4fb7e13c785ed201e065f98fcfa5b68f12a32d482ec7ee8658e9\
            8691555b44c59311",
        );
        let der = domain(&p, &a, &b, &g, &n, &[1]);
        assert_eq!(
            recognize(&der),
            None,
            "brainpoolP320r1 is a real curve this build has no arithmetic \
             for; recognizing it would promise what it cannot do",
        );
    }

    /// Garbage, a truncated structure and an empty input are refused
    /// rather than panicking.
    #[test]
    fn malformed_input_is_refused_without_panicking() {
        use der::Decode as _;
        for bad in [
            vec![0x30, 0x00],
            vec![0x30, 0x03, 0x02, 0x01, 0x01],
            vec![0x30, 0x02, 0xff, 0xff],
        ] {
            let any = AnyRef::from_der(&bad).expect("these are well-formed TLVs");
            assert_eq!(named_curve_from_specified(any), None);
        }
    }

    /// Version 2 and 3 carry a verifiable-generation field this parser
    /// does not check, so they are refused rather than silently read as
    /// version 1.
    #[test]
    fn only_ecdp_version_one_is_accepted() {
        let mut der = domain(&P256_P, &P256_A, &P256_B, &P256_G, &P256_N, &[1]);
        // The version INTEGER is the first element of the SEQUENCE: its
        // value byte sits after the outer header (0x30 0x81 len) and
        // the INTEGER header (0x02 0x01).
        let v = der
            .iter()
            .position(|&b| b == 0x02)
            .expect("the version INTEGER should be present")
            + 2;
        der[v] = 2;
        assert_eq!(recognize(&der), None, "ecdpVer2 is not read as ecdpVer1");
    }
}