ic-fips 0.2.12

FIPS 140-3 module policy, self-tests, and service indicators for IronCrypto
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
//! Known-answer tests for every implemented algorithm.
//!
//! FIPS 140-3 requires a *cryptographic algorithm self-test* (CAST) for each
//! approved security function, run before that function is first used, plus a
//! pre-operational software integrity test. This module provides both.
//!
//! Each algorithm implements [`ic_core::traits::SelfTest`], so the table below
//! is a list of function pointers rather than a re-implementation of each
//! vector — the test that runs at startup is the same code path the unit tests
//! exercise.

use ic_core::traits::SelfTest;
use ic_core::Result;

/// The result of one known-answer test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TestOutcome {
    /// The ontology identifier of the algorithm under test.
    pub algorithm: &'static str,
    /// Whether its known-answer test passed.
    pub passed: bool,
}

/// The outcome of a full self-test run.
#[derive(Debug, Clone)]
pub struct SelfTestReport {
    /// How many tests passed.
    pub passed: usize,
    /// How many failed.
    pub failed: usize,
    /// Per-algorithm results, in table order.
    pub outcomes: [TestOutcome; TEST_COUNT],
}

impl SelfTestReport {
    /// The algorithms whose tests failed.
    pub fn failures(&self) -> impl Iterator<Item = &TestOutcome> {
        self.outcomes.iter().filter(|o| !o.passed)
    }

    /// Whether every test passed.
    pub fn all_passed(&self) -> bool {
        self.failed == 0
    }
}

/// One entry in the CAST table.
type Cast = (&'static str, fn() -> Result<()>);

/// Every algorithm with a known-answer test, in a fixed order.
///
/// The order is stable so that a failure report is comparable between runs.
static CASTS: &[Cast] = &[
    // Hashes
    ("sha2-224", ic_hash::Sha224::self_test),
    ("sha2-256", ic_hash::Sha256::self_test),
    ("sha2-384", ic_hash::Sha384::self_test),
    ("sha2-512", ic_hash::Sha512::self_test),
    ("sha2-512-224", ic_hash::Sha512_224::self_test),
    ("sha2-512-256", ic_hash::Sha512_256::self_test),
    ("sha3-224", ic_hash::Sha3_224::self_test),
    ("sha3-256", ic_hash::Sha3_256::self_test),
    ("sha3-384", ic_hash::Sha3_384::self_test),
    ("sha3-512", ic_hash::Sha3_512::self_test),
    ("shake128", ic_hash::Shake128::self_test),
    ("shake256", ic_hash::Shake256::self_test),
    ("cshake128", ic_hash::CShake128::self_test),
    ("cshake256", ic_hash::CShake256::self_test),
    ("tuplehash128", ic_hash::TupleHash128::self_test),
    ("tuplehash256", ic_hash::TupleHash256::self_test),
    ("parallelhash128", ic_hash::ParallelHash128::self_test),
    ("parallelhash256", ic_hash::ParallelHash256::self_test),
    // MACs
    ("hmac-sha2-256", ic_mac::HmacSha256::self_test),
    ("hmac-sha2-384", ic_mac::HmacSha384::self_test),
    ("hmac-sha2-512", ic_mac::HmacSha512::self_test),
    ("hmac-sha2-512-256", ic_mac::HmacSha512_256::self_test),
    ("hmac-sha3-256", ic_mac::HmacSha3_256::self_test),
    ("hmac-sha3-512", ic_mac::HmacSha3_512::self_test),
    ("cmac-aes-128", ic_mac::CmacAes128::self_test),
    ("cmac-aes-192", ic_mac::CmacAes192::self_test),
    ("cmac-aes-256", ic_mac::CmacAes256::self_test),
    ("kmac128", ic_mac::Kmac128::self_test),
    ("kmac256", ic_mac::Kmac256::self_test),
    ("poly1305", ic_cipher::Poly1305::self_test),
    ("blake2b", blake2b_self_test),
    // Block ciphers and AEADs
    ("aes-128", ic_cipher::Aes128::self_test),
    ("aes-192", ic_cipher::Aes192::self_test),
    ("aes-256", ic_cipher::Aes256::self_test),
    ("aes-128-gcm", ic_cipher::Aes128Gcm::self_test),
    ("aes-192-gcm", ic_cipher::Aes192Gcm::self_test),
    ("aes-256-gcm", ic_cipher::Aes256Gcm::self_test),
    ("chacha20-poly1305", ic_cipher::ChaCha20Poly1305::self_test),
    ("aes-128-gcm-siv", ic_cipher::Aes128GcmSiv::self_test),
    ("aes-256-gcm-siv", ic_cipher::Aes256GcmSiv::self_test),
    ("aes-128-kw", ic_cipher::Aes128Kw::self_test),
    ("aes-256-kw", ic_cipher::Aes256Kw::self_test),
    ("aes-192-kwp", ic_cipher::Aes192Kwp::self_test),
    ("aes-256-kwp", ic_cipher::Aes256Kwp::self_test),
    // KDFs
    (
        "hkdf-sha2-256",
        ic_kdf::Hkdf::<ic_mac::HmacSha256>::self_test,
    ),
    ("argon2id", argon2id_self_test),
    // Post-quantum
    ("ml-kem-512", ml_kem_512_self_test),
    ("ml-kem-768", ml_kem_768_self_test),
    ("ml-kem-1024", ml_kem_1024_self_test),
    ("ml-dsa-44", ml_dsa_44_self_test),
    ("ml-dsa-65", ml_dsa_65_self_test),
    ("ml-dsa-87", ml_dsa_87_self_test),
    // DRBGs
    ("hmac-drbg-sha2-256", ic_drbg::HmacDrbgSha256::self_test),
    ("ctr-drbg-aes-256", ic_drbg::CtrDrbg::self_test),
    // Elliptic curve
    ("x25519", ic_ec::X25519::self_test),
    ("ed25519", ic_ec::Ed25519::self_test),
    ("ecdh-p256", ic_ec::p256::EcdhP256::self_test),
    ("ecdsa-p256-sha256", ic_ec::p256::EcdsaP256Sha256::self_test),
    ("ecdh-p384", ic_ec::p384::EcdhP384::self_test),
    ("ecdsa-p384-sha384", ic_ec::p384::EcdsaP384Sha384::self_test),
    ("ecdh-p521", ic_ec::p521::EcdhP521::self_test),
    ("ecdsa-p521-sha512", ic_ec::p521::EcdsaP521Sha512::self_test),
    // Constructions
    ("hpke-x25519-sha256", ic_hpke::Hpke::self_test),
    ("shamir-gf256", ic_cipher::shamir::Shamir::self_test),
    // RSA
    //
    // Six 2048-bit private-key operations, which dominate the runtime of this
    // suite. They stay in because every ontology entry marked Available has to
    // have a CAST; an algorithm offered without one is exactly the gap this
    // table exists to close.
    ("rsa-pkcs1-sha256", ic_rsa::Pkcs1Sha256::self_test),
    ("rsa-pkcs1-sha384", ic_rsa::Pkcs1Sha384::self_test),
    ("rsa-pkcs1-sha512", ic_rsa::Pkcs1Sha512::self_test),
    ("rsa-pss-sha256", ic_rsa::PssSha256::self_test),
    ("rsa-pss-sha384", ic_rsa::PssSha384::self_test),
    ("rsa-pss-sha512", ic_rsa::PssSha512::self_test),
];

/// BLAKE2b known-answer test: RFC 7693 Appendix A.
///
/// BLAKE2b has a variable output length and so does not fit the fixed-size
/// `Digest`/`SelfTest` pair; its CAST is spelled out here instead.
fn blake2b_self_test() -> Result<()> {
    let mut got = [0u8; 64];
    ic_hash::Blake2b::hash(b"abc", &mut got)?;
    let mut want = [0u8; 64];
    ic_core::codec::hex_decode(
        b"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923",
        &mut want,
    )?;
    ic_core::ensure!(ic_core::ct::verify(&want, &got), SelfTestFailed, "blake2b");
    Ok(())
}

/// ML-KEM-768 known-answer test: ACVP ML-KEM-keyGen-FIPS203, tcId 26.
///
/// Key generation is deterministic in `(d, z)`, so this one case exercises the
/// sampler, the NTT and the whole encapsulation-key encoding together. Only the
/// encapsulation key is compared: the decapsulation key comes out of the same
/// computation and contains this verbatim, so checking both would double the
/// size of this file and catch nothing more.
///
/// Taken from usnistgov/ACVP-Server at 975de31eb83d. The same case is in
/// testvectors/ml-kem-768-keygen.json, where the full set of 25 is checked.
fn ml_kem_768_self_test() -> Result<()> {
    const D: &[u8] = b"\
         E582B7D75E6C80B05AE392A1FC9F7153B12390FD99930368CC67A768BAEBC8A0";
    const Z: &[u8] = b"\
         1CDACB8740C0B87C4A379575F187B367CBFA3B300BF591B109F79816E9CBE8F0";
    const EK: &[u8] = b"\
         28C793778741B80B02B4339F2AA4347255B099F17264E1B8CC0A2C7C2A1A79F7997B907FD0496C6E6C8AD7714F5F\
         339D75F11F625591A869BE1175AE47F05FD4313468232BA6957D7807B824F445AC99A0D568AB1AD54DCA8249D148\
         2E61275F52248C77F61A4248753188CD1794CD0A465EC0DC4B025985C461B74E76286E4C37E77405695CC9FD0654\
         374B427A20343AEC0FF1A187768273BFC4905472A1DA387F14559D6CE87313F6A5B6138434539F9A13684055B177\
         E543F8B40F432ABD7CC49989A50A9084C660913F45A8593B17499BC4CF936C2BC1851421CB986808A0EF30AFE97A\
         AB5B8B8EB3F0B3506A95B91563A0E57DB7231044987EF141BDAB3537C316AD16F17805A81F29329879A94E96157E\
         4B7447F7D59603B21BD896CC47B7CD4E232322EB9C5D2215696BCFFCA3A04EFCC4C5D9CC39AC9A6E8700D38C244B\
         0169E7FA1FE81B4B10365E74E6A1F7F756D11ACDC84043F81006D62995376C22535958FEB53F78117EE0F61C4C86\
         2640D06DC57A2B8BE62A41A642AF3BC63F6BAC98BBBBFF70570F37B8F8D9572F2735657A6C98F96CAF57A8498687\
         20B2640B8BB2732237A1F984C18872D10289CE43C952C9257E06529AEB76AFD127B17596FD25C5216C9CABD9B18E\
         FC50E87BBB04568BB7D5C4E9288C006483AF5912E19108573700BD10CD77224B80659EA75AA74270B33AC4008B73\
         8BFEE271E78658C8742FF13C96AD0781A03C7576CA26DD58B52980BA58C0505E446AFA140CDCEA0490DB1F9B1881\
         5D4314B2459CACC562441C91F4084E5426C88E632CF7482E79907911D06473260835D7B85E7856A829AEA0381707\
         B939CE86882CC09C4448C6AE94A9C303107C5667EEFB8DF7763CC21189A3C590C40AA51F491503A7935EC08F4FC3\
         00CBE607ED8C9100C29FBF45584B13C8D780069337AEC76C36CEB70373E2AB6E7B934B466F53FB32EAF040055496\
         B8540E23A2A277E534468608D5EC0F8D38CEA5BBB806C1BF4F164F6AC826FE733F95461E29DCC11200C0AADA1B83\
         32023EAB329718CE25CC0A09555903F3578BBC863B1752CA94365DA556DF54C3B7E05CBB7115FBC1B6C57A172C31\
         B9906560C8FB54F3C563A2256CC073243B8179B4A28D60E086CF51082EE429272996F0AABE03BA0EAFD3C8E7D954\
         BD0933E2F60ED0C32CEDE7B820A28E48F3CA3C40913CCCAE2337ABFC59843F08C9863325D65A4E9E15C1F46172B1\
         18B2B5EB0F1D5158A00134F27B085488C3A0621FE4E5678698250FB74EE5152E3E35A66544A05D279EA99131FBC1\
         5165060B90F88EEB7B20892A4DE4CB1683495BD7DA037966B47CC040F1764C5DEB06B5499D4267391CEBBB47F734\
         D8539E39528436A1858182854BF20B1F93279AFB706464C65CCC5AE099B37CC03556C26ABF4C3F8B9BA3A9367072\
         11A49A59B268F5284F7970C77612719450377417428C4BA47C9CA115CF95304C4759C5D8859B44985C06A6C92468\
         9237BA320D610960D61C53E85431789E67A40113F167FF93429C264F6CABC95448C903437D39A6577BE0CF001285\
         2AA476351A9046A110A1A625A3D74C910B78BCE9CFCA735E4F91B8A4C57DBE489E849446098AACF73070AEE638FC\
         C8896473D3C159D3AFB4B687B40DFBF371A9C2644B605187B71A14BC4C8678FE8247";

    let mut d = [0u8; 32];
    let mut z = [0u8; 32];
    ic_core::codec::hex_decode(D, &mut d)?;
    ic_core::codec::hex_decode(Z, &mut z)?;

    let mut ek = [0u8; ic_mlkem::kem::ENCAPS_KEY_LEN];
    let mut dk = [0u8; ic_mlkem::kem::DECAPS_KEY_LEN];
    ic_mlkem::MlKem768::keygen_deterministic(&d, &z, &mut ek, &mut dk);

    let mut want = [0u8; ic_mlkem::kem::ENCAPS_KEY_LEN];
    ic_core::codec::hex_decode(EK, &mut want)?;
    ic_core::ensure!(
        ic_core::ct::verify(&want, &ek),
        SelfTestFailed,
        "ml-kem-768"
    );
    Ok(())
}

/// ML-KEM-512 known-answer test: ACVP ML-KEM-keyGen-FIPS203, tcId 1.
///
/// The same construction as [`ml_kem_768_self_test`], for the parameter set
/// that shares ML-KEM-768's code: the parameters are what differ, and key
/// generation is where they all take effect.
///
/// Taken from usnistgov/ACVP-Server at 975de31eb83d. The same case is in
/// testvectors/ml-kem-512-keygen.json, where the full set of 25 is checked.
fn ml_kem_512_self_test() -> Result<()> {
    const D: &[u8] = b"\
         47B893474672BA92E4B12EE44FB32953AF8E8503B5FB471D1614FB8A021A660A";
    const Z: &[u8] = b"\
         1F8CB39E9E30BC458A0DC5408884B1187FB217018DF760FA57317703B844A0A9";
    const EK: &[u8] = b"\
         28266A088B3482439BCA01AFB7CA5C6136A979B5159985A9484B36B679A5F7B9819EB63577891F7BB9CB98413C\
         CC434ADC79A16D6AB3076569CE6291C59B5D64612A7FB0C15013200BC8BEBB03A570174B5E4363AED86EB02A22\
         0D281FB5457F0A549FC5051D49A6B2015259A2C3084F405E1769952260675586A584904059275A265234EF3ABF\
         88C171A80898FC783358BBC9803C8789027D917C9EBACBC568CC18DE84C85454B94249586C0C6E2B8A16FA789C\
         51212DD1728EE9B8C6C40528BF93826FA82368419623032AF27B5694305816811D3CA85805100E9C1A9621E508\
         9E54CB47F5A8FEA0B49EF81C6B5187F48924C7947D6B61697A4A8A18452EF803336AD4BE503275BCACC03C1814\
         05F7B1DC9B47FB169EB37BBE27E29C763A4E52B9A42520388CF09B8EDBCDF41CCF6537190E6156C37CC1AAC63C\
         0F90CE78D0B9B190C548D71B6F26CC8F585EA14004B5B30AAA100B2ADC1263828833B24E46163B41446F98C882\
         092A39941867B80632E2097674A793935227DB0B8577E03A69C50A514C7473C892E3FBA7C4316BDABC952A7064\
         4176687D4191323BAD93D85A3CA250868C0747E6C44F6126C874AFBEC0BDD4503CB2C59A69816E7D4109941467\
         579A1FFE6A4F50FA379051729DAB6E2F61432F15BE67D667C7CC1054742B2B953078A5CF88D9133087309D88C6\
         1DA240D99C59137329907B47865321ECD5564E987333B4CB607B0AFCA86769DC95B2F921357213FCB80C3B1529\
         18E9BAB2228C0A1B77897AC68CE55088165F87F397DA9790873B62C5383C0CCC370F0267CBE195651CCF336182\
         C22AC3924B76C9E779B7A271D166B6D24B84242B7E73CC723F764039F6C851744034C3304DB0C091A5764FDC9D\
         593556FF734B82A87CCBC38CA99564D988BBD2D1BF071BB160722D365104FB27610651A8ED817F2742A6B5A127\
         3A61ACAF4460B0AB1456A9922351400A1C7D95D856D6E3370622C9C4164BC6B401435624A98B95CAEB274F34CE\
         92038D785068CDD8CF44C38D84ACB2C466A2756C870EE78C26E738CC451002304EB8C90AB24B6463EB124D779F\
         937A2E3692611D2E34D57B36CC4B2CD3B31FF485C6684D408B972E0D5CA7D2224AAE4E";

    let mut d = [0u8; 32];
    let mut z = [0u8; 32];
    ic_core::codec::hex_decode(D, &mut d)?;
    ic_core::codec::hex_decode(Z, &mut z)?;

    let mut ek = [0u8; ic_mlkem::kem512::ENCAPS_KEY_LEN];
    let mut dk = [0u8; ic_mlkem::kem512::DECAPS_KEY_LEN];
    ic_mlkem::MlKem512::keygen_deterministic(&d, &z, &mut ek, &mut dk);

    let mut want = [0u8; ic_mlkem::kem512::ENCAPS_KEY_LEN];
    ic_core::codec::hex_decode(EK, &mut want)?;
    ic_core::ensure!(
        ic_core::ct::verify(&want, &ek),
        SelfTestFailed,
        "ml-kem-512"
    );
    Ok(())
}

/// ML-KEM-1024 known-answer test: ACVP ML-KEM-keyGen-FIPS203, tcId 51.
///
/// The same construction as [`ml_kem_768_self_test`], for the parameter set
/// that shares ML-KEM-768's code: the parameters are what differ, and key
/// generation is where they all take effect.
///
/// Taken from usnistgov/ACVP-Server at 975de31eb83d. The same case is in
/// testvectors/ml-kem-1024-keygen.json, where the full set of 25 is checked.
fn ml_kem_1024_self_test() -> Result<()> {
    const D: &[u8] = b"\
         F3A706FAF090C03DB506863AB0B20BD8A1627956318E88C67EB875E8E7266009";
    const Z: &[u8] = b"\
         35D2BC43DD1CC879F765BF2A0C5E297889DDE910E57E2BB0EAE417B90AB7A275";
    const EK: &[u8] = b"\
         8D0923CA8A2DA2B4146EC25321122B8A5AA8AFE0C03415273008A46EE83031E98AAAA125ABC75D3B30322560C1\
         97E75DD0E48A348099F7B2144D7B8A8660A4A97BCF19C0583BD9BB2123033CD7BB5A14B08B817831A673A28170\
         F5F6443C0551913A327CBA18C3A053C4040250403B70AB9588832403AA0FC37665E04980FE1602E7D2715D9CBC\
         00515DF432A4F5B32B3BC92AE3F31700166D498123E94576509B712B18491B1435EE7AB7AEB1AD30D72348C3CC\
         083ABE24A8B12097BF32F792476288EECC3BF630ADCDAC6ACA7950D9839501A448500742BAE37F109203A809B2\
         B960A307E25347A32C3EAB79288173A878789B296E9E8C1C28C5BB3AC472601C9765F7B77225A810C7B85370BE\
         F4A5B079D2015ADA54236B8F33840675F9B2EB427A1B5974CD5C61B24010886C5A7BDA5BBED974AF7217F3338A\
         D719CB308A8BCB1B6D6ED2A1643736C29095E8A8452A3A36C7BB5AE58CBFDC61529466A90F454ED6895B086108\
         3DD1371999B2F559A3A487CF59A074FB49215EA6A6BE656F9AF17B121A2447CB7985590E9738842B899BA57AC3\
         11810AE2D9794F37483DD6BCCB64AF6D56588AE94665961C025C3AA2861974C236BCA4BD8FF5509F7AB774593E\
         7C5549E57C2F18D15C0515094AD9A0DFAA0601E524F8231156B627BB25A0DAE04DACD0A66C041CEF400583FC13\
         BAE640291A39A5C5CA8BCA1AD5C683CDD8290891A76940817DD8C9F52678780548E37A05806600801426DBB950\
         C3B2BA34E24CC77864DD91B39F1408C716A69DF63342854E50A245FB50977B9410DED2C93F86B1F9D5A78B87BF\
         81E51CA620A7E8566B19AB700964A40E3266415228D432156E5CBDF52364A90483A55C39B3FB16FC7465A3F8AC\
         801B70B9FB28B583444BA5C1A73722D417A9D6D9B7DEB08BC6B330FF27CF61AB8831E27758C64AF3B12150CB7B\
         33ABC29858106D63686D8762459ABF9413850AE53ED6313F76F83D0FB8AB34374E7DF693E4A1B3E5A8AD0CE820\
         AFE1CF401ACDE650A8101B0946022D52178E19613C42B88B07CC04EAA81DFB28AC9DC076236B67219A30F8F945\
         DD57BD2F335C52D59372308D38993467DB53DA3382B74867B616481BD0091A2232C1116DC88A589DB9107224A6\
         81008C67C589186A6929549BEEF92253DB02B0C8AA9F9C875A670266C72BCBDB4F5625043703C1A0457395832E\
         4C335180462ED2220C59E7361903C107D85457F6CD82EB820D0855D97675C2E0151CDB73C2885DDB7849D74541\
         580124E890116A65BC068093B57914E20C937C60A3EB25576F1A976A9583839B672144CD4A45C3477A45C29B4E\
         0BC2BDBD206585C9B7A7741C8B6B5793A92797A15AE7A5B73A74B2971463634BA52AA792AF05530730B6D0A89A\
         346156B733677932BD36593A7496130CC458DCC5CA987C21960604EC8A8C5396056680CBF3F1AAC4F401AA5029\
         FB2150434BB4706C31A2D54E4297939FA7C9C6F85700613CEB65C7F03AC56EB86E2D27CCC6DCB7B9394DCDB942\
         FF222D86958A996C0CB6A8A44F97A70441C95FA71250116EEC20863C0B5A643458788AB001F8869D909922F51E\
         E547A1E889255B3A0599C65842E5AB8D73872F053BC62392EA53896D328102D460BF1609583C22C3B43780EC6D\
         AD0319EB4A5A65B4756C3CB40EAA935183BF8BD46ABE76BA46E199103A5313C3235F49C915E097BCA804DE6807\
         81D8365731BEAC6789A9203FB8787C4C070E00A13A6722A66A28236DB179825653D33CCF898B72C6B8450D97AF\
         D3276BB13340519CBEDA708D12A858F54C49F4547195B7788A9150B2649E36AA394121926D568A488B16D3557B\
         2A32AF57D11FC3373F80A28C0723273D362502E7C428AB44D3CBABF9EA585FD1BD0C9846556A1E196B78CF9515\
         92984A0A8487A78C2317D7ACA4118E1049750A0788F0D66AD9E48E34731130ABA0B427360A856D96D80B3F028F\
         DD3ABA9035C10106BA1C0934BED36C6D7C7434249654EA89FC22137F4AB903653B75FB25B6F01635E6CC7D39CF\
         1508690562826B49B6FFC59E0DD35022E541F8BA0D304AA5B4E20606907C424395666C54ABC2B8FB009847C863\
         17685000C231215C8C15945860F6A85DDB98A8C3A527F2749D3C027E694E8F0B0F0FA454913AADB635AADD452F\
         7128BF7752569669A8B93290EB92E78F6ADFF23E89F57F3890753B51F12F3F3A8A654E677847";

    let mut d = [0u8; 32];
    let mut z = [0u8; 32];
    ic_core::codec::hex_decode(D, &mut d)?;
    ic_core::codec::hex_decode(Z, &mut z)?;

    let mut ek = [0u8; ic_mlkem::kem1024::ENCAPS_KEY_LEN];
    let mut dk = [0u8; ic_mlkem::kem1024::DECAPS_KEY_LEN];
    ic_mlkem::MlKem1024::keygen_deterministic(&d, &z, &mut ek, &mut dk);

    let mut want = [0u8; ic_mlkem::kem1024::ENCAPS_KEY_LEN];
    ic_core::codec::hex_decode(EK, &mut want)?;
    ic_core::ensure!(
        ic_core::ct::verify(&want, &ek),
        SelfTestFailed,
        "ml-kem-1024"
    );
    Ok(())
}

/// ML-DSA-44 known-answer test: ACVP ML-DSA-keyGen-FIPS204, tcId 1.
///
/// The same construction as [`ml_dsa_65_self_test`], for the parameter set
/// that shares ML-DSA-65's code: key generation is deterministic in the seed
/// and pins every parameter-dependent layer at once.
///
/// Taken from usnistgov/ACVP-Server at 975de31eb83d. The same case is in
/// testvectors/ml-dsa-44-keygen.json, where the full set of 25 is checked.
fn ml_dsa_44_self_test() -> Result<()> {
    const SEED: &[u8] = b"\
         7194B13C95231010AFD2C909992BD2003BA6F437C3886BDBE3F6B867A14BA161";
    const PK: &[u8] = b"\
         0B89806F0EEC39F2891116152ED4319D4260DFB8AC0710765BD497E6E1DE17783CF81E435A412EABEF5DB3AF5D\
         15867BBB4C60F8CF98BA31BAD6D41A5F8EB0C11B632C3F19D844A223C353BD182883DCF13B5C97823D0C0E6902\
         DB25AD8D344A37F59F4AFACA5BC8874792DA1E6A3EAE742AB7034B20A4AB75A93BCA4B68002DD242CED348920B\
         7E5ABF645A0E2E79617BCB3EE7BA972B3E718D3EFFC59B1869814BA3F526927477B12BF25CBAD8B04B09905FDA\
         D3820715A8B9A905DE1CD65EFF6B0B0886305EFB6CFEEC9E90B5EF9A5AAEC45C753298E8DF9B017CE0FEC9B743\
         1B20775CE8CB11F1F42D1D9FE936D0803196E71ADDC26CC430CC3B69760C7CCAFAB7651E21BAA28F92BBFF1C4A\
         6EEF156D6F08F80B5E3B6FC943E6E984378B90888D09A6EA38B0BA86A3446211452E076DC9F65620014205D527\
         1C7A44FEC3CC5375EB246AFFC11B26CAFB8B96CEE3A68E31642E3D69B9130795F25ED818EBB211CD8BE648ADB5\
         C8A120C8186017727FBCAB31C7425C08FE9195DE6BDBADA5778D727EE5CDE0674FACB7AB81786357B529C71DDB\
         24DF770E8E95E5F3112BD297B352CB91B08ED1097A98E87BD7CE4235B8DD42292CD4C59D87C1F0FF00734AA22D\
         7CAE4361ADC47742C897601048526702538828BA3C3A959990C0E99463FD22417E147FF2DAA74C0C8D3A06E970\
         3A2E160590086DB8011A3D9CEC5AE6348706F87CB2379632CE56E660A0BA1B30E3846C5B5C6C0339DD993E543A\
         5322AF5A11FC7040A2DF23A0B43E882D7A0FF4431A723BBB918AFF7F14BC045CBE94BCAB27AE3109147B588665\
         EF486006562B1297016EFDE787B46237060EE431E0F011166F916AA0789A7647103B7400A1CBCF0E22BD7B6DD2\
         BB3EC51EC98F0EC6A5BAA4CDC83F993D302F8FA849F2046B78AA32F0B3751885ECB941799E250E6546DCA5C20C\
         24845190F239EDC20DDA77353D555DE61509CA6D3C6DC3195BBC6F1703CB03EAD5E7FCBCF5D196E9AB71522408\
         E11D6337C74F9A31EB22AD084A19132BF72E7076A9743ED070ABA78789791824E050CD27694C2648263D120081\
         1FA1B81A00B8FC09CB7A338795E54F6598D7753395F05C60E6EBA9630912B7AA8CAAB3017565DEF72C7929F4E7\
         736C2B8043FEB448801E2DED704E834294B69F6A109C0968214FDC5C3FF0D1B1555D617E16DF61829231962C59\
         B22A10FE400F8B8CB2A3F19FB4B2E8D087F22687506E7F0D061857D1C1789C7F55B899FF4B322982D64BD0AA75\
         1D5BEE320B135C7F5DDCD5E6245B57DD22F44042F2BA6DE942365A59FD0C6B0F20C07B71277C6EE7DD9D225032\
         605AED1D3CF8242EB85C33A0AFC3AB42764088D8F4A80FAF804CD84360B2055181E58A0B5AD4C367ABC6679820\
         45AD0FD7E048AF8C326D5DB60233302B107E515B15B0F90E5F348C54192B559B4C0A86CDF0719387EA3FF6B1D6\
         0B324A98963C56927E2B8DD5A39AC792AEB85EBDBD8DC34B395C2B4DEF4D853AC21A7660348EA8C96C943DE0BA\
         FF3AA6849179E5EF2BAA1731C81C605BEC3860FC4A6A08CC9F75BDE9533511780FF1E0B01D34C0DC3EB80A7E2F\
         52A7A4B815DDA98EA775DFE0C5B3D419B05934DDA05A9616C0978CC99CC8D7B68227BD846419D765956C3D7AA8\
         11CE60AF22DF322FEF0DCE38C4278E0237F1D29EF139E201C8ECB4D36E79910D06C5CA4CAA8C2886B96DE6EDD4\
         0D2499E30EB942F22BEBF6ED5C8E37DF9557E74D67DC467BAAFA68F1CE37C8BD9B3A4F9DE71670128125AA16AC\
         A7232239575E1C6819C820AD16832F23647DD53C5740A8552F86901AA4F883EFD5A3EFD7C3BF458C5122712D44\
         BE43306C9B8264";

    let mut seed = [0u8; 32];
    ic_core::codec::hex_decode(SEED, &mut seed)?;

    let mut pk = [0u8; ic_mldsa::sign44::PUBLIC_KEY_LEN];
    let mut sk = [0u8; ic_mldsa::sign44::SECRET_KEY_LEN];
    ic_core::ensure!(
        ic_mldsa::sign44::keygen(&seed, &mut pk, &mut sk),
        SelfTestFailed,
        "ml-dsa-44 pairwise consistency"
    );

    let mut want = [0u8; ic_mldsa::sign44::PUBLIC_KEY_LEN];
    ic_core::codec::hex_decode(PK, &mut want)?;
    ic_core::ensure!(ic_core::ct::verify(&want, &pk), SelfTestFailed, "ml-dsa-44");
    Ok(())
}

/// ML-DSA-87 known-answer test: ACVP ML-DSA-keyGen-FIPS204, tcId 51.
///
/// The same construction as [`ml_dsa_65_self_test`], for the parameter set
/// that shares ML-DSA-65's code: key generation is deterministic in the seed
/// and pins every parameter-dependent layer at once.
///
/// Taken from usnistgov/ACVP-Server at 975de31eb83d. The same case is in
/// testvectors/ml-dsa-87-keygen.json, where the full set of 25 is checked.
fn ml_dsa_87_self_test() -> Result<()> {
    const SEED: &[u8] = b"\
         A16F5B0796703E2D1A0140A35CBF36EFABE70E752BA59B6A9A0E9C4B05302F73";
    const PK: &[u8] = b"\
         A5787E8044248F3F85AAC54E9469FC98F1B1138CC127B120F9946C80B96E3D89CCFE38C995645D4B6A559EACB2\
         AFB81621D765C6E42E73031D44CBE74D322C7B16249576EB4C500253538D1A2C6B408E681B93B9014E3147DFBE\
         CF9D9858F7E8635F8598BA6847127D216A888FFB1636CC761616A0389C39A4245695DDE0C86CCF8A3BC5A50EA6\
         FDBCC0A34457D4DEFE35F775C5993685AEF2237C31912A619FF804AFE8AC3418C13502820AEE5249D6E577EE0B\
         2A5E3E8DA2DD30F514A076B50556D7581BA1F9B2E4671756A63065C20EBDA6EE2C33C9D97AB14C5F2204FC5359\
         ADB2BDAA3AAB7AE1DACFF18A67D801BCB8F054BBC444F0FD0001A7908EBDCDF2B84F3C026EEC1282498D31AC33\
         AE6A309ACAB17B70DC9F0EFBE52648D1AD2A4CD5964DC619B66CDC9D35EDA7A3DC21C729B9929024DB8B852DFD\
         F102A086845702FD249EE43B54D2D033ABA95110C4F0A66EEAEE78F3C41D5D792A37D1D2299252A5498A44CA35\
         4F6F37FDC2F3B72B1A8378A5BA8B4997556E5A6F4125AD946BD4FC402C4320B27111BC204B8B5448F43F7E77A8\
         166A48137D85584BEFE2D9C85CCCD9BBF3F8A4E05930180AFDD697DA82ED9F1069150FFC76578C941CDBCC5BD2\
         ECB7D6ABF9E68327DF51C26C8B42CB1DD8BDA98A82C4C6BA6A991E651BDFF68F0A62D5DBFEA020D4303E0C53D4\
         74CB11D553C5BEE1156917D72AC2A6CCC4EC1C775D41EE660E2485A45AF5A7CA083DDDCC3EE4FFFC5E77BA97CC\
         4473303C77D8B6FDB35E2A20627BEBBE327DD2D1AD1F880CA8EAE1E0067A9093929E5AB18D406A518EDD8C1E0F\
         0AB07736F55FCECF4A3B2ADCE1CE3E080B58DDF85A2262D0803A7E5B4E485E642BA533E2EC7A43F9E8DB20F752\
         92ADAC704395469408C15641A9C28B83E8C1C799FAE0652F51369978F4C089FE15DD78C5F560CD28F5F75FE0A3\
         9A60A61AEF6C7D802141E9809E7ACA68A38BE9BDF5312258704F8B11AF4262220CB55641FE95DF83EC9F786D6E\
         69202C91EC4CAA4E38A21C3CC609C28B8F65552FE8334850858BBB30B837D874867EAD330A1F5B4D7F6BEC4748\
         BE54A782D5B21A192BC00A7F2240FBD900460785D1971A94C587493D21CDA249676EDAC6C865147E269488B9CA\
         78FAEFDC778FF60E79735DD5539879182424B054FAE8A9E153BFFD6957C533AEDC105E43AD7626312C8D229327\
         D3E72AA9644BF3E2C9A08ABF807CF3A472C7DAF0AC4290A9E8F88D07AE8FEDB8A4B218C3EBBDBE53882781F2DE\
         034B17FEFE69302B4975CF43E03645DC53BD355AF988B3A3D2431BF9D9A865750051EED7BAEFD1BAD4939C7EC2\
         93509A5851A145F79DCBEEFD195571AC2172AC6036812B4DC8040D186B8984CF9DC24F8F765166C6B2E8389DD2\
         4ED63CEE951442861669BDA0622BD90B041DC477C01A0D95D547E07A892CE1F26275ABC6F97702E03B776E2CA7\
         1E3D0EBB88D1ADF591122E6F0EC95A6CFBB976AE64BD0C7F074CB6E78E644DEE8200E2D626435907B9134000DB\
         C3B50271F5A8F254D2CF02DA039D458E80FA13A33567AA9B374B47B799D0FF1A14CA92A50EFA192EA1641FE29A\
         380E11386528B7248D6DE6AA90E1C9744713B768264B72A13CCAA94F3E19ADA5129E0D8155EC1B267E2CDC7F0E\
         7A08F203D9A18F8C8D18529709EF746A21D5FEC36EB547A2FD4490092AD0F06C55EE0A1CB104E2C3C3CF2BCBCB\
         FFEAEC744A13E37310962CE40E072E7ECAE223943A03002077D3D96C7B4C3FB1E2C9EE9C5222A63252F26372BC\
         2BD94507CE5728CEB7A0AA33527E0662B4561D1BD255806450772EABB7ED40F787A2E3C664FA6BC3BE9BCD84FC\
         7B42F16F94CC56CFB67297E475177E19E51010CFB74BA996BA1C3D793EA010C99901E2223B375E364BA193772B\
         329D5D05AED959EBB924B698F0657AF43EEE8E0D54D15C93511209AAA9E10251BF81AD8B467D8FAEE2A440782C\
         372F55A62CFEF408803E4B3BD8EFB94061EAB525BD31957779B89EB1C75AB97F278B3EAF99A05686E04873D7A6\
         85868D1C0F4510ADAB0B267FE4D3CB70C35B295AFC671B60C6575B60EEB99756E7B204A24D7095DF277BE18668\
         E0F1AA5621D16F204575F76C3B13385BAF61AFF7F36D56111FD88FF093BEC4FFC26BA63720660B5BD209A9C14C\
         0AC6B4E08B38FF580C18E39A22A9AC36912892537B0FD42800445DBEF1A03D2D8624C1B125519927C282EEFAC4\
         AFC16128B07456FBC99D34C783AE08EBB0C46915971429FE64E448F1678BF76C7C20F91AD80E213E39AD89962A\
         EA44E06EAB351C9B3A5859D5A884DE0CD767260CB60A96F508C62B731047CB1F3CA6AE28742771F4EC3BE45DF5\
         00F0132B6E947D2468AAB9410BC1F581328471B3E53E8E29A0794F4EA8BDF9FDB3922CECBD2AAAF75A2AF4C7CE\
         BA03382332D39DFB770559789708930E4C77966C7364E2A4D762C122BE3FCBD37276EA6194071BB7C18E262752\
         4F3AB2BE7C0C6E59F62D1F075E1951DD3352F6CA9762F243F6691FE6A9DCE4278B178F688E433B990272000F23\
         C92F74A1CFF1429BDF1C3FE1B9AA1C0E7A58ABFFBB54D3F38ED93B11FB12233CFF48C812A227747849012F7BB8\
         5529D87459E11DCA9F7A9C3242054DB6BB93B48A47D69BA791B2A5D694A8776B22B8881BB2D192AB0A45AEC71A\
         7171F844E3B1C4149D118EFA899E88D96A296D5EB811AF923AFD1A92E0C71464B90C8E5EC24954FE8C9BFB518A\
         308B3D301D8D6C62E5AD40F63BCE24699AF0BBD2E48FD9AA7C3A1C597731700E3D86E16AD36A67BC031BF381B8\
         2CF40B1B235F51727913BBC311A186FDC23EE267739740CC57C36BE05F9331EA40279C34C44FB8FDFCC7E9CDA5\
         4C394CEF9C17F8529A56E3BCCBA327CABD07F5F9C567B70DFBD9D7139E39B7E1A493482321B11C881BA9D44CBA\
         BEA64F1AF18C18B3B5F98FF4A95FD907E112AED857B033BB7E0FF9466CF5FC691CCC1142BFB8CE81BAD7DB5544\
         09B79E23D0A41063857E4AA05583525E69EDAA017F6A7FA96C25A38E7A7D01E22F96ADBB683B4EB8A487202426\
         D68D297B30BE0A803D4FCA1E037DB3BD63A2F06EFD68BD4D7BEAD8338D36AC1425163B3C739B86AC9D967ED54D\
         E24CA58BC129CFF73585B667DC33F32BC4A4D9E106076849BC2574F0E5AB2C0B5CBDBCA59BB644BC86F3339B23\
         B3B12959FC7887F7291136343E54F4A56C344DC5BE641DBCE62AED4D4BB958C4D54D7196DB4ACB8A1F43F88CDB\
         B758546F44C59293501E0569F00B97FC244507C248031D07EE4DBB6A97270B772791E758E582989D93124AB82F\
         15A9DCA469C1A0E98CC75FF683430036F16B4E94E94DECA06EBE7FE2B8E9C0A690AAD7A91877799FCF24CE2758\
         44A63E68F1A5C799BC83C7F5384CD9322E20B619D39D0031482FFED8224F6C522C8533CB29C04AF154D920D747\
         D81616EA219E358385AA9FDB8E94A7EE5B53F2CC31B3A7BAC787E54AB9536FC42A3E369043C6F5C11D0F7D4528\
         52C3FB3F1845942186044385FB9E482962B1DAEBD2B3DF125D1A61843F71A272E3A1D97AAB97DE5831C56D16A6\
         A6620F8C6CD0F4F1E41AFE6895BA3664D23A03EAB3531126E87335F4BCBBF2E39C47B5A58BA15066F79717D829\
         6667553ECD0991F14D42F8934D753929F146E4B58D00A3E0139D66";

    let mut seed = [0u8; 32];
    ic_core::codec::hex_decode(SEED, &mut seed)?;

    let mut pk = [0u8; ic_mldsa::sign87::PUBLIC_KEY_LEN];
    let mut sk = [0u8; ic_mldsa::sign87::SECRET_KEY_LEN];
    ic_core::ensure!(
        ic_mldsa::sign87::keygen(&seed, &mut pk, &mut sk),
        SelfTestFailed,
        "ml-dsa-87 pairwise consistency"
    );

    let mut want = [0u8; ic_mldsa::sign87::PUBLIC_KEY_LEN];
    ic_core::codec::hex_decode(PK, &mut want)?;
    ic_core::ensure!(ic_core::ct::verify(&want, &pk), SelfTestFailed, "ml-dsa-87");
    Ok(())
}

/// ML-DSA-65 known-answer test: ACVP ML-DSA-keyGen-FIPS204, tcId 26.
///
/// As with ML-KEM, key generation is deterministic in the seed and pins the
/// samplers, the NTT, `Power2Round` and the key encoding in one case. Only the
/// verification key is compared, for the same reason.
///
/// `keygen` also runs its own pairwise consistency check and returns false if
/// that fails, so this asserts on the return value as well as on the bytes.
///
/// Taken from usnistgov/ACVP-Server at 975de31eb83d. The same case is in
/// testvectors/ml-dsa-65-keygen.json, where the full set of 25 is checked.
fn ml_dsa_65_self_test() -> Result<()> {
    const SEED: &[u8] = b"\
         A991FD42B071D49C48AE3E75C647459E0DAAD1E1BA356A04801912D3294BCFF8";
    const PK: &[u8] = b"\
         36DB0B5DCE98BD190CB139E80B71B49C7D7040B71C5A1F3412C46BDE939192B1B57CCB88AC2714C1240CB0EB62C6\
         89E031AEA3D9F3EB3ED7BFA45931D288DCAE3413199B31A7032560DCE8A61E195D13A1440615C2F3AA7DD28C5B1B\
         742BFA400052186721F13D3DF9DCFAEE348B10D66913C7148913E085E1A4A03C659398DADC6A8E0E0C1A7F9F44D3\
         0436DB90FD65A6AB8F36137338255653BAAE8DA21526A333426DBD9F76CCE0F43212643E854D772018B35CE726BC\
         AAA5AB0651BAF8C122E13929BB35B6E4963DF2595FDC7237CDAA7234BF776B07F353CCDBA12AD3E025138E3492D7\
         F8E929DB55DC23E23075F66D57A10492E6A10AE7B758ACC2291CA18BA1CA07A5B574AB6D8AAC18B9524990AD2F11\
         0225B7D82F696300A660A166AD35B3C57ECBAB77117C79656FA8AE2A19A7DEFB2AFD2AF54683D043BE0F933B8EAE\
         0D591448ED55D00068CD9FE10B067FCFAAC53AEDB1E9B667E36C4E30231F85C7AA0A474AF2FA4776226F4479555E\
         155528D78B98183CBDF7FAE4E7301140F163EB71E991D15FAD4A0D2F25A5A62FA2E9BCC823CC2927662E40C53821\
         3DED9E2DF508E911E4924E507A50861FBB050EDBBF56D937206F8FBC6F4CEAD4CD10D06B73AADCD4AA39703A7A2B\
         FFAE68B7BAA47341B699DA9F3B167D4D90EFEE0A07EE3529A3B5E8648B9CB07EE973E1D8DCCF1D16E95092C4A018\
         4CCB4902D6086D9F444ACA5FA45F43CA91B351E82585989FFCBD6D2C3471D6B8593AA46F29D0DD9B44E8AA4D8F9A\
         0BC886BB7982C56AAB11E23BFDBD8BC674732FADACACAE25FA416B2D0CC7743827293336507DA4B14C1F0AA2E929\
         AF975466DADC89A016F33A0CCA2D5C08114CF04B02358805A772536432C44DBE9886130D2D3A0FFA0E175875A220\
         7686F5E562B879EB2957573AB706B942468C20CC69BC566D29D9F151F3CFAE71CC97CE4A30722D4679FC1C089B50\
         09935931EE60AAC5496B0FD5F24E514C0E20FA1DCC7729184A50FC85FAD1D2F32F715FBF55666E49F5A19761F2DD\
         1AA5D1A33C7916EB6A794981C0334176ABC493EF30D9EAEAAD42E705989DCFCDEB578529A700BD14076A348A2062\
         D6483CC63CD7F55136587AAC0E531A06EB2DE74E61CFCBBCE18F2ADA5A741F683BF101F71432EE659DD1508E0C8F\
         B2400E0CCBE435DA3466D543D3EF5BA369E125C0B84D855EFE6D4A22FF929A7A7A984E448D23871E09B88A0BC3F3\
         B7DA55DD2EDFB5A6DAA102819FF50CD4DCCD0A95D2F27354668065D4A56C31FB18B92B2A8DB2C6453BAA9333AEA6\
         EABB1BD6411D584DD5900262057A707F81CC5137DBDD9AC1079BB98DA78A8E4BD1B2E0546C2B3D956FCC280D37D8\
         55E31F1E4315B387A742280F057F3219EAE512884AE7EC4D2E3A72265B1D0163FBCBF616B2E289B0EAF9C63437D5\
         0B7B50CE408F5B4562F2ABF510C19F5E8A0ACE264DB6E0F2A69A7D0B4A5E62A2B964F08C8FFE9C295F5773BDD7FA\
         B054A13822D428FAE28AE5E4ADC9D9F6E4DFFC457A3E49F0BCF62B32961C4667B60960452AFD917FDD00D954FA30\
         C8533E5629F90AF85948DC1BAD889F91832DDF9B738254C9E7939726C37AB4557C2CE363C1391816C467537B471E\
         5985E8084C277B62BE514922D352E20689EABB3EB91C343F36E77B152D5E85AFD088F4D02E7024B248A7420F58C7\
         EBBEB480CAE39B56164F5ACD37A4F56B3DB6E1CC6B7C8C96CD3C44A69D9AC99175257BAB7FD83C5B574B5C9702C0\
         FD13A5B176C60F82D2DFFF50C2AF25D96E0F8D27EC818D499E479B9642AED4A4A0E6AF5F14CC5E1299EABAE055EF\
         3C763D1E350E2D76E92CEE47A4233368466A298AFB4CA108A325D2A4F8B79F21EE7349C1C186ECD7897F9886CF27\
         EC01B05388870484867F84BAE2C016D04A3762241907C4DE207798DD125A2CEBB6C2982F779E04117BDD65CD7FF0\
         361A59D3EC05F6D903B6D15554BEEFB6D40D96A0D4B37AE76C69C1B9592088B7DB878F95ABEDCB5FD5423ED93DF1\
         B27D01A4DC9F4438E7C55F35B0AEB7395B08E1ECBF15CB2B61D043C0454AEAEF2D487093FA0D7DE3FC6CAF084B6A\
         0F15A5CB05D9340D4E6763983DC45B7828539C77A60D5E081A03FE29949D916392B6D989B4C8C047E3635A76BA88\
         AC18A7A18CCFF5C7E06B02A43D2DFF169FA449739E382BD020E0963C14A9ACAE6B6561C722D2BDA183F33EE6A904\
         DF0207F5B098E56335CC063F9640C4997F593218D502F6B382354C73979E93C4B1B2471965FFA5A0DC8EE8ECA9F5\
         697E7EF08DC0EEFD9AD75CD4122194B450201DFD73CDA46A7B2478DF66129FBB9C75B774213F9615BD990F8D0750\
         1FED440FD25D6CB912B8ECFA678D887A4EE28677E6E0491D49EFC7A3B34B9815C5C22983DA280D0AFDE2324F5281\
         BC8B796DDACFD82723BBD9AA34B0C96075B36848591E47B80086897846FA76D092BC8BC6200837BFB5545039F860\
         2B7EA49F63C0C3B8317EEEB7612F8E818DDE09E43C7DA76FD2FF6847906A45DA3D993E8EAED9FB3B1E579D8CC690\
         0C89522AAEB0B4A80DA1E66AB8DFD62DFE4E4D77A3A77E5BD669207C70AA8537DD6D80A647B0420D79531A745605\
         2C3C989F0F08DE3D343C40067680B39ECE95A17AAC8A622D1D5D95B38CA0F11D94E5B0A7634EEF4055517ACE79F0\
         DF1D7C172E0246ABB2AB6B135EE1A38A3B84F86FD7C3CAF178CD4446D0B554256AD45C657E1192070ABA7DF480F4\
         89EBDF9753A79CCBC6AA893913C5F1271F1C6035";

    let mut seed = [0u8; 32];
    ic_core::codec::hex_decode(SEED, &mut seed)?;

    let mut pk = [0u8; ic_mldsa::sign::PUBLIC_KEY_LEN];
    let mut sk = [0u8; ic_mldsa::sign::SECRET_KEY_LEN];
    ic_core::ensure!(
        ic_mldsa::sign::keygen(&seed, &mut pk, &mut sk),
        SelfTestFailed,
        "ml-dsa-65 pairwise consistency"
    );

    let mut want = [0u8; ic_mldsa::sign::PUBLIC_KEY_LEN];
    ic_core::codec::hex_decode(PK, &mut want)?;
    ic_core::ensure!(ic_core::ct::verify(&want, &pk), SelfTestFailed, "ml-dsa-65");
    Ok(())
}

/// Argon2id known-answer test: RFC 9106 section 5.3.
fn argon2id_self_test() -> Result<()> {
    use ic_kdf::argon2::{argon2_full, Argon2Params, Variant};

    let params = Argon2Params {
        memory_kib: 32,
        passes: 3,
        lanes: 4,
    };
    let mut got = [0u8; 32];
    argon2_full(
        Variant::Argon2id,
        &params,
        &[0x01u8; 32],
        &[0x02u8; 16],
        &[0x03u8; 8],
        &[0x04u8; 12],
        &mut got,
    )?;
    let mut want = [0u8; 32];
    ic_core::codec::hex_decode(
        b"0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659",
        &mut want,
    )?;
    ic_core::ensure!(ic_core::ct::verify(&want, &got), SelfTestFailed, "argon2id");
    Ok(())
}

/// The number of known-answer tests in the suite.
pub const TEST_COUNT: usize = 70;

/// Run every known-answer test and summarize the results.
///
/// This never panics and never short-circuits: a failing algorithm must not
/// hide the status of the ones after it, because the report is what an operator
/// uses to decide whether the build is salvageable.
pub fn run_all_self_tests() -> SelfTestReport {
    let mut outcomes = [TestOutcome {
        algorithm: "",
        passed: false,
    }; TEST_COUNT];
    let mut passed = 0;
    let mut failed = 0;

    for (i, (name, test)) in CASTS.iter().enumerate() {
        let ok = test().is_ok();
        outcomes[i] = TestOutcome {
            algorithm: name,
            passed: ok,
        };
        if ok {
            passed += 1;
        } else {
            failed += 1;
        }
    }

    SelfTestReport {
        passed,
        failed,
        outcomes,
    }
}

/// Run the known-answer test for a single algorithm.
///
/// Returns [`ic_core::ErrorKind::Unsupported`] when the identifier has no
/// registered test.
pub fn run_self_test(algorithm_id: &str) -> Result<()> {
    match CASTS.iter().find(|(name, _)| *name == algorithm_id) {
        Some((_, test)) => test(),
        None => Err(ic_core::err!(
            Unsupported,
            "no known-answer test for this algorithm"
        )),
    }
}

/// The identifiers of every algorithm with a known-answer test.
pub fn tested_algorithms() -> impl Iterator<Item = &'static str> {
    CASTS.iter().map(|(name, _)| *name)
}

/// The pre-operational software integrity test.
///
/// # What this checks, and what it does not
///
/// A conforming integrity test computes an approved MAC or signature over the
/// module's *executable image* and compares it against a value embedded at
/// build time. Doing that requires a post-link step that patches the digest
/// into the binary, which is a property of the build system rather than the
/// source, and is listed as a pre-validation task in `FIPS.md`.
///
/// What runs here is the weaker check available to a pure-source library: an
/// HMAC over the self-test vector table, which detects a corrupted or partially
/// linked constant pool. It is a real check — flip a byte in any embedded
/// vector and it fails — but it is not an image integrity test, and this
/// documentation says so rather than letting the function's name imply more
/// than it delivers.
pub fn integrity_check() -> Result<()> {
    use ic_core::traits::Mac;

    let mut mac = ic_mac::HmacSha256::new(INTEGRITY_KEY)?;
    for (name, _) in CASTS {
        mac.update(name.as_bytes());
        mac.update(&[0]);
    }
    let tag = mac.finalize();

    let mut expected = [0u8; 32];
    ic_core::codec::hex_decode(INTEGRITY_TAG.as_bytes(), &mut expected)?;
    ic_core::ensure!(
        ic_core::ct::verify(&expected, tag.as_ref()),
        SelfTestFailed,
        "module integrity check failed"
    );
    Ok(())
}

/// The domain separator for the integrity tag.
///
/// Named rather than inlined so the operational path and the test that
/// regenerates the tag cannot drift apart, which would leave the constant
/// correct for a key nothing actually uses.
const INTEGRITY_KEY: &[u8] = b"IronCrypto/integrity/v1";

/// The expected integrity tag over the CAST table.
const INTEGRITY_TAG: &str = "4406d3f02daeae032d9da4a755d0a58585e8fa49e8618556d5e8b15d51ecfd81";

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

    #[test]
    fn table_length_matches_the_declared_count() {
        assert_eq!(
            CASTS.len(),
            TEST_COUNT,
            "update TEST_COUNT when adding a CAST"
        );
    }

    #[test]
    fn every_test_passes() {
        let report = run_all_self_tests();
        let names: std::vec::Vec<_> = report.failures().map(|o| o.algorithm).collect();
        assert_eq!(report.failed, 0, "failing self-tests: {names:?}");
        assert_eq!(report.passed, TEST_COUNT);
        assert!(report.all_passed());
    }

    #[test]
    fn every_available_ontology_entry_has_a_cast() {
        for e in ic_ontology::all()
            .iter()
            .filter(|e| e.status == ic_ontology::ImplStatus::Available)
        {
            // Modes are exercised through the AEAD and block-cipher tests, and
            // the generic KDFs through their SHA-256 instantiation.
            let exempt = matches!(
                e.id,
                "aes-cbc"
                    | "aes-ctr"
                    | "hkdf-sha2-384"
                    | "hkdf-sha2-512"
                    | "sp800-108-counter-hmac-sha2-256"
                    | "pbkdf2-hmac-sha2-256"
                    | "pbkdf2-hmac-sha2-512"
                    | "hmac-drbg-sha2-512"
            );
            if exempt {
                continue;
            }
            assert!(
                tested_algorithms().any(|t| t == e.id),
                "{} is available but has no known-answer test",
                e.id
            );
        }
    }

    /// Each CAST must call the algorithm it is filed under.
    ///
    /// The two coverage tests either side of this one check that the table and
    /// the ontology list the same algorithms. Neither looks at the function.
    /// `("sha2-224", Sha256::self_test)` passes both, and then SHA-224 can be
    /// broken in any way at all while the report says it passed -- which is
    /// precisely what a self-test exists to prevent, so it is worth one more
    /// test to rule out.
    ///
    /// The ontology records each entry's Rust path for its own reasons, which
    /// makes it a usable second opinion on what a CAST for that entry should
    /// call. The table is read from the source text because a function pointer
    /// does not carry its own name at runtime.
    #[test]
    fn each_cast_calls_the_algorithm_it_is_filed_under() {
        // Compiled in, so this cannot be defeated by running from another
        // directory, and cannot go looking at a stale copy on disk.
        const SOURCE: &str = include_str!("selftest.rs");

        let table = SOURCE
            .split_once("static CASTS: &[Cast] = &[")
            .expect("the CAST table is not where this expects it")
            .1
            .split_once("\n];")
            .expect("the CAST table does not end")
            .0;

        let mut by_path = 0;
        let mut by_local_fn = 0;

        // Flattened first: rustfmt wraps a row whose path is long, and
        // `hkdf-sha2-256` is spread over four lines. Reading line by line
        // silently skipped it.
        let flat: String = table
            .lines()
            .map(|l| l.split("//").next().unwrap_or("").trim())
            .collect::<Vec<_>>()
            .join(" ");

        for row in flat.split("),") {
            let Some((id, rest)) = row.split_once('"').and_then(|(_, r)| r.split_once('"')) else {
                continue;
            };
            let function = rest
                .trim()
                .trim_start_matches(',')
                .trim()
                .trim_end_matches(')')
                .trim_end_matches(',')
                .trim();

            if function.is_empty() {
                continue;
            }
            let entry =
                ic_ontology::get(id).unwrap_or_else(|| panic!("{id} has no ontology entry"));

            if let Some(ty) = function.strip_suffix("::self_test") {
                // The usual form: the trait method on the type itself. The
                // ontology's path for the entry must be that same type, or the
                // table is testing something else under this name.
                assert_eq!(
                    ty, entry.rust_path,
                    "the CAST for {id} calls {ty}, but the ontology says {id} is \
                     {}",
                    entry.rust_path
                );
                by_path += 1;
            } else {
                // A hand-written vector, for the algorithms whose check does not
                // fit the trait. The name is the only thing tying it to the
                // entry, so it has to match.
                let expected = format!("{}_self_test", id.replace('-', "_"));
                assert_eq!(
                    function, expected,
                    "the CAST for {id} calls {function}, which does not name {id}"
                );
                by_local_fn += 1;
            }
        }

        // Floors: the parse above is the kind that quietly matches nothing if
        // the table is reformatted, and then this passes having checked none of
        // it. Both forms must also still be present, or the branch that is gone
        // is no longer being tested.
        assert_eq!(
            by_path + by_local_fn,
            CASTS.len(),
            "the source table and the compiled one are different lengths, so the \
             parse missed rows"
        );
        assert!(
            by_path > 50,
            "only {by_path} casts checked against a rust path"
        );
        assert!(by_local_fn > 0, "no hand-written casts found");
    }

    #[test]
    fn every_cast_names_a_real_ontology_entry() {
        for name in tested_algorithms() {
            assert!(
                ic_ontology::get(name).is_some(),
                "{name} has a CAST but no ontology entry"
            );
        }
    }

    #[test]
    fn single_algorithm_tests_are_addressable() {
        run_self_test("sha2-256").unwrap();
        run_self_test("aes-256-gcm").unwrap();
        assert_eq!(
            run_self_test("no-such-algorithm").unwrap_err().kind(),
            ic_core::ErrorKind::Unsupported
        );
    }

    #[test]
    fn integrity_check_passes() {
        integrity_check().unwrap();
    }

    /// The expected tag must match the one the table actually produces, and the
    /// failure must say what to paste.
    ///
    /// [`integrity_check`] compares in constant time and reports only that the
    /// check failed, which is right for an operational path and useless for
    /// maintenance: adding a CAST changes the tag, and before this test the
    /// only guidance was a bare "module integrity check failed". Anyone hitting
    /// it had to reverse-engineer where the constant came from. Now the
    /// recomputed value is printed, so the fix is a copy and paste.
    #[test]
    fn the_integrity_tag_matches_the_table() {
        use ic_core::traits::Mac;

        let mut mac = ic_mac::HmacSha256::new(INTEGRITY_KEY).unwrap();
        for (name, _) in CASTS {
            mac.update(name.as_bytes());
            mac.update(&[0]);
        }
        let tag = mac.finalize();
        let computed: String = tag.as_ref().iter().map(|b| format!("{b:02x}")).collect();

        assert_eq!(
            computed, INTEGRITY_TAG,
            "the CAST table changed. Set INTEGRITY_TAG to {computed:?}"
        );
    }
}