crypto-profile 0.10.0

Named cryptographic profiles over the AWS-LC FIPS module: algorithm types, per-module capabilities and a conformance suite
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
//! Strict DER for the private keys the crate imports (decision 0011): RFC 5958 §2
//! OneAsymmetricKey, and the structure each key type carries inside it.

// X.690 §8.1.2: the identifier's first octet and the bytes after the identifier. A tag number
// above 30, and only such a number, takes the high-tag-number form, in minimal base-128 octets.
fn identifier(der: &[u8]) -> Option<(u8, &[u8])> {
    let (&first, rest) = der.split_first()?;
    if first & 0x1f != 0x1f {
        return Some((first, rest));
    }
    let end = rest.iter().position(|octet| octet & 0x80 == 0)?;
    let minimal = match &rest[..=end] {
        [only] => *only > 30,
        [leading, ..] => *leading != 0x80,
        [] => false,
    };
    minimal.then_some((first, &rest[end + 1..]))
}

// One DER element with a minimal definite length of at most two bytes: its identifier's first
// octet, its value and the bytes after it.
pub(crate) fn split_tlv(der: &[u8]) -> Option<(u8, &[u8], &[u8])> {
    let (tag, after) = identifier(der)?;
    let (header, len) = match after {
        [n @ 0..=0x7f, ..] => (1, usize::from(*n)),
        [0x81, n @ 0x80..=0xff, ..] => (2, usize::from(*n)),
        [0x82, hi @ 0x01..=0xff, lo, ..] => (3, usize::from(u16::from_be_bytes([*hi, *lo]))),
        _ => return None,
    };
    let (value, rest) = after[header..].split_at_checked(len)?;
    Some((tag, value, rest))
}

fn optional(tag: u8, der: &[u8]) -> (Option<&[u8]>, &[u8]) {
    match split_tlv(der) {
        Some((t, value, rest)) if t == tag => (Some(value), rest),
        _ => (None, der),
    }
}

// X.690 §11.6: `next` does not precede `prev`, compared as octet strings with the shorter padded
// at its end with 0-octets.
fn not_after(prev: &[u8], next: &[u8]) -> bool {
    fn padded(s: &[u8], len: usize) -> impl Iterator<Item = u8> + '_ {
        s.iter().copied().chain(std::iter::repeat(0)).take(len)
    }
    let len = prev.len().max(next.len());
    padded(prev, len).le(padded(next, len))
}

// The elements of a SET OF in `der`, each passing `element(tag, value)`, in ascending order of their
// encodings (X.690 §11.6).
fn set_of(mut der: &[u8], element: impl Fn(u8, &[u8]) -> bool) -> bool {
    let mut previous: Option<&[u8]> = None;
    for _ in 0..=der.len() {
        if der.is_empty() {
            return true;
        }
        let Some((tag, value, rest)) = split_tlv(der) else {
            return false;
        };
        let whole = &der[..der.len() - rest.len()];
        if !element(tag, value) || !previous.is_none_or(|p| not_after(p, whole)) {
            return false;
        }
        previous = Some(whole);
        der = rest;
    }
    false
}

// X.690 §8.19: base-128 subidentifiers, minimal (none starts with 0x80), the last one terminated.
fn is_oid(contents: &[u8]) -> bool {
    let mut starts = true;
    for &octet in contents {
        if starts && octet == 0x80 {
            return false;
        }
        starts = octet & 0x80 == 0;
    }
    starts && !contents.is_empty()
}

// RFC 5958 §2 Attributes, IMPLICIT: Attribute ::= SEQUENCE { type OBJECT IDENTIFIER, values SET },
// a SET OF Attribute whose attrValues is a SET OF ANY.
fn are_attributes(der: &[u8]) -> bool {
    set_of(der, |tag, attribute| {
        let Some((0x06, oid, values)) = split_tlv(attribute) else {
            return false;
        };
        tag == 0x30
            && is_oid(oid)
            && matches!(split_tlv(values), Some((0x31, set, [])) if set_of(set, |_, _| true))
    })
}

/// RFC 5958 §2, DER: the privateKey contents, and the publicKey bits if it carries one, of one
/// OneAsymmetricKey spanning `der` whose privateKeyAlgorithm is byte for byte `algorithm`. Then
/// come optional `[0]` attributes and, only where `public_key` allows it, a `[1]` publicKey with no
/// unused bits; the version is v2 exactly when `[1]` is present, and nothing follows.
fn one_asymmetric_key<'a>(
    der: &'a [u8],
    algorithm: &[u8],
    public_key: bool,
) -> Option<(&'a [u8], Option<&'a [u8]>)> {
    let Some((0x30, body, [])) = split_tlv(der) else {
        return None;
    };
    let (v2, rest) = match body {
        [0x02, 0x01, 0x00, rest @ ..] => (false, rest),
        [0x02, 0x01, 0x01, rest @ ..] if public_key => (true, rest),
        _ => return None,
    };
    let rest = rest.strip_prefix(algorithm)?;
    let Some((0x04, private_key, rest)) = split_tlv(rest) else {
        return None;
    };
    let (attributes, rest) = optional(0xa0, rest);
    let (carried, rest) = optional(0x81, rest);
    if !rest.is_empty() || !attributes.is_none_or(are_attributes) || carried.is_some() != v2 {
        return None;
    }
    match carried {
        None => Some((private_key, None)),
        Some([0x00, bits @ ..]) => Some((private_key, Some(bits))),
        Some(_) => None,
    }
}

/// The first octet of an uncompressed SEC 1 point (SEC 1 §2.3.3).
pub(crate) const UNCOMPRESSED: u8 = 0x04;

/// A NIST curve's RFC 5480 §2.1.1 AlgorithmIdentifier, id-ecPublicKey with its namedCurve, and its
/// private scalar and uncompressed point lengths (RFC 5915 §3, SEC 1 §2.3.3).
pub(crate) struct EcCurve {
    algorithm: &'static [u8],
    pub(crate) scalar_len: usize,
    point_len: usize,
}

const ALGORITHM_HEADER: usize = 11;

impl EcCurve {
    fn named_curve(&self) -> &'static [u8] {
        &self.algorithm[ALGORITHM_HEADER..]
    }
}

pub(crate) const P256: EcCurve = EcCurve {
    algorithm: &[
        0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86,
        0x48, 0xce, 0x3d, 0x03, 0x01, 0x07,
    ],
    scalar_len: 32,
    point_len: 65,
};

pub(crate) const P384: EcCurve = EcCurve {
    algorithm: &[
        0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81,
        0x04, 0x00, 0x22,
    ],
    scalar_len: 48,
    point_len: 97,
};

pub(crate) const P521: EcCurve = EcCurve {
    algorithm: &[
        0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81,
        0x04, 0x00, 0x23,
    ],
    scalar_len: 66,
    point_len: 133,
};

/// The publicKey point an EC private key carries, if any, once `der` is an RFC 5958 §2
/// PrivateKeyInfo, version v1, whose privateKeyAlgorithm is `c`'s and whose privateKey is one RFC
/// 5915 §3 ECPrivateKey on `c`; or, where `bare` allows it, that ECPrivateKey alone, with its
/// parameters.
pub(crate) fn ec<'a>(c: &EcCurve, der: &'a [u8], bare: bool) -> Option<Option<&'a [u8]>> {
    if let Some((private_key, _)) = one_asymmetric_key(der, c.algorithm, false) {
        let Some((0x30, body, [])) = split_tlv(private_key) else {
            return None;
        };
        return ec_private_key(c, body, false);
    }
    if bare { sec1(c, der) } else { None }
}

/// The publicKey point an EC private key carries, if any, once `der` is one RFC 5915 §3
/// ECPrivateKey on `c` with its parameters, and nothing else.
pub(crate) fn sec1<'a>(c: &EcCurve, der: &'a [u8]) -> Option<Option<&'a [u8]>> {
    match split_tlv(der) {
        Some((0x30, body, [])) => ec_private_key(c, body, true),
        _ => None,
    }
}

// RFC 5915 §3 (EXPLICIT TAGS). §3 requires parameters; inside a PrivateKeyInfo, §1 a) puts the
// curve in privateKeyAlgorithm.
fn ec_private_key<'a>(c: &EcCurve, body: &'a [u8], bare: bool) -> Option<Option<&'a [u8]>> {
    let rest = body.strip_prefix(&[0x02, 0x01, 0x01])?;
    let Some((0x04, scalar, rest)) = split_tlv(rest) else {
        return None;
    };
    let (parameters, rest) = optional(0xa0, rest);
    let (public_key, rest) = optional(0xa1, rest);
    let curve = match parameters {
        Some(named_curve) => named_curve == c.named_curve(),
        None => !bare,
    };
    if scalar.len() != c.scalar_len || !curve || !rest.is_empty() {
        return None;
    }
    match public_key.map(split_tlv) {
        None => Some(None),
        // RFC 5480 §2.2: an uncompressed point, the crate's only public-key form.
        Some(Some((0x03, [0x00, point @ ..], [])))
            if point.len() == c.point_len && point.first() == Some(&UNCOMPRESSED) =>
        {
            Some(Some(point))
        }
        Some(_) => None,
    }
}

// RFC 8410 §3: id-Ed25519, parameters absent.
const ED25519_ALGORITHM: &[u8] = &[0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70];

/// The publicKey an Ed25519 private key carries, if any, once `der` is an RFC 5958 §2
/// OneAsymmetricKey with RFC 8410 §3's id-Ed25519 and no parameters, its privateKey the 32-byte
/// CurvePrivateKey (RFC 8410 §7, RFC 8032 §5.1.5), version v1, or v2 with a 32-byte publicKey.
pub(crate) fn ed25519(der: &[u8]) -> Option<Option<&[u8]>> {
    let (private_key, public_key) = one_asymmetric_key(der, ED25519_ALGORITHM, true)?;
    match (split_tlv(private_key)?, public_key) {
        ((0x04, seed, []), None) if seed.len() == 32 => Some(None),
        ((0x04, seed, []), Some(key)) if seed.len() == 32 && key.len() == 32 => Some(Some(key)),
        _ => None,
    }
}

// RFC 3279 §2.3.1, RFC 8017 A.1: rsaEncryption, parameters NULL.
const RSA_ALGORITHM: &[u8] = &[
    0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00,
];

// RFC 8017 §3.2: a positive INTEGER, DER-minimal (X.690 §8.3.2): its contents and what follows.
fn positive(der: &[u8]) -> Option<(&[u8], &[u8])> {
    match split_tlv(der)? {
        (0x02, value @ ([0x01..=0x7f, ..] | [0x00, 0x80..=0xff, ..]), rest) => Some((value, rest)),
        _ => None,
    }
}

/// Whether `der` is an RFC 5958 §2 PrivateKeyInfo, version v1, with rsaEncryption and NULL
/// parameters, whose privateKey is one [`pkcs1`] RSAPrivateKey of `bits` bits.
pub(crate) fn rsa(der: &[u8], bits: usize) -> bool {
    one_asymmetric_key(der, RSA_ALGORITHM, false)
        .is_some_and(|(private_key, _)| pkcs1(private_key, bits))
}

/// Whether `der` is one RFC 8017 A.1.2 RSAPrivateKey and nothing else: version 0 (two primes),
/// then eight positive, minimal INTEGERs and nothing after them, the modulus of exactly `bits` bits
/// and the public exponent 65537.
pub(crate) fn pkcs1(der: &[u8], bits: usize) -> bool {
    let Some((0x30, body, [])) = split_tlv(der) else {
        return false;
    };
    let Some(rest) = body.strip_prefix(&[0x02, 0x01, 0x00]) else {
        return false;
    };
    let mut rest = rest;
    let mut values = Vec::with_capacity(8);
    for _ in 0..8 {
        let Some((value, next)) = positive(rest) else {
            return false;
        };
        values.push(value);
        rest = next;
    }
    let n = values[0];
    rest.is_empty()
        && n.first() == Some(&0)
        && n.len() == 1 + bits / 8
        && values[1] == [0x01, 0x00, 0x01]
}

// RFC 9881 §2: id-ml-dsa-87, parameters absent.
const ML_DSA_87_ALGORITHM: &[u8] = &[
    0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x13,
];

const ML_DSA_87_EXPANDED_KEY: usize = 4896;
const ML_DSA_87_PUBLIC_KEY: usize = 2592;

/// What a private key carries besides the key, each of which must be the imported key's own: the
/// publicKey, and for ML-DSA-87 the expandedKey of RFC 9881 §6's `both` form.
#[derive(Default, PartialEq, Eq)]
#[cfg_attr(test, derive(Debug))]
pub(crate) struct Carried<'a> {
    pub(crate) public_key: Option<&'a [u8]>,
    pub(crate) expanded_key: Option<&'a [u8]>,
}

/// An ML-DSA-87 private key's seed and what it carries, once `der` is an RFC 5958 §2
/// OneAsymmetricKey with RFC 9881 §2's id-ml-dsa-87 and no parameters, its privateKey one RFC 9881
/// §6 ML-DSA-87-PrivateKey: the 32-byte seed, or both the seed and the 4,896-byte expandedKey. The
/// expandedKey form alone is refused: the module cannot export such a key again. Version v1, or v2
/// with a 2,592-byte publicKey.
pub(crate) fn ml_dsa_87(der: &[u8]) -> Option<(&[u8], Carried<'_>)> {
    let (private_key, public_key) = one_asymmetric_key(der, ML_DSA_87_ALGORITHM, true)?;
    let (seed, expanded_key) = match split_tlv(private_key)? {
        (0x80, seed, []) if seed.len() == 32 => (seed, None),
        (0x30, both, []) => match split_tlv(both)? {
            (0x04, seed, expanded) if seed.len() == 32 => match split_tlv(expanded)? {
                (0x04, key, []) if key.len() == ML_DSA_87_EXPANDED_KEY => (seed, Some(key)),
                _ => return None,
            },
            _ => return None,
        },
        _ => return None,
    };
    match public_key {
        Some(key) if key.len() != ML_DSA_87_PUBLIC_KEY => None,
        _ => Some((
            seed,
            Carried {
                public_key,
                expanded_key,
            },
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn only_one_minimally_encoded_sequence_spanning_the_input_is_whole() {
        let with = |head: &[u8], n: usize| [head, &vec![0; n][..]].concat();
        let is_one_sequence = |der: &[u8]| matches!(split_tlv(der), Some((0x30, _, [])));
        for (whole, header) in [
            (with(&[0x30, 0x03], 3), 2),
            (with(&[0x30, 0x81, 0x80], 0x80), 3),
            (with(&[0x30, 0x82, 0x01, 0x01], 0x101), 4),
        ] {
            let empty: &[u8] = &[];
            assert_eq!(
                split_tlv(&whole),
                Some((0x30, &whole[header..], empty)),
                "{:02x?}",
                &whole[..4]
            );
        }
        for bad in [
            Vec::new(),
            vec![0x30],
            with(&[0x30, 0x03], 2),
            with(&[0x30, 0x03], 4),
            with(&[0x31, 0x03], 3),
            with(&[0x30, 0x80], 2),
            with(&[0x30, 0x81, 0x7f], 0x7f),
            with(&[0x30, 0x81, 0x80], 0x81),
            with(&[0x30, 0x82, 0x00, 0xff], 0xff),
            with(&[0x30, 0x82, 0x01, 0x01], 0x100),
            with(&[0x30, 0x83, 0x00, 0x01, 0x00], 0x100),
        ] {
            assert!(!is_one_sequence(&bad), "{bad:02x?}");
        }
    }

    #[test]
    fn a_tag_number_above_30_alone_takes_the_minimal_high_tag_number_form() {
        let empty: &[u8] = &[];
        for (der, first) in [
            (&[0x1f, 0x1f, 0x01, 0x00][..], 0x1f),
            (&[0x9f, 0x28, 0x01, 0x00], 0x9f),
            (&[0xbf, 0x81, 0x00, 0x01, 0x00], 0xbf),
            (&[0x1f, 0x8f, 0xff, 0xff, 0xff, 0x7f, 0x01, 0x00], 0x1f),
            (&[0x1f, 0x90, 0x80, 0x80, 0x80, 0x00, 0x01, 0x00], 0x1f),
            (
                &[0x1f, 0x81, 0x80, 0x80, 0x80, 0x80, 0x00, 0x01, 0x00],
                0x1f,
            ),
        ] {
            assert_eq!(
                split_tlv(der),
                Some((first, &[0x00][..], empty)),
                "{der:02x?}"
            );
        }
        for bad in [
            &[0x1f, 0x01, 0x00][..],
            &[0x1f, 0x1e, 0x01, 0x00],
            &[0x1f, 0x80, 0x1f, 0x01, 0x00],
            &[0x1f],
            &[0x1f, 0x81],
            &[0x1f, 0x81, 0x80],
        ] {
            assert_eq!(split_tlv(bad), None, "{bad:02x?}");
        }
    }

    #[test]
    fn set_of_elements_are_compared_as_octet_strings_padded_with_zeros() {
        assert!(not_after(&[1, 2], &[1, 3]));
        assert!(not_after(&[1, 2], &[1, 2]));
        assert!(not_after(&[1, 2], &[1, 2, 1]));
        assert!(not_after(&[1, 2], &[1, 2, 0]));
        assert!(not_after(&[1, 2, 0], &[1, 2]));
        assert!(!not_after(&[1, 3], &[1, 2]));
        assert!(!not_after(&[1, 2, 1], &[1, 2]));
        assert!(!not_after(&[1, 3], &[1, 2, 9]));
        assert!(!not_after(&[2], &[1, 9, 9]));
        assert!(not_after(&[1, 9, 9], &[2]));
        assert!(not_after(&[0x31], &[0x31, 0x00]));
        assert!(not_after(&[0x31, 0x00], &[0x31]));
        assert!(!not_after(&[0x31, 0x01], &[0x31]));
        assert!(not_after(&[0x31], &[0x31, 0x01]));
    }

    #[test]
    fn an_object_identifier_is_non_empty_minimal_arcs_the_last_terminated() {
        for good in [
            &[0x2a][..],
            &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d],
            &[0x00],
            &[0x81, 0x00],
            &[0x2a, 0x81, 0x80, 0x01],
        ] {
            assert!(is_oid(good), "{good:02x?}");
        }
        for bad in [
            &[][..],
            &[0x80],
            &[0x80, 0x01],
            &[0x2a, 0x86],
            &[0x2a, 0x80, 0x01],
            &[0x2a, 0x7f, 0x80, 0x01],
            &[0x81],
        ] {
            assert!(!is_oid(bad), "{bad:02x?}");
        }
    }

    fn tlv(tag: u8, value: &[u8]) -> Vec<u8> {
        let n = u16::try_from(value.len()).unwrap();
        let [hi, lo] = n.to_be_bytes();
        let len = match n {
            0..=0x7f => vec![lo],
            0x80..=0xff => vec![0x81, lo],
            _ => vec![0x82, hi, lo],
        };
        [&[tag][..], &len, value].concat()
    }

    fn sequence(fields: &[Vec<u8>]) -> Vec<u8> {
        tlv(0x30, &fields.concat())
    }

    fn attribute(last: u8) -> Vec<u8> {
        sequence(&[
            tlv(
                0x06,
                &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, last],
            ),
            tlv(0x31, &[]),
        ])
    }

    fn attribute_of(oid: &[u8]) -> Vec<u8> {
        tlv(0xa0, &sequence(&[tlv(0x06, oid), tlv(0x31, &[])]))
    }

    const V1: [u8; 3] = [0x02, 0x01, 0x00];
    const V2: [u8; 3] = [0x02, 0x01, 0x01];
    const NULL: [u8; 2] = [0x05, 0x00];

    fn key(version: &[u8], algorithm: &[u8], private_key: &[u8], after: &[Vec<u8>]) -> Vec<u8> {
        let fields = [
            vec![version.to_vec(), algorithm.to_vec(), tlv(0x04, private_key)],
            after.to_vec(),
        ]
        .concat();
        sequence(&fields)
    }

    fn bits(key: &[u8]) -> Vec<u8> {
        tlv(0x81, &[&[0][..], key].concat())
    }

    // Every OneAsymmetricKey framing the validators share, around a well-formed privateKey `inner`
    // and, where the type defines one, a publicKey `public`.
    fn framings(
        algorithm: &[u8],
        inner: &[u8],
        public: Option<&[u8]>,
    ) -> Vec<(&'static str, Vec<u8>)> {
        let attributes = tlv(0xa0, &[attribute(0x14), attribute(0x15)].concat());
        let mut bad = vec![
            (
                "an attribute OID starting with 0x80",
                key(&V1, algorithm, inner, &[attribute_of(&[0x80, 0x01])]),
            ),
            (
                "an attribute OID with an unterminated last arc",
                key(&V1, algorithm, inner, &[attribute_of(&[0x2a, 0x86])]),
            ),
            (
                "an attribute OID with a padded arc",
                key(&V1, algorithm, inner, &[attribute_of(&[0x2a, 0x80, 0x01])]),
            ),
            (
                "trailing byte",
                [key(&V1, algorithm, inner, &[]), vec![0]].concat(),
            ),
            (
                "two keys",
                [
                    key(&V1, algorithm, inner, &[]),
                    key(&V1, algorithm, inner, &[]),
                ]
                .concat(),
            ),
            ("v2 without [1]", key(&V2, algorithm, inner, &[])),
            ("version 2", key(&[0x02, 0x01, 0x02], algorithm, inner, &[])),
            (
                "version 0 in two bytes",
                key(&[0x02, 0x02, 0x00, 0x00], algorithm, inner, &[]),
            ),
            (
                "attributes out of order",
                key(
                    &V1,
                    algorithm,
                    inner,
                    &[tlv(0xa0, &[attribute(0x15), attribute(0x14)].concat())],
                ),
            ),
            (
                "attributes as an explicit SET",
                key(&V1, algorithm, inner, &[tlv(0x31, &attribute(0x14))]),
            ),
            (
                "an undefined field",
                key(&V1, algorithm, inner, &[NULL.to_vec()]),
            ),
            (
                "two [0]",
                key(
                    &V1,
                    algorithm,
                    inner,
                    &[attributes.clone(), attributes.clone()],
                ),
            ),
            (
                "unknown [2]",
                key(&V1, algorithm, inner, &[tlv(0xa2, &NULL)]),
            ),
            (
                "privateKey not an OCTET STRING",
                sequence(&[V1.to_vec(), algorithm.to_vec(), tlv(0x30, inner)]),
            ),
            (
                "another algorithm",
                key(
                    &V1,
                    &sequence(&[tlv(0x06, &[0x2b, 0x65, 0x6e])]),
                    inner,
                    &[],
                ),
            ),
            (
                "the algorithm with NULL appended",
                key(
                    &V1,
                    &tlv(0x30, &[&algorithm[2..], &NULL[..]].concat()),
                    inner,
                    &[],
                ),
            ),
            ("BER outer length", {
                let good = key(&V1, algorithm, inner, &[]);
                let (_, body, _) = split_tlv(&good).unwrap();
                let n = u32::try_from(body.len()).unwrap().to_be_bytes();
                [&[0x30, 0x84][..], &n, body].concat()
            }),
        ];
        match public {
            Some(public) => {
                bad.push(("v1 with [1]", key(&V1, algorithm, inner, &[bits(public)])));
                bad.push((
                    "[1] with unused bits",
                    key(
                        &V2,
                        algorithm,
                        inner,
                        &[tlv(0x81, &[&[1][..], public].concat())],
                    ),
                ));
                bad.push((
                    "[1] constructed",
                    key(
                        &V2,
                        algorithm,
                        inner,
                        &[tlv(0xa1, &tlv(0x03, &[&[0][..], public].concat()))],
                    ),
                ));
                bad.push((
                    "[1] before [0]",
                    key(&V2, algorithm, inner, &[bits(public), attributes.clone()]),
                ));
                bad.push((
                    "[1] one byte short",
                    key(&V2, algorithm, inner, &[bits(&public[1..])]),
                ));
                bad.push((
                    "[1] one byte long",
                    key(&V2, algorithm, inner, &[bits(&[public, &[0]].concat())]),
                ));
                bad.push((
                    "two [1]",
                    key(&V2, algorithm, inner, &[bits(public), bits(public)]),
                ));
            }
            None => bad.push(("v2 with [1]", key(&V2, algorithm, inner, &[bits(&[7; 32])]))),
        }
        bad
    }

    #[test]
    fn every_validator_takes_v1_attributes_and_refuses_what_rfc_5958_does_not_define() {
        let ec_inner = sequence(&[V2.to_vec(), tlv(0x04, &[7; 48])]);
        let rsa_inner = rsa_private_key(2048, &[0x01, 0x00, 0x01]);
        let ed_inner = tlv(0x04, &[9; 32]);
        let ml_inner = tlv(0x80, &[5; 32]);
        let attributes = tlv(0xa0, &[attribute(0x14), attribute(0x15)].concat());
        type Case<'a> = (
            &'a str,
            &'a [u8],
            &'a [u8],
            Option<Vec<u8>>,
            fn(&[u8]) -> bool,
        );
        let cases: [Case<'_>; 4] = [
            ("ec", P384.algorithm, &ec_inner, None, |d| {
                ec(&P384, d, false).is_some()
            }),
            ("rsa", RSA_ALGORITHM, &rsa_inner, None, |d| rsa(d, 2048)),
            (
                "ed25519",
                ED25519_ALGORITHM,
                &ed_inner,
                Some(vec![3; 32]),
                |d| ed25519(d).is_some(),
            ),
            (
                "ml-dsa-87",
                ML_DSA_87_ALGORITHM,
                &ml_inner,
                Some(vec![4; 2592]),
                |d| ml_dsa_87(d).is_some(),
            ),
        ];
        for (name, algorithm, inner, public, check) in cases {
            assert!(check(&key(&V1, algorithm, inner, &[])), "{name}");
            assert!(
                check(&key(
                    &V1,
                    algorithm,
                    inner,
                    std::slice::from_ref(&attributes)
                )),
                "{name}"
            );
            assert!(
                check(&key(&V1, algorithm, inner, &[tlv(0xa0, &[])])),
                "{name}"
            );
            for oid in [&[0x2a][..], &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d]] {
                assert!(
                    check(&key(&V1, algorithm, inner, &[attribute_of(oid)])),
                    "{name}: {oid:02x?}"
                );
            }
            if let Some(public) = &public {
                assert!(
                    check(&key(&V2, algorithm, inner, &[bits(public)])),
                    "{name}"
                );
                assert!(
                    check(&key(
                        &V2,
                        algorithm,
                        inner,
                        &[attributes.clone(), bits(public)]
                    )),
                    "{name}"
                );
            }
            for (why, der) in framings(algorithm, inner, public.as_deref()) {
                assert!(!check(&der), "{name}: {why} {der:02x?}");
            }
        }
    }

    #[test]
    fn an_ed25519_key_is_a_32_byte_curve_private_key_with_its_32_byte_public_key() {
        let public = [3; 32];
        assert_eq!(
            ed25519(&key(&V1, ED25519_ALGORITHM, &tlv(0x04, &[9; 32]), &[])),
            Some(None)
        );
        assert_eq!(
            ed25519(&key(
                &V2,
                ED25519_ALGORITHM,
                &tlv(0x04, &[9; 32]),
                &[bits(&public)]
            )),
            Some(Some(&public[..]))
        );
        for (why, inner) in [
            ("31 bytes", tlv(0x04, &[9; 31])),
            ("33 bytes", tlv(0x04, &[9; 33])),
            ("not wrapped", vec![9; 32]),
            ("wrapped twice", tlv(0x04, &tlv(0x04, &[9; 32]))),
            ("a byte after", [tlv(0x04, &[9; 32]), vec![0]].concat()),
            ("a BIT STRING", tlv(0x03, &[9; 32])),
        ] {
            assert_eq!(
                ed25519(&key(&V1, ED25519_ALGORITHM, &inner, &[])),
                None,
                "{why}"
            );
        }
        let null = sequence(&[tlv(0x06, &[0x2b, 0x65, 0x70]), NULL.to_vec()]);
        assert_eq!(ed25519(&key(&V1, &null, &tlv(0x04, &[9; 32]), &[])), None);
    }

    fn integer(magnitude: &[u8]) -> Vec<u8> {
        if magnitude[0] & 0x80 == 0 {
            tlv(0x02, magnitude)
        } else {
            tlv(0x02, &[&[0][..], magnitude].concat())
        }
    }

    fn rsa_private_key(bits: usize, e: &[u8]) -> Vec<u8> {
        let mut n = vec![0xc5; bits / 8];
        n[bits / 8 - 1] = 0x01;
        let half = vec![0xd3; bits / 16];
        sequence(&[
            V1.to_vec(),
            integer(&n),
            integer(e),
            integer(&n),
            integer(&half),
            integer(&half),
            integer(&half),
            integer(&half),
            integer(&half),
        ])
    }

    #[test]
    fn an_rsa_key_is_version_0_then_eight_positive_minimal_integers() {
        let pki = |inner: &[u8]| key(&V1, RSA_ALGORITHM, inner, &[]);
        for bits in [2048, 3072, 4096] {
            assert!(rsa(&pki(&rsa_private_key(bits, &[0x01, 0x00, 0x01])), bits));
        }
        let good = rsa_private_key(2048, &[0x01, 0x00, 0x01]);
        let (_, body, _) = split_tlv(&good).unwrap();
        let mut fields = Vec::new();
        let mut rest = body;
        while let Some((tag, value, next)) = split_tlv(rest).filter(|_| fields.len() < 16) {
            fields.push(tlv(tag, value));
            rest = next;
        }
        assert_eq!(fields.len(), 9);
        let with = |at: usize, field: Vec<u8>| {
            let mut f = fields.clone();
            f[at] = field;
            sequence(&f)
        };
        let mut wider = vec![0xc5; 257];
        wider[0] = 0x01;
        let zero = tlv(0x02, &[0]);
        for (why, inner) in [
            ("version 1, multi-prime", with(0, vec![0x02, 0x01, 0x01])),
            (
                "version 0 in two bytes",
                with(0, vec![0x02, 0x02, 0x00, 0x00]),
            ),
            ("2,049 bits", with(1, integer(&wider))),
            ("2,040 bits", with(1, integer(&[0xc5; 255]))),
            (
                "2,047 bits",
                with(1, tlv(0x02, &[&[0x7f][..], &[0xc5; 255]].concat())),
            ),
            ("e = 3", with(2, integer(&[3]))),
            ("e = 65539", with(2, integer(&[0x01, 0x00, 0x03]))),
            (
                "e with a leading zero",
                with(2, tlv(0x02, &[0x00, 0x01, 0x00, 0x01])),
            ),
            ("e zero (stripped)", with(2, zero.clone())),
            ("d zero", with(3, zero.clone())),
            ("p zero", with(4, zero.clone())),
            ("q zero", with(5, zero.clone())),
            ("dP zero", with(6, zero.clone())),
            ("dQ zero", with(7, zero.clone())),
            ("qInv zero", with(8, zero.clone())),
            ("qInv negative", with(8, tlv(0x02, &[0x80, 0x01]))),
            ("qInv non-minimal", with(8, tlv(0x02, &[0x00, 0x01]))),
            ("qInv empty", with(8, tlv(0x02, &[]))),
            ("qInv an OCTET STRING", with(8, tlv(0x04, &[0x01]))),
            ("eight integers", sequence(&fields[..8])),
            (
                "ten integers",
                sequence(&[&fields[..], &[integer(&[1])]].concat()),
            ),
            (
                "otherPrimeInfos",
                sequence(
                    &[
                        &fields[..],
                        &[sequence(&[sequence(&[
                            integer(&[3]),
                            integer(&[3]),
                            integer(&[3]),
                        ])])],
                    ]
                    .concat(),
                ),
            ),
            ("a byte after", [good.clone(), vec![0]].concat()),
            ("not a SEQUENCE", tlv(0x31, body)),
        ] {
            assert!(!rsa(&pki(&inner), 2048), "{why}");
        }
        assert!(!rsa(&pki(&good), 3072));
        let absent = sequence(&[RSA_ALGORITHM[2..13].to_vec()]);
        assert!(
            !rsa(&key(&V1, &absent, &good, &[]), 2048),
            "parameters absent"
        );
        let pss = sequence(&[tlv(
            0x06,
            &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a],
        )]);
        assert!(!rsa(&key(&V1, &pss, &good, &[]), 2048), "id-RSASSA-PSS");
    }

    #[test]
    fn pkcs1_takes_one_rsa_private_key_and_nothing_else() {
        let good = rsa_private_key(2048, &[0x01, 0x00, 0x01]);
        assert!(pkcs1(&good, 2048));
        assert!(!pkcs1(&good, 3072));
        assert!(!pkcs1(&key(&V1, RSA_ALGORITHM, &good, &[]), 2048));
        assert!(!pkcs1(&[good.clone(), vec![0]].concat(), 2048));
        assert!(!pkcs1(&[good.clone(), good].concat(), 2048));
    }

    #[test]
    fn sec1_takes_one_ec_private_key_with_its_parameters_and_nothing_else() {
        let scalar = tlv(0x04, &[7; 48]);
        let with = |curve: &EcCurve| {
            sequence(&[V2.to_vec(), scalar.clone(), tlv(0xa0, curve.named_curve())])
        };
        let bare = sequence(&[V2.to_vec(), scalar.clone()]);
        let wrapped = key(&V1, P384.algorithm, &bare, &[]);
        assert_eq!(sec1(&P384, &with(&P384)), Some(None));
        assert_eq!(ec(&P384, &with(&P384), true), Some(None));
        assert_eq!(ec(&P384, &with(&P384), false), None);
        assert_eq!(ec(&P384, &wrapped, true), Some(None));
        for (why, der) in [
            ("a PrivateKeyInfo", wrapped),
            ("no parameters", bare),
            ("parameters naming P-521", with(&P521)),
            ("a byte after", [with(&P384), vec![0]].concat()),
            ("two keys", [with(&P384), with(&P384)].concat()),
        ] {
            assert_eq!(sec1(&P384, &der), None, "{why}");
        }
    }

    #[test]
    fn positive_takes_minimal_positive_integers_only() {
        for value in [
            &[0x01][..],
            &[0x7f],
            &[0x00, 0x80],
            &[0x00, 0xff, 0x00],
            &[0x01, 0x00],
        ] {
            let der = [tlv(0x02, value), vec![0xee]].concat();
            assert_eq!(positive(&der), Some((value, &[0xee][..])), "{value:02x?}");
        }
        for value in [&[][..], &[0x00], &[0x00, 0x7f], &[0x80], &[0xff, 0x01]] {
            assert_eq!(positive(&tlv(0x02, value)), None, "{value:02x?}");
        }
        assert_eq!(positive(&tlv(0x04, &[0x01])), None);
    }

    #[test]
    fn an_ml_dsa_87_key_is_the_seed_or_both_forms_with_nothing_after() {
        let pki = |inner: &[u8], after: &[Vec<u8>]| {
            let version = if after.is_empty() { &V1 } else { &V2 };
            key(version, ML_DSA_87_ALGORITHM, inner, after)
        };
        let seed = tlv(0x80, &[5; 32]);
        let expanded = tlv(0x04, &[6; 4896]);
        let both = sequence(&[tlv(0x04, &[7; 32]), expanded.clone()]);
        let public = vec![4; 2592];
        let carried = |seed: &'static [u8], public_key, expanded_key| {
            Some((
                seed,
                Carried {
                    public_key,
                    expanded_key,
                },
            ))
        };
        let expanded_key = Some(&[6; 4896][..]);
        assert_eq!(ml_dsa_87(&pki(&seed, &[])), carried(&[5; 32], None, None));
        assert_eq!(
            ml_dsa_87(&pki(&both, &[])),
            carried(&[7; 32], None, expanded_key)
        );
        assert_eq!(
            ml_dsa_87(&pki(&seed, &[bits(&public)])),
            carried(&[5; 32], Some(&public[..]), None)
        );
        assert_eq!(
            ml_dsa_87(&pki(&both, &[bits(&public)])),
            carried(&[7; 32], Some(&public[..]), expanded_key)
        );
        for (why, inner) in [
            ("expandedKey alone", expanded.clone()),
            ("seed then 05 00", [seed.clone(), NULL.to_vec()].concat()),
            ("both then 05 00", [both.clone(), NULL.to_vec()].concat()),
            ("seed of 31 bytes", tlv(0x80, &[5; 31])),
            ("seed of 33 bytes", tlv(0x80, &[5; 33])),
            ("seed as an OCTET STRING", tlv(0x04, &[5; 32])),
            ("seed constructed", tlv(0xa0, &tlv(0x04, &[5; 32]))),
            (
                "both, expandedKey one byte short",
                sequence(&[tlv(0x04, &[5; 32]), tlv(0x04, &[6; 4895])]),
            ),
            (
                "both, expandedKey one byte long",
                sequence(&[tlv(0x04, &[5; 32]), tlv(0x04, &[6; 4897])]),
            ),
            (
                "both, seed of 31 bytes",
                sequence(&[tlv(0x04, &[5; 31]), expanded.clone()]),
            ),
            (
                "both, seed tagged [0]",
                sequence(&[tlv(0x80, &[5; 32]), expanded.clone()]),
            ),
            (
                "both, expandedKey first",
                sequence(&[expanded.clone(), tlv(0x04, &[5; 32])]),
            ),
            (
                "both, a field after",
                sequence(&[tlv(0x04, &[5; 32]), expanded.clone(), NULL.to_vec()]),
            ),
            ("both, seed only", sequence(&[tlv(0x04, &[5; 32])])),
            ("empty", vec![]),
        ] {
            assert_eq!(ml_dsa_87(&pki(&inner, &[])), None, "{why}");
            assert_eq!(ml_dsa_87(&pki(&inner, &[bits(&public)])), None, "{why}, v2");
        }
        let with_params = sequence(&[tlv(0x06, &ML_DSA_87_ALGORITHM[4..]), NULL.to_vec()]);
        assert_eq!(ml_dsa_87(&key(&V1, &with_params, &seed, &[])), None);
    }

    #[test]
    fn the_ec_algorithm_identifiers_name_their_curves() {
        for (c, oid) in [
            (
                &P256,
                &[0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07][..],
            ),
            (&P384, &[0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22]),
            (&P521, &[0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23]),
        ] {
            assert_eq!(c.named_curve(), oid);
            assert_eq!(
                c.algorithm,
                sequence(&[
                    tlv(0x06, &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01]),
                    oid.to_vec()
                ])
            );
            assert_eq!(c.point_len, 2 * c.scalar_len + 1);
        }
    }
}