crypto-profile 0.9.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
//! Shared conformance data and helpers for `crypto-profile` backends.
use crate::{Algorithm, CryptoError, Module, SignatureAlgorithm, TlsSignatureScheme, capability};

#[doc(hidden)]
pub mod golden;
mod peer_certificate_tests;
mod profile_tests;

#[doc(hidden)]
pub use hex as __hex;
#[doc(hidden)]
pub use serde_json as __serde_json;

/// One Wycheproof signature case: `(public key, message, signature, result, tcId)`.
#[doc(hidden)]
pub type SigCase = (Vec<u8>, Vec<u8>, Vec<u8>, String, u64);

/// The signature-verification cases of a Wycheproof file; `pk_field` and `pk_sub` name where
/// each test group carries its raw public key. A case with a non-empty ML-DSA `ctx` is skipped,
/// because the backends verify under the empty context only.
#[doc(hidden)]
pub fn __wycheproof_sig_cases(file: &str, pk_field: &str, pk_sub: &str) -> Vec<SigCase> {
    let v: serde_json::Value = serde_json::from_str(file).unwrap_or_default();
    let mut out = Vec::new();
    for g in v["testGroups"].as_array().into_iter().flatten() {
        let pk_hex = if pk_sub.is_empty() {
            g[pk_field].as_str()
        } else {
            g[pk_field][pk_sub].as_str()
        };
        let pk = hex::decode(pk_hex.unwrap_or_default()).unwrap_or_default();
        for t in g["tests"].as_array().into_iter().flatten() {
            if !t["ctx"].as_str().unwrap_or_default().is_empty() {
                continue;
            }
            out.push((
                pk.clone(),
                hex::decode(t["msg"].as_str().unwrap_or_default()).unwrap_or_default(),
                hex::decode(t["sig"].as_str().unwrap_or_default()).unwrap_or_default(),
                t["result"].as_str().unwrap_or_default().to_string(),
                t["tcId"].as_u64().unwrap_or_default(),
            ));
        }
    }
    out
}

/// One Wycheproof AEAD case.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AeadCase {
    /// The key.
    pub key: Vec<u8>,
    /// The nonce.
    pub iv: Vec<u8>,
    /// The additional authenticated data.
    pub aad: Vec<u8>,
    /// The plaintext.
    pub msg: Vec<u8>,
    /// The ciphertext followed by the tag.
    pub ct_tag: Vec<u8>,
    /// `valid`, `invalid` or `acceptable`.
    pub result: String,
    /// The Wycheproof test-case id.
    pub tc_id: u64,
}

/// The cases of a Wycheproof AEAD file whose groups have exactly these key, IV and tag sizes in bits.
#[doc(hidden)]
pub fn __wycheproof_aead_cases(
    file: &str,
    key_bits: u64,
    iv_bits: u64,
    tag_bits: u64,
) -> Vec<AeadCase> {
    let v: serde_json::Value = serde_json::from_str(file).unwrap_or_default();
    let d = |x: &serde_json::Value| hex::decode(x.as_str().unwrap_or_default()).unwrap_or_default();
    let mut out = Vec::new();
    for g in v["testGroups"].as_array().into_iter().flatten() {
        let sizes = (
            g["keySize"].as_u64(),
            g["ivSize"].as_u64(),
            g["tagSize"].as_u64(),
        );
        if sizes != (Some(key_bits), Some(iv_bits), Some(tag_bits)) {
            continue;
        }
        for t in g["tests"].as_array().into_iter().flatten() {
            let mut ct_tag = d(&t["ct"]);
            ct_tag.extend_from_slice(&d(&t["tag"]));
            out.push(AeadCase {
                key: d(&t["key"]),
                iv: d(&t["iv"]),
                aad: d(&t["aad"]),
                msg: d(&t["msg"]),
                ct_tag,
                result: t["result"].as_str().unwrap_or_default().to_string(),
                tc_id: t["tcId"].as_u64().unwrap_or_default(),
            });
        }
    }
    out
}

/// `(message, digest)` pairs from a NIST CAVP `*ShortMsg.rsp` file, honouring `Len`.
#[doc(hidden)]
pub fn __cavp_short(file: &str) -> Vec<(Vec<u8>, Vec<u8>)> {
    let mut out = Vec::new();
    let (mut len, mut msg) = (0usize, Vec::new());
    for line in file.lines() {
        let line = line.trim();
        if let Some(v) = line.strip_prefix("Len = ") {
            len = v.parse().unwrap_or_default();
        } else if let Some(v) = line.strip_prefix("Msg = ") {
            msg = hex::decode(v).unwrap_or_default();
            msg.truncate(len / 8);
        } else if let Some(v) = line.strip_prefix("MD = ") {
            out.push((msg.clone(), hex::decode(v).unwrap_or_default()));
        }
    }
    out
}

/// The handshake schemes a test peer offers on `module`: every scheme the module has.
#[doc(hidden)]
pub fn __peer_schemes(module: Module) -> Vec<TlsSignatureScheme> {
    TlsSignatureScheme::ALL
        .into_iter()
        .filter(|t| capability(module, Algorithm::Scheme(*t)).available)
        .collect()
}

/// What a handshake whose server key is a fresh `key` gives when the client lists no scheme for
/// it: `no_scheme`, or, on a module without `key`, the refusal to generate that key.
#[doc(hidden)]
pub fn __unlisted_key(
    module: Module,
    key: SignatureAlgorithm,
    no_scheme: &str,
) -> Result<u16, String> {
    let a = Algorithm::Signature(key);
    if capability(module, a).available {
        Err(no_scheme.to_string())
    } else {
        Err(CryptoError::Unavailable(a).to_string())
    }
}

/// Whether `name` can be a shared library's name without its `lib` prefix and extension: not
/// empty, and no path separator or control character.
#[doc(hidden)]
pub fn __library_basename(name: &str) -> bool {
    !name.is_empty()
        && !name
            .chars()
            .any(|c| c == '/' || c == '\\' || c.is_control())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Linkage, ModuleLine, Options};

    const M3S: Module = Module {
        line: ModuleLine::AwsLcFips3,
        linkage: Linkage::Static,
    };
    const M3D: Module = Module {
        line: ModuleLine::AwsLcFips3,
        linkage: Linkage::Dynamic,
    };
    const M4S: Module = Module {
        line: ModuleLine::AwsLcFips4,
        linkage: Linkage::Static,
    };
    const M4D: Module = Module {
        line: ModuleLine::AwsLcFips4,
        linkage: Linkage::Dynamic,
    };

    #[test]
    fn the_profile_suite_hands_a_3x_module_only_what_it_has() {
        let ml_dsa = SignatureAlgorithm::MlDsa87;
        for m in [M3S, M3D] {
            assert!(
                __peer_schemes(m)
                    .iter()
                    .all(|t| capability(m, Algorithm::Scheme(*t)).available),
                "{m:?}"
            );
            let missing: Vec<Algorithm> = Algorithm::all()
                .into_iter()
                .filter(|a| !capability(m, *a).available)
                .collect();
            assert_eq!(
                missing,
                [
                    Algorithm::Signature(ml_dsa),
                    Algorithm::Scheme(TlsSignatureScheme::MlDsa87)
                ],
                "{m:?}"
            );
            for g in golden::GOLDEN {
                let o = Options {
                    peer_certificates_match_profile: false,
                    pq_key_exchange_required: g.pq,
                };
                if let Ok(row) = golden::expected(m, g.profile, o) {
                    assert!(!row.schemes.contains(&0x0906));
                    assert!(!row.keys.contains(&"ml-dsa-87"));
                }
            }
            assert_eq!(
                __unlisted_key(m, ml_dsa, "no scheme"),
                Err("Signature(MlDsa87) is not available on this backend's module".to_string())
            );
            assert_eq!(
                __unlisted_key(m, SignatureAlgorithm::Ed25519, "no scheme"),
                Err("no scheme".to_string())
            );
        }
    }

    #[test]
    fn the_profile_suite_helpers_change_nothing_on_4x() {
        for m in [M4S, M4D] {
            assert_eq!(__peer_schemes(m), TlsSignatureScheme::ALL);
            assert_eq!(
                __unlisted_key(m, SignatureAlgorithm::MlDsa87, "no scheme"),
                Err("no scheme".to_string())
            );
        }
    }

    #[test]
    fn a_library_name_is_a_bare_basename() {
        for ok in ["aws_lc_fips_0_14_2_crypto", "crypto"] {
            assert!(__library_basename(ok), "{ok}");
        }
        for bad in ["", "a/crypto", "a\\crypto", "crypto\n", "cry\0pto"] {
            assert!(!__library_basename(bad), "{bad:?}");
        }
    }

    #[test]
    fn cavp_short_honours_len() {
        let file = "[L = 32]\r\n\r\nLen = 0\r\nMsg = 00\r\nMD = aa\r\n\r\nLen = 16\r\nMsg = 0102\r\nMD = bbcc\r\n\r\nLen = 8\r\nMsg = 0102\r\nMD = dd\r\n";
        assert_eq!(
            __cavp_short(file),
            vec![
                (vec![], vec![0xaa]),
                (vec![1, 2], vec![0xbb, 0xcc]),
                (vec![1], vec![0xdd]),
            ]
        );
    }

    #[test]
    fn signature_cases_read_the_named_key_field() {
        let file = r#"{"testGroups":[
            {"publicKey":{"pk":"01"},"flat":"02","tests":[{"tcId":7,"msg":"03","sig":"04","result":"valid"}]},
            {"publicKey":{"pk":"05"},"flat":"06","tests":[{"tcId":8,"msg":"","sig":"07","result":"invalid"},{"tcId":9,"msg":"","sig":"07","ctx":"08","result":"valid"}]}
        ]}"#;
        assert_eq!(
            __wycheproof_sig_cases(file, "publicKey", "pk"),
            vec![
                (vec![1], vec![3], vec![4], "valid".to_string(), 7),
                (vec![5], vec![], vec![7], "invalid".to_string(), 8),
            ]
        );
        let flat = __wycheproof_sig_cases(file, "flat", "");
        assert_eq!(
            flat.iter().map(|c| c.0.clone()).collect::<Vec<_>>(),
            vec![vec![2], vec![6]]
        );
        assert!(__wycheproof_sig_cases("not json", "flat", "").is_empty());
    }

    #[test]
    fn aead_cases_keep_only_the_named_sizes() {
        let file = r#"{"testGroups":[
            {"keySize":128,"ivSize":96,"tagSize":128,"tests":[{"tcId":1,"key":"00","iv":"00","aad":"","msg":"","ct":"","tag":"00","result":"valid"}]},
            {"keySize":256,"ivSize":128,"tagSize":128,"tests":[{"tcId":2,"key":"00","iv":"00","aad":"","msg":"","ct":"","tag":"00","result":"valid"}]},
            {"keySize":256,"ivSize":96,"tagSize":64,"tests":[{"tcId":3,"key":"00","iv":"00","aad":"","msg":"","ct":"","tag":"00","result":"valid"}]},
            {"keySize":256,"ivSize":96,"tagSize":128,"tests":[{"tcId":4,"key":"01","iv":"02","aad":"03","msg":"04","ct":"05","tag":"06","result":"invalid"}]}
        ]}"#;
        assert_eq!(
            __wycheproof_aead_cases(file, 256, 96, 128),
            vec![AeadCase {
                key: vec![1],
                iv: vec![2],
                aad: vec![3],
                msg: vec![4],
                ct_tag: vec![5, 6],
                result: "invalid".to_string(),
                tc_id: 4,
            }]
        );
    }
}

/// Known-answer data every backend's conformance run checks.
pub mod vectors {
    /// Wycheproof ECDSA P-256 / SHA-256.
    pub const ECDSA_P256: &str = include_str!("vectors/ecdsa_secp256r1_sha256_test.json");
    /// Wycheproof ECDSA P-384 / SHA-384.
    pub const ECDSA_P384: &str = include_str!("vectors/ecdsa_secp384r1_sha384_test.json");
    /// Wycheproof ECDSA P-521 / SHA-512.
    pub const ECDSA_P521: &str = include_str!("vectors/ecdsa_secp521r1_sha512_test.json");
    /// Wycheproof Ed25519.
    pub const ED25519: &str = include_str!("vectors/ed25519_test.json");
    /// RFC 8032 Ed25519 test vectors 1-3.
    pub const ED25519_RFC8032: &str = include_str!("vectors/ed25519_rfc8032.json");
    /// Wycheproof RSA PKCS#1 v1.5, 2048-bit, SHA-384.
    pub const RSA_PKCS1_SHA384: &str = include_str!("vectors/rsa_signature_2048_sha384_test.json");
    /// Wycheproof RSA PKCS#1 v1.5, 3072-bit, SHA-384.
    pub const RSA3072_PKCS1_SHA384: &str =
        include_str!("vectors/rsa_signature_3072_sha384_test.json");
    /// Wycheproof RSA PKCS#1 v1.5, 4096-bit, SHA-384.
    pub const RSA4096_PKCS1_SHA384: &str =
        include_str!("vectors/rsa_signature_4096_sha384_test.json");
    /// Wycheproof ML-DSA-87 verification.
    pub const ML_DSA_87: &str = include_str!("vectors/mldsa_87_verify_test.json");
    /// Wycheproof AES-GCM.
    pub const AES_GCM: &str = include_str!("vectors/aes_gcm_test.json");
    /// NIST CAVP SHA-256 short messages.
    pub const SHA256_SHORT: &str = include_str!("vectors/SHA256ShortMsg.rsp");
    /// NIST CAVP SHA-384 short messages.
    pub const SHA384_SHORT: &str = include_str!("vectors/SHA384ShortMsg.rsp");
    /// NIST CAVP SHA-512 short messages.
    pub const SHA512_SHORT: &str = include_str!("vectors/SHA512ShortMsg.rsp");

    /// The sealed-box known-answer vectors, produced by an independent implementation.
    pub mod sealbox {
        /// The domain the known-answer blob was sealed under.
        pub const DOMAIN: &[u8] = b"maknae-seal-v1";
        /// The plaintext of the known-answer blob.
        pub const PLAINTEXT: &[u8] = b"maknae-seal known-answer plaintext";
        /// The recipient's P-384 private key as PKCS#8 DER, hex-encoded.
        pub const PRIVATE_KEY_PKCS8_HEX: &str = "3081b6020100301006072a8648ce3d020106052b8104002204819e30819b0201010430111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111a16403620004386e767ea5cb716c9cd620ff7342129c892a6fccefe612140c80bff59e943468019dda16e5079b0c1d9001d23a624b6dd088d0c3826394194787403e8a7d07e5e22f7e9c0b8e80fa1faff5d28b4bb597b267f0b87023ca61fc8454bddefd2e0e";
        /// The known-answer sealed blob, hex-encoded.
        pub const BLOB_HEX: &str = "01044f2bda7fd2105f8467e21f45223ad58863ffa4c084832d9f6c64ffc47fdd519727ab53cb71f9c40de24b64acde61f02fc7dce130b612fa5dbcac94573a2354fd005d8e9caefdc5fde48304474708bbd82f77e1fd2c630bea236f6f8dccc1678e000102030405060708090a0b9e5112a45c454d89052a69d413fb8bab9027d5b1ee8f724947f1375c31bf4f0cca4de10984b9e6f2057ce1ec13c1185fb116";
        /// AES-256-GCM output (ciphertext and tag), hex-encoded, under the key derived from a fixed
        /// shared secret of 48 bytes of `0x33` and the known-answer ephemeral key.
        pub const FIXED_SHARED_CT_HEX: &str = "0b97a82530c1e3b734c40e1d1bd3021ecd6c502e16d304d333ccdfdf7e0f35672a70c0815ce1d2c6c5ad3ab9c8968987c6c3";
        /// The nonce of [`FIXED_SHARED_CT_HEX`].
        pub const NONCE: [u8; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

        /// The additional authenticated data of the known-answer blob.
        pub fn aad() -> Vec<u8> {
            let mut out = b"maknae-seal-aad-v1".to_vec();
            for field in [
                "c-1",
                "openai",
                "gpt-5.6-luna",
                "maknae-kv/data/maknae/users/alice/openai/personal",
                "api_key",
            ] {
                out.extend_from_slice(&(field.len() as u16).to_be_bytes());
                out.extend_from_slice(field.as_bytes());
            }
            out
        }

        #[cfg(test)]
        mod tests {
            use super::*;
            use crate::sealbox_wire::{MIN_BLOB_LEN, NONCE_LEN, VERSION};

            #[test]
            fn the_vectors_are_well_formed() {
                let blob = crate::conformance::__hex::decode(BLOB_HEX).unwrap();
                assert!(blob.len() >= MIN_BLOB_LEN);
                assert_eq!(blob[0], VERSION);
                assert_eq!(NONCE.len(), NONCE_LEN);
                assert_eq!(
                    &blob[1 + crate::sealbox_wire::EPHEMERAL_KEY_LEN
                        ..crate::sealbox_wire::HEADER_LEN],
                    &NONCE
                );
                assert_eq!(blob.len(), crate::sealbox_wire::sealed_len(PLAINTEXT.len()));
                assert_eq!(
                    crate::conformance::__hex::decode(PRIVATE_KEY_PKCS8_HEX)
                        .unwrap()
                        .len(),
                    185
                );
                assert_eq!(
                    crate::conformance::__hex::decode(FIXED_SHARED_CT_HEX)
                        .unwrap()
                        .len(),
                    PLAINTEXT.len() + 16
                );
            }

            #[test]
            fn the_aad_is_length_prefixed_fields() {
                let aad = aad();
                assert!(aad.starts_with(b"maknae-seal-aad-v1\x00\x03c-1\x00\x06openai"));
                assert!(aad.ends_with(b"\x00\x07api_key"));
            }
        }
    }
}

/// Expands, in a backend's integration test, to the conformance tests over that backend.
#[macro_export]
macro_rules! conformance_tests {
    ($b:ident) => {
        use $b::test_support::handshake;
        use $b::tls::Policy;
        use $b::*;
        use $crate::conformance::{
            __cavp_short, __wycheproof_aead_cases, __wycheproof_sig_cases, vectors,
        };

        fn policy(
            v: &[TlsVersion],
            c: &[CipherSuite],
            k: &[KxGroup],
            t: &[TlsSignatureScheme],
        ) -> Policy {
            Policy {
                peer_certificate_rule: None,
                versions: v.to_vec(),
                cipher_suites: c.to_vec(),
                kx_groups: k.to_vec(),
                signature_schemes: t.to_vec(),
            }
        }

        fn suite_key(c: CipherSuite) -> SignatureAlgorithm {
            match c {
                CipherSuite::Tls12EcdheRsaAes256GcmSha384
                | CipherSuite::Tls12EcdheRsaAes128GcmSha256
                | CipherSuite::Tls12EcdheRsaChacha20Poly1305Sha256 => {
                    SignatureAlgorithm::Rsa2048Sha384
                }
                CipherSuite::Tls13Aes256GcmSha384
                | CipherSuite::Tls13Aes128GcmSha256
                | CipherSuite::Tls13Chacha20Poly1305Sha256
                | CipherSuite::Tls12EcdheEcdsaAes256GcmSha384
                | CipherSuite::Tls12EcdheEcdsaAes128GcmSha256
                | CipherSuite::Tls12EcdheEcdsaChacha20Poly1305Sha256 => {
                    SignatureAlgorithm::EcdsaP384Sha384
                }
            }
        }

        // RFC 8446 §4.2.3 forbids PKCS#1 v1.5 for TLS 1.3 handshake signatures, so those schemes are exercised on TLS 1.2.
        fn scheme_setup(t: TlsSignatureScheme) -> (SignatureAlgorithm, TlsVersion, CipherSuite) {
            let t13 = (TlsVersion::Tls13, CipherSuite::Tls13Aes256GcmSha384);
            let rsa12 = (TlsVersion::Tls12, CipherSuite::Tls12EcdheRsaAes256GcmSha384);
            match t {
                TlsSignatureScheme::EcdsaNistp256Sha256 => {
                    (SignatureAlgorithm::EcdsaP256Sha256, t13.0, t13.1)
                }
                TlsSignatureScheme::EcdsaNistp384Sha384 => {
                    (SignatureAlgorithm::EcdsaP384Sha384, t13.0, t13.1)
                }
                TlsSignatureScheme::EcdsaNistp521Sha512 => {
                    (SignatureAlgorithm::EcdsaP521Sha512, t13.0, t13.1)
                }
                TlsSignatureScheme::Ed25519 => (SignatureAlgorithm::Ed25519, t13.0, t13.1),
                TlsSignatureScheme::RsaPssSha256
                | TlsSignatureScheme::RsaPssSha384
                | TlsSignatureScheme::RsaPssSha512 => {
                    (SignatureAlgorithm::Rsa2048Sha384, t13.0, t13.1)
                }
                TlsSignatureScheme::RsaPkcs1Sha256
                | TlsSignatureScheme::RsaPkcs1Sha384
                | TlsSignatureScheme::RsaPkcs1Sha512 => {
                    (SignatureAlgorithm::Rsa2048Sha384, rsa12.0, rsa12.1)
                }
                TlsSignatureScheme::MlDsa87 => (SignatureAlgorithm::MlDsa87, t13.0, t13.1),
            }
        }

        fn reference_pq_first() -> Policy {
            policy(
                &[TlsVersion::Tls13],
                &[
                    CipherSuite::Tls13Aes256GcmSha384,
                    CipherSuite::Tls13Aes128GcmSha256,
                ],
                &[
                    KxGroup::MlKem1024,
                    KxGroup::X25519MlKem768,
                    KxGroup::Secp256r1MlKem768,
                    KxGroup::Secp384r1,
                    KxGroup::Secp256r1,
                ],
                &$crate::conformance::__peer_schemes(MODULE),
            )
        }

        fn reference_cnsa1() -> Policy {
            policy(
                &[TlsVersion::Tls13, TlsVersion::Tls12],
                &[
                    CipherSuite::Tls13Aes256GcmSha384,
                    CipherSuite::Tls12EcdheEcdsaAes256GcmSha384,
                    CipherSuite::Tls12EcdheRsaAes256GcmSha384,
                ],
                &[KxGroup::Secp384r1],
                &$crate::conformance::__peer_schemes(MODULE),
            )
        }

        #[test]
        fn conformance_sha2_cavp_short_messages() {
            for (h, file) in [
                (HashAlgorithm::Sha256, vectors::SHA256_SHORT),
                (HashAlgorithm::Sha384, vectors::SHA384_SHORT),
                (HashAlgorithm::Sha512, vectors::SHA512_SHORT),
            ] {
                let cases = __cavp_short(file);
                let want = match h {
                    HashAlgorithm::Sha256 => 65,
                    HashAlgorithm::Sha384 | HashAlgorithm::Sha512 => 129,
                };
                assert_eq!(cases.len(), want, "{h:?}");
                for (m, d) in cases {
                    assert_eq!(digest::digest(h, &m), d, "{h:?}");
                }
            }
        }

        #[test]
        fn conformance_wycheproof_signatures() {
            let p = "publicKey";
            for (a, file, field, sub, want) in [
                (
                    SignatureAlgorithm::EcdsaP256Sha256,
                    vectors::ECDSA_P256,
                    p,
                    "uncompressed",
                    (174, 310),
                ),
                (
                    SignatureAlgorithm::EcdsaP384Sha384,
                    vectors::ECDSA_P384,
                    p,
                    "uncompressed",
                    (194, 310),
                ),
                (
                    SignatureAlgorithm::EcdsaP521Sha512,
                    vectors::ECDSA_P521,
                    p,
                    "uncompressed",
                    (232, 310),
                ),
                (
                    SignatureAlgorithm::Ed25519,
                    vectors::ED25519,
                    p,
                    "pk",
                    (117, 64),
                ),
                (
                    SignatureAlgorithm::Rsa2048Sha384,
                    vectors::RSA_PKCS1_SHA384,
                    "publicKeyAsn",
                    "",
                    (7, 250),
                ),
                (
                    SignatureAlgorithm::Rsa3072Sha384,
                    vectors::RSA3072_PKCS1_SHA384,
                    "publicKeyAsn",
                    "",
                    (7, 251),
                ),
                (
                    SignatureAlgorithm::Rsa4096Sha384,
                    vectors::RSA4096_PKCS1_SHA384,
                    "publicKeyAsn",
                    "",
                    (7, 251),
                ),
                (
                    SignatureAlgorithm::MlDsa87,
                    vectors::ML_DSA_87,
                    p,
                    "",
                    (69, 165),
                ),
            ] {
                let available = capability(MODULE, Algorithm::Signature(a)).available;
                let (mut valid, mut invalid) = (0, 0);
                for (pk, msg, sig, result, id) in __wycheproof_sig_cases(file, field, sub) {
                    let verdict = signature::verify(a, &pk, &msg, &sig);
                    if !available {
                        assert_eq!(
                            verdict,
                            Err(CryptoError::Unavailable(Algorithm::Signature(a))),
                            "{a} tcId {id}"
                        );
                    }
                    let ok = verdict.is_ok();
                    match result.as_str() {
                        "valid" => {
                            valid += 1;
                            if let Some(len) = rsa_public_len(a) {
                                // An RSAPublicKey DER with e = 65537 ends with INTEGER 0x010001.
                                assert!(
                                    pk.len() == len
                                        && pk.ends_with(&[0x02, 0x03, 0x01, 0x00, 0x01]),
                                    "{a} tcId {id}: not an e=65537 key of the algorithm's size"
                                );
                            }
                            if module_refuses(a, id) {
                                assert!(
                                    !ok,
                                    "{a} tcId {id}: now accepted; drop it from module_refuses (#24)"
                                );
                            } else {
                                assert!(ok || !available, "{a} tcId {id}: valid but refused");
                            }
                        }
                        "invalid" => {
                            invalid += 1;
                            assert!(!ok, "{a} tcId {id}: invalid but accepted");
                        }
                        "acceptable" => {}
                        other => panic!("{a} tcId {id}: unknown result {other:?}"),
                    }
                }
                assert_eq!((valid, invalid), want, "{a}");
            }
        }

        // AWS-LC refuses these valid P-256 signatures on aarch64 (#24).
        fn module_refuses(a: SignatureAlgorithm, id: u64) -> bool {
            cfg!(target_arch = "aarch64")
                && matches!(a, SignatureAlgorithm::EcdsaP256Sha256)
                && matches!(id, 483 | 484)
        }

        fn rsa_public_len(a: SignatureAlgorithm) -> Option<usize> {
            match a {
                SignatureAlgorithm::Rsa2048Sha384 => Some(270),
                SignatureAlgorithm::Rsa3072Sha384 => Some(398),
                SignatureAlgorithm::Rsa4096Sha384 => Some(526),
                SignatureAlgorithm::MlDsa87
                | SignatureAlgorithm::EcdsaP256Sha256
                | SignatureAlgorithm::EcdsaP384Sha384
                | SignatureAlgorithm::EcdsaP521Sha384
                | SignatureAlgorithm::EcdsaP521Sha512
                | SignatureAlgorithm::Ed25519 => None,
            }
        }

        #[test]
        fn conformance_wycheproof_aes_gcm() {
            let cases = __wycheproof_aead_cases(vectors::AES_GCM, 256, 96, 128);
            let (mut valid, mut invalid) = (0, 0);
            for c in cases {
                let key: [u8; aead::KEY_LEN] = c.key.as_slice().try_into().unwrap();
                let nonce: [u8; aead::NONCE_LEN] = c.iv.as_slice().try_into().unwrap();
                let k = aead::Aes256GcmKey::new(&key).unwrap();
                let mut buf = c.ct_tag.clone();
                let opened = k
                    .open_in_place(&nonce, &c.aad, &mut buf)
                    .map(|p| p.to_vec());
                match c.result.as_str() {
                    "valid" => {
                        valid += 1;
                        assert_eq!(opened, Ok(c.msg), "tcId {}", c.tc_id);
                    }
                    "invalid" => {
                        invalid += 1;
                        assert_eq!(opened, Err(CryptoError::AeadOpen), "tcId {}", c.tc_id);
                    }
                    other => panic!("tcId {}: unknown result {other:?}", c.tc_id),
                }
            }
            assert_eq!((valid, invalid), (39, 27));
        }

        #[test]
        fn conformance_rfc8032_ed25519() {
            let v: $crate::conformance::__serde_json::Value =
                $crate::conformance::__serde_json::from_str(vectors::ED25519_RFC8032).unwrap();
            let d = |x: &$crate::conformance::__serde_json::Value| {
                $crate::conformance::__hex::decode(x.as_str().unwrap()).unwrap()
            };
            let cases = v.as_array().unwrap();
            assert_eq!(cases.len(), 3);
            for t in cases {
                assert_eq!(
                    signature::verify(
                        SignatureAlgorithm::Ed25519,
                        &d(&t["pk"]),
                        &d(&t["msg"]),
                        &d(&t["sig"])
                    ),
                    Ok(())
                );
            }
        }

        #[test]
        fn conformance_sealed_box_v1_known_answer_opens() {
            use vectors::sealbox as kat;
            let pkcs8 = $crate::conformance::__hex::decode(kat::PRIVATE_KEY_PKCS8_HEX).unwrap();
            let blob = $crate::conformance::__hex::decode(kat::BLOB_HEX).unwrap();
            let key = sealbox::PrivateKey::from_pkcs8_der(&pkcs8).unwrap();
            let opened = sealbox::open(&key, kat::DOMAIN, &kat::aad(), &blob).unwrap();
            assert_eq!(&opened[..], kat::PLAINTEXT);
        }

        #[test]
        fn conformance_capability_honesty() {
            for a in Algorithm::all() {
                let cap = capability(MODULE, a);
                match a {
                    Algorithm::Signature(s) => match sign_and_verify(s) {
                        Ok(()) => assert!(cap.available, "{a:?} works but is marked unavailable"),
                        Err(e) => assert!(
                            !cap.available && e == CryptoError::Unavailable(a),
                            "{a:?}: {e}"
                        ),
                    },
                    Algorithm::Hash(h) => {
                        assert!(cap.available, "{a:?}");
                        assert_eq!(digest::digest(h, b"").len(), h.output_len());
                    }
                    Algorithm::Kx(k) => {
                        let p = policy(
                            &[TlsVersion::Tls13],
                            &[CipherSuite::Tls13Aes256GcmSha384],
                            &[k],
                            &$crate::conformance::__peer_schemes(MODULE),
                        );
                        if cap.available {
                            let n = handshake(&p, &p, SignatureAlgorithm::EcdsaP384Sha384)
                                .unwrap_or_else(|e| panic!("{a:?}: {e}"));
                            assert_eq!(n.kx, k, "{a:?}");
                        } else {
                            assert_eq!(
                                tls::crypto_provider(&p).err(),
                                Some(CryptoError::Unavailable(a))
                            );
                        }
                    }
                    Algorithm::Cipher(c) => {
                        let p = policy(
                            &[c.version()],
                            &[c],
                            &[KxGroup::Secp384r1],
                            &$crate::conformance::__peer_schemes(MODULE),
                        );
                        if cap.available {
                            let n = handshake(&p, &p, suite_key(c))
                                .unwrap_or_else(|e| panic!("{a:?}: {e}"));
                            assert_eq!((n.version, n.suite), (c.version(), c), "{a:?}");
                        } else {
                            assert_eq!(
                                tls::crypto_provider(&p).err(),
                                Some(CryptoError::Unavailable(a))
                            );
                        }
                    }
                    Algorithm::Protocol(v) => {
                        let suites: Vec<_> = CipherSuite::ALL
                            .into_iter()
                            .filter(|c| c.version() == v)
                            .collect();
                        let p = policy(
                            &[v],
                            &suites,
                            &[KxGroup::Secp384r1],
                            &$crate::conformance::__peer_schemes(MODULE),
                        );
                        if cap.available {
                            let n = handshake(&p, &p, SignatureAlgorithm::EcdsaP384Sha384)
                                .unwrap_or_else(|e| panic!("{a:?}: {e}"));
                            assert_eq!(n.version, v, "{a:?}");
                        } else {
                            assert_eq!(
                                tls::crypto_provider(&p).err(),
                                Some(CryptoError::Unavailable(a))
                            );
                        }
                    }
                    Algorithm::Scheme(t) => {
                        let (key, v, c) = scheme_setup(t);
                        let server = policy(
                            &[v],
                            &[c],
                            &[KxGroup::Secp384r1],
                            &$crate::conformance::__peer_schemes(MODULE),
                        );
                        let client = policy(&[v], &[c], &[KxGroup::Secp384r1], &[t]);
                        if cap.available {
                            let n = handshake(&client, &server, key)
                                .unwrap_or_else(|e| panic!("{a:?}: {e}"));
                            assert_eq!(n.scheme, t, "{a:?}");
                        } else {
                            assert_eq!(
                                tls::crypto_provider(&client).err(),
                                Some(CryptoError::Unavailable(a))
                            );
                        }
                    }
                }
            }
        }

        fn sign_and_verify(s: SignatureAlgorithm) -> Result<(), CryptoError> {
            let k = signature::KeyPair::generate(s)?;
            let sig = k.sign(b"m")?;
            signature::verify(s, &k.public_key(), b"m", &sig)
        }

        #[test]
        fn conformance_reference_policies_handshake() {
            let n = handshake(
                &reference_pq_first(),
                &reference_pq_first(),
                SignatureAlgorithm::EcdsaP384Sha384,
            )
            .unwrap();
            assert_eq!(
                (n.version, n.suite, n.kx),
                (
                    TlsVersion::Tls13,
                    CipherSuite::Tls13Aes256GcmSha384,
                    KxGroup::MlKem1024
                )
            );
            let n = handshake(
                &reference_cnsa1(),
                &reference_cnsa1(),
                SignatureAlgorithm::EcdsaP384Sha384,
            )
            .unwrap();
            assert_eq!(
                (n.version, n.suite, n.kx),
                (
                    TlsVersion::Tls13,
                    CipherSuite::Tls13Aes256GcmSha384,
                    KxGroup::Secp384r1
                )
            );
            let legacy = policy(
                &[TlsVersion::Tls12],
                &[CipherSuite::Tls12EcdheRsaAes256GcmSha384],
                &[KxGroup::Secp384r1],
                &$crate::conformance::__peer_schemes(MODULE),
            );
            let n = handshake(
                &legacy,
                &reference_cnsa1(),
                SignatureAlgorithm::Rsa3072Sha384,
            )
            .unwrap();
            assert_eq!(
                (n.version, n.suite, n.kx),
                (
                    TlsVersion::Tls12,
                    CipherSuite::Tls12EcdheRsaAes256GcmSha384,
                    KxGroup::Secp384r1
                )
            );
        }

        #[test]
        fn conformance_runtime_release_matches_the_selected_line() {
            let expected = if MODULE.line == ModuleLine::AwsLcFips3 {
                "3.6.0"
            } else {
                assert_eq!(MODULE.line, ModuleLine::AwsLcFips4);
                "4.2.0"
            };
            assert_eq!(awslc_version(), expected);
        }

        #[test]
        fn conformance_linkage_matches_the_binary() {
            if let Ok(intended) = std::env::var("AWS_LC_FIPS_SYS_STATIC") {
                let expected = match intended.as_str() {
                    "1" => Linkage::Static,
                    "0" => Linkage::Dynamic,
                    other => panic!("invalid intended linkage: {other:?}"),
                };
                assert_eq!(MODULE.linkage, expected, "{MODULE:?}");
            }
            let lib = test_support::FIPS_LIBRARY;
            assert!($crate::conformance::__library_basename(lib), "{lib:?}");
            let named = |path: Option<&str>, file: &str| {
                path.and_then(|p| p.rsplit('/').next()) == Some(file)
            };
            if cfg!(target_os = "linux") {
                let maps = std::fs::read_to_string("/proc/self/maps").unwrap();
                let file = format!("lib{lib}.so");
                let shared = maps
                    .lines()
                    .any(|l| named(l.split_whitespace().nth(5), &file));
                assert_eq!(shared, MODULE.linkage == Linkage::Dynamic, "{MODULE:?}");
            } else if cfg!(target_os = "macos") {
                let exe = std::env::current_exe().unwrap();
                let out = std::process::Command::new("otool")
                    .arg("-L")
                    .arg(&exe)
                    .output()
                    .unwrap();
                let file = format!("lib{lib}.dylib");
                let shared = String::from_utf8_lossy(&out.stdout)
                    .lines()
                    .any(|l| named(l.split_whitespace().next(), &file));
                assert_eq!(shared, MODULE.linkage == Linkage::Dynamic, "{MODULE:?}");
            } else {
                panic!("no linkage check for this target");
            }
        }

        mod conformance_profiles {
            $crate::__conformance_profile_tests!($b);
        }
    };
}