metamorphic-crypto 0.6.0

Zero-knowledge end-to-end encryption with post-quantum hybrid KEM (ML-KEM-512/768/1024 + X25519)
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
//! Hybrid post-quantum KEM: ML-KEM-512 + X25519 (Cat-1), ML-KEM-768 + X25519
//! (Cat-3, default), and ML-KEM-1024 + X25519 (Cat-5).
//!
//! This module implements hybrid KEMs combining ML-KEM with X25519, ensuring
//! byte-level compatibility with existing production ciphertext. The three tiers
//! span the **full standardized ML-KEM range** — NIST (FIPS 203) defines ML-KEM
//! only at categories 1, 3, and 5 (512 / 768 / 1024). There is **no** category-2
//! or category-4 ML-KEM parameter set, so none is offered here.
//!
//! ## Security Levels
//!
//! | Level | ML-KEM | NIST Category | Equivalent | Version Tag |
//! |-------|--------|---------------|------------|-------------|
//! | Cat-1 | 512    | 1             | ~AES-128   | `0x01`      |
//! | Cat-3 | 768    | 3             | ~AES-192   | `0x02`      |
//! | Cat-5 | 1024   | 5             | ~AES-256   | `0x03`      |
//!
//! ### About the version tags
//!
//! The version tag is a **per-artifact-type wire-format version**, *not* a
//! global NIST-category code. A KEM tag only ever appears as the first byte of a
//! hybrid-KEM ciphertext produced by this module and is parsed only by
//! [`hybrid_open`] / [`is_hybrid_ciphertext`]; it is never handed to the
//! signature code. The KEM tags form a dense ordered sequence — Cat-1 = `0x01`,
//! Cat-3 = `0x02`, Cat-5 = `0x03`.
//!
//! By design these tags **agree with the signature tags in [`crate::sign`] on
//! every level the two families share**: Cat-3 = `0x02` and Cat-5 = `0x03` in
//! both. The single divergence is at `0x01`, which here denotes Cat-1
//! (ML-KEM-512) while on the signature side `0x01` denotes Cat-2 (ML-DSA-44).
//! This is unavoidable: NIST standardizes ML-KEM at categories {1, 3, 5} but
//! ML-DSA at {2, 3, 5}, so the two families have different lowest rungs and
//! "tag == category" cannot hold for both.
//!
//! These bytes are **not legacy sentinels**, either. The pre-PQ `box_seal`
//! ciphertext format is *unversioned* — its output is `ephemeral_pk (32) ||
//! box_ct`, so its first byte is a random X25519 public-key byte, not a reserved
//! tag — so there is no `0x00`/`0x01` legacy marker anywhere for these values to
//! clash with. Both [`is_hybrid_ciphertext`] and [`hybrid_open`] additionally
//! enforce a minimum-length gate per tier, so a legacy ciphertext whose random
//! first byte happens to be `0x01` cannot be mis-routed as a Cat-1 hybrid
//! ciphertext; [`crate::seal::unseal_from_user`] also falls back to the legacy
//! opener if a hybrid open fails, closing the residual length-collision case.
//!
//! ## Construction (from noble source)
//!
//! ```text
//! combineKEMS(
//!   seedLen = 32,
//!   outputLen = 32,
//!   expandSeed = SHAKE256(seed, dkLen=96),
//!   combiner = SHA3-256(ss_mlkem || ss_x25519 || ct_x25519 || pk_x25519 || b"\\.//^\\"),
//!   ml_kem{512|768|1024},
//!   ecdhKem(x25519)
//! )
//! ```
//!
//! ## Key layout (Cat-1 / Cat-3 / Cat-5)
//!
//! | Component | Cat-1 (512) | Cat-3 (768) | Cat-5 (1024) | Description |
//! |-----------|-------------|-------------|--------------|-------------|
//! | Secret key (seed) | 32 bytes | 32 bytes | 32 bytes | Root seed expanded via SHAKE256 |
//! | Public key | 832 bytes | 1216 bytes | 1600 bytes | ML-KEM ek ‖ X25519 pk (32) |
//! | Ciphertext | 800 bytes | 1120 bytes | 1600 bytes | ML-KEM ct ‖ X25519 ephemeral pk (32) |
//! | Shared secret | 32 bytes | 32 bytes | 32 bytes | SHA3-256 combiner output |
//!
//! ## Classical partner caveat
//!
//! The classical half is **X25519 (~Cat-1 classical) at every tier** — it does
//! not scale up with the ML-KEM parameter set. At Cat-3 and Cat-5 the
//! post-quantum half dominates and X25519 is the classical floor; this is
//! standard hybrid-KEM practice (the hybrid is at least as strong as its
//! strongest component, and a break requires defeating *both* halves). If you
//! need a higher classical margin, that is a separate (currently non-standard
//! for X25519) concern.
//!
//! ## Sealed-box ciphertext format
//!
//! ```text
//! v1: 0x01 || hybrid_ciphertext_512  (800 B)  || nonce (24 B) || secretbox_ct
//! v2: 0x02 || hybrid_ciphertext_768  (1120 B) || nonce (24 B) || secretbox_ct
//! v3: 0x03 || hybrid_ciphertext_1024 (1600 B) || nonce (24 B) || secretbox_ct
//! ```

use ml_kem::{Decapsulate, MlKem512, MlKem768, MlKem1024};
use ml_kem::{DecapsulationKey, EncapsulationKey, KeyExport};
use sha3::Shake256;
use sha3::digest::{ExtendableOutput, Update, XofReader};
use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret as X25519StaticSecret};
use zeroize::Zeroize;

use crypto_secretbox::aead::Aead;
use crypto_secretbox::aead::generic_array::GenericArray;
use crypto_secretbox::{KeyInit, XSalsa20Poly1305};

use crate::CryptoError;
use crate::b64;

// === Constants ===

/// Version tag for Cat-1 hybrid ciphertext (ML-KEM-512).
const VERSION_HYBRID_512: u8 = 0x01;
/// Version tag for Cat-3 hybrid ciphertext (ML-KEM-768).
const VERSION_HYBRID_768: u8 = 0x02;
/// Version tag for Cat-5 hybrid ciphertext (ML-KEM-1024).
const VERSION_HYBRID_1024: u8 = 0x03;
/// XSalsa20 nonce length.
const NONCE_LEN: usize = 24;
/// X25519 key size.
const X25519_LEN: usize = 32;
/// Root seed length.
const SEED_LEN: usize = 32;
/// Poly1305 MAC.
const MAC_LEN: usize = 16;
/// Noble's domain-separation label.
const LABEL: &[u8] = b"\\.//^\\";

// ML-KEM-512 (Cat-1)
/// ML-KEM-512 encapsulation key size.
const MLKEM512_EK_LEN: usize = 800;
/// ML-KEM-512 ciphertext size.
const MLKEM512_CT_LEN: usize = 768;
/// ML-KEM-512 seed portion (64 bytes).
const MLKEM512_SEED_LEN: usize = 64;
/// Expanded seed for Cat-1: ML-KEM seed (64) + X25519 secret (32).
const EXPANDED_SEED_512_LEN: usize = 96;
/// Combined public key for Cat-1: ML-KEM ek (800) + X25519 pk (32).
const COMBINED_PK_512_LEN: usize = MLKEM512_EK_LEN + X25519_LEN;
/// Combined ciphertext for Cat-1: ML-KEM ct (768) + X25519 ephemeral pk (32).
const COMBINED_CT_512_LEN: usize = MLKEM512_CT_LEN + X25519_LEN;
/// Minimum sealed-box length for a Cat-1 hybrid ciphertext (empty plaintext:
/// version tag + combined ct + nonce + Poly1305 MAC). Single source of truth
/// shared by the routing check ([`is_hybrid_ciphertext`]) and the open gate
/// ([`hybrid_open_512`]); keeping them in lockstep is what prevents a legacy
/// ciphertext from being mis-routed.
const MIN_HYBRID_512_LEN: usize = 1 + COMBINED_CT_512_LEN + NONCE_LEN + MAC_LEN;

// ML-KEM-768 (Cat-3)
/// ML-KEM-768 encapsulation key size.
const MLKEM768_EK_LEN: usize = 1184;
/// ML-KEM-768 ciphertext size.
const MLKEM768_CT_LEN: usize = 1088;
/// ML-KEM-768 seed portion (64 bytes).
const MLKEM768_SEED_LEN: usize = 64;
/// Expanded seed for Cat-3: ML-KEM seed (64) + X25519 secret (32).
const EXPANDED_SEED_768_LEN: usize = 96;
/// Combined public key for Cat-3: ML-KEM ek (1184) + X25519 pk (32).
const COMBINED_PK_768_LEN: usize = MLKEM768_EK_LEN + X25519_LEN;
/// Combined ciphertext for Cat-3: ML-KEM ct (1088) + X25519 ephemeral pk (32).
const COMBINED_CT_768_LEN: usize = MLKEM768_CT_LEN + X25519_LEN;
/// Minimum sealed-box length for a Cat-3 hybrid ciphertext (empty plaintext).
/// Shared by [`is_hybrid_ciphertext`] and [`hybrid_open_768`].
const MIN_HYBRID_768_LEN: usize = 1 + COMBINED_CT_768_LEN + NONCE_LEN + MAC_LEN;

// ML-KEM-1024 (Cat-5)
/// ML-KEM-1024 encapsulation key size.
const MLKEM1024_EK_LEN: usize = 1568;
/// ML-KEM-1024 ciphertext size.
const MLKEM1024_CT_LEN: usize = 1568;
/// ML-KEM-1024 seed portion (64 bytes).
const MLKEM1024_SEED_LEN: usize = 64;
/// Expanded seed for Cat-5: ML-KEM seed (64) + X25519 secret (32).
const EXPANDED_SEED_1024_LEN: usize = 96;
/// Combined public key for Cat-5: ML-KEM ek (1568) + X25519 pk (32).
const COMBINED_PK_1024_LEN: usize = MLKEM1024_EK_LEN + X25519_LEN;
/// Combined ciphertext for Cat-5: ML-KEM ct (1568) + X25519 ephemeral pk (32).
const COMBINED_CT_1024_LEN: usize = MLKEM1024_CT_LEN + X25519_LEN;
/// Minimum sealed-box length for a Cat-5 hybrid ciphertext (empty plaintext).
/// Shared by [`is_hybrid_ciphertext`] and [`hybrid_open_1024`].
const MIN_HYBRID_1024_LEN: usize = 1 + COMBINED_CT_1024_LEN + NONCE_LEN + MAC_LEN;

// === Types ===

/// A hybrid ML-KEM + X25519 keypair (base64-encoded).
#[derive(Debug, Clone)]
pub struct HybridKeyPair {
    /// Combined public key: ML-KEM ek ‖ X25519 pk. Base64.
    pub public_key: String,
    /// Root seed (32 bytes). Base64.
    pub secret_key: String,
}

/// Security level for hybrid PQ operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SecurityLevel {
    /// NIST Category 1: ML-KEM-512 + X25519 (~AES-128).
    Cat1,
    /// NIST Category 3: ML-KEM-768 + X25519 (~AES-192). Default.
    #[default]
    Cat3,
    /// NIST Category 5: ML-KEM-1024 + X25519 (~AES-256).
    Cat5,
}

// === Helpers ===

/// Fill buffer with OS random bytes.
#[inline]
fn random_bytes(buf: &mut [u8]) {
    getrandom::getrandom(buf).expect("OS CSPRNG unavailable");
}

/// Expand a 32-byte seed using SHAKE256.
fn expand_seed(seed: &[u8; SEED_LEN], output_len: usize) -> Vec<u8> {
    let mut hasher = Shake256::default();
    hasher.update(seed);
    let mut reader = hasher.finalize_xof();
    let mut out = vec![0u8; output_len];
    reader.read(&mut out);
    out
}

/// SHA3-256 combiner: `SHA3-256(ss_mlkem || ss_x25519 || ct_x25519 || pk_x25519 || label)`
fn combine(
    ss_mlkem: &[u8],
    ss_x25519: &[u8],
    ct_x25519: &[u8; X25519_LEN],
    pk_x25519: &[u8; X25519_LEN],
) -> [u8; 32] {
    use sha3::Digest;
    let mut hasher = sha3::Sha3_256::new();
    Digest::update(&mut hasher, ss_mlkem);
    Digest::update(&mut hasher, ss_x25519);
    Digest::update(&mut hasher, ct_x25519);
    Digest::update(&mut hasher, pk_x25519);
    Digest::update(&mut hasher, LABEL);
    hasher.finalize().into()
}

/// Encrypt plaintext with a 32-byte shared secret using XSalsa20-Poly1305.
fn secretbox_encrypt(
    shared_secret: &[u8; 32],
    plaintext: &[u8],
) -> Result<(Vec<u8>, [u8; NONCE_LEN]), CryptoError> {
    let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(shared_secret));
    let mut nonce_buf = [0u8; NONCE_LEN];
    random_bytes(&mut nonce_buf);
    let nonce = GenericArray::from_slice(&nonce_buf);
    let ct = cipher
        .encrypt(nonce, plaintext)
        .map_err(|_| CryptoError::Hybrid("secretbox encrypt failed".into()))?;
    Ok((ct, nonce_buf))
}

/// Decrypt ciphertext with a 32-byte shared secret using XSalsa20-Poly1305.
fn secretbox_decrypt(
    shared_secret: &[u8; 32],
    nonce: &[u8],
    ciphertext: &[u8],
) -> Result<Vec<u8>, CryptoError> {
    let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(shared_secret));
    let nonce = GenericArray::from_slice(nonce);
    cipher
        .decrypt(nonce, ciphertext)
        .map_err(|_| CryptoError::Decryption)
}

// === Public API: Cat-1 (ML-KEM-512) ===

/// Generate a hybrid ML-KEM-512 + X25519 keypair (Cat-1).
pub fn generate_hybrid_keypair_512() -> HybridKeyPair {
    generate_hybrid_keypair_with_level(SecurityLevel::Cat1)
}

/// Seal `plaintext` to a Cat-1 hybrid public key (ML-KEM-512).
///
/// Returns base64: `0x01 || hybrid_ct (800 B) || nonce (24 B) || secretbox_ct`.
pub fn hybrid_seal_512(plaintext: &[u8], combined_pk_b64: &str) -> Result<String, CryptoError> {
    hybrid_seal_with_level(plaintext, combined_pk_b64, SecurityLevel::Cat1)
}

// === Public API: Cat-3 (ML-KEM-768, default) ===

/// Generate a hybrid ML-KEM-768 + X25519 keypair (Cat-3, default).
pub fn generate_hybrid_keypair() -> HybridKeyPair {
    generate_hybrid_keypair_with_level(SecurityLevel::Cat3)
}

/// Seal `plaintext` to a Cat-3 hybrid public key (ML-KEM-768).
///
/// Returns base64: `0x02 || hybrid_ct (1120 B) || nonce (24 B) || secretbox_ct`.
pub fn hybrid_seal(plaintext: &[u8], combined_pk_b64: &str) -> Result<String, CryptoError> {
    hybrid_seal_with_level(plaintext, combined_pk_b64, SecurityLevel::Cat3)
}

/// Open a Cat-1, Cat-3, or Cat-5 hybrid-sealed ciphertext. Auto-detects from version tag.
pub fn hybrid_open(ct_b64: &str, seed_b64: &str) -> Result<Vec<u8>, CryptoError> {
    let combined = b64::decode(ct_b64)?;
    match combined.first() {
        Some(&VERSION_HYBRID_512) => hybrid_open_512(&combined, seed_b64),
        Some(&VERSION_HYBRID_768) => hybrid_open_768(&combined, seed_b64),
        Some(&VERSION_HYBRID_1024) => hybrid_open_1024(&combined, seed_b64),
        _ => Err(CryptoError::Hybrid(
            "not a hybrid ciphertext (bad version tag)".into(),
        )),
    }
}

/// Returns `true` if the base64 blob is a hybrid ciphertext: its first byte is a
/// known version tag (`0x01`, `0x02`, or `0x03`) **and** its total length is at
/// least the minimum for that tier.
///
/// The length check (matching the exact minimum-length gate enforced by
/// [`hybrid_open`]) is what definitively distinguishes a hybrid ciphertext from a
/// legacy `box_seal` ciphertext whose random first byte happens to collide with a
/// tag value: a real hybrid ciphertext is always `>=` its tier minimum, while a
/// short legacy ciphertext below that bound is correctly rejected here. (A legacy
/// ciphertext that collides on *both* the first byte *and* a hybrid-matching
/// length is still handled safely by the fallback in
/// [`crate::seal::unseal_from_user`].)
pub fn is_hybrid_ciphertext(ct_b64: &str) -> bool {
    let Ok(bytes) = b64::decode(ct_b64) else {
        return false;
    };
    match bytes.first() {
        Some(&VERSION_HYBRID_512) => bytes.len() >= MIN_HYBRID_512_LEN,
        Some(&VERSION_HYBRID_768) => bytes.len() >= MIN_HYBRID_768_LEN,
        Some(&VERSION_HYBRID_1024) => bytes.len() >= MIN_HYBRID_1024_LEN,
        _ => false,
    }
}

// === Public API: Cat-5 (ML-KEM-1024) ===

/// Generate a hybrid ML-KEM-1024 + X25519 keypair (Cat-5).
pub fn generate_hybrid_keypair_1024() -> HybridKeyPair {
    generate_hybrid_keypair_with_level(SecurityLevel::Cat5)
}

/// Seal `plaintext` to a Cat-5 hybrid public key (ML-KEM-1024).
///
/// Returns base64: `0x03 || hybrid_ct (1600 B) || nonce (24 B) || secretbox_ct`.
pub fn hybrid_seal_1024(plaintext: &[u8], combined_pk_b64: &str) -> Result<String, CryptoError> {
    hybrid_seal_with_level(plaintext, combined_pk_b64, SecurityLevel::Cat5)
}

// === Public API: Level-parametric ===

/// Generate a hybrid keypair at the specified security level.
pub fn generate_hybrid_keypair_with_level(level: SecurityLevel) -> HybridKeyPair {
    let mut seed = [0u8; SEED_LEN];
    random_bytes(&mut seed);

    let expanded_len = match level {
        SecurityLevel::Cat1 => EXPANDED_SEED_512_LEN,
        SecurityLevel::Cat3 => EXPANDED_SEED_768_LEN,
        SecurityLevel::Cat5 => EXPANDED_SEED_1024_LEN,
    };
    let mlkem_seed_len = match level {
        SecurityLevel::Cat1 => MLKEM512_SEED_LEN,
        SecurityLevel::Cat3 => MLKEM768_SEED_LEN,
        SecurityLevel::Cat5 => MLKEM1024_SEED_LEN,
    };

    let mut expanded = expand_seed(&seed, expanded_len);
    let x25519_sk_bytes: [u8; X25519_LEN] = expanded[mlkem_seed_len..].try_into().unwrap();

    // X25519 keypair
    let x25519_sk = X25519StaticSecret::from(x25519_sk_bytes);
    let x25519_pk = X25519PublicKey::from(&x25519_sk);

    let combined_pk = match level {
        SecurityLevel::Cat1 => {
            let mlkem_seed: [u8; MLKEM512_SEED_LEN] =
                expanded[..MLKEM512_SEED_LEN].try_into().unwrap();
            let dk = DecapsulationKey::<MlKem512>::from_seed(mlkem_seed.into());
            let ek = dk.encapsulation_key();
            let ek_bytes = ek.to_bytes();
            let mut pk = Vec::with_capacity(COMBINED_PK_512_LEN);
            pk.extend_from_slice(&ek_bytes);
            pk.extend_from_slice(x25519_pk.as_bytes());
            pk
        }
        SecurityLevel::Cat3 => {
            let mlkem_seed: [u8; MLKEM768_SEED_LEN] =
                expanded[..MLKEM768_SEED_LEN].try_into().unwrap();
            let dk = DecapsulationKey::<MlKem768>::from_seed(mlkem_seed.into());
            let ek = dk.encapsulation_key();
            let ek_bytes = ek.to_bytes();
            let mut pk = Vec::with_capacity(COMBINED_PK_768_LEN);
            pk.extend_from_slice(&ek_bytes);
            pk.extend_from_slice(x25519_pk.as_bytes());
            pk
        }
        SecurityLevel::Cat5 => {
            let mlkem_seed: [u8; MLKEM1024_SEED_LEN] =
                expanded[..MLKEM1024_SEED_LEN].try_into().unwrap();
            let dk = DecapsulationKey::<MlKem1024>::from_seed(mlkem_seed.into());
            let ek = dk.encapsulation_key();
            let ek_bytes = ek.to_bytes();
            let mut pk = Vec::with_capacity(COMBINED_PK_1024_LEN);
            pk.extend_from_slice(&ek_bytes);
            pk.extend_from_slice(x25519_pk.as_bytes());
            pk
        }
    };

    let pair = HybridKeyPair {
        public_key: b64::encode(&combined_pk),
        secret_key: b64::encode(&seed),
    };

    seed.zeroize();
    expanded.zeroize();
    pair
}

/// Seal plaintext at the specified security level.
pub fn hybrid_seal_with_level(
    plaintext: &[u8],
    combined_pk_b64: &str,
    level: SecurityLevel,
) -> Result<String, CryptoError> {
    let pk_bytes = b64::decode(combined_pk_b64)?;

    let (expected_pk_len, mlkem_ek_len, version_tag) = match level {
        SecurityLevel::Cat1 => (COMBINED_PK_512_LEN, MLKEM512_EK_LEN, VERSION_HYBRID_512),
        SecurityLevel::Cat3 => (COMBINED_PK_768_LEN, MLKEM768_EK_LEN, VERSION_HYBRID_768),
        SecurityLevel::Cat5 => (COMBINED_PK_1024_LEN, MLKEM1024_EK_LEN, VERSION_HYBRID_1024),
    };

    if pk_bytes.len() != expected_pk_len {
        return Err(CryptoError::InvalidLength {
            expected: expected_pk_len,
            got: pk_bytes.len(),
        });
    }

    // Split combined public key
    let mlkem_ek_bytes = &pk_bytes[..mlkem_ek_len];
    let x25519_pk_bytes: [u8; X25519_LEN] = pk_bytes[mlkem_ek_len..].try_into().unwrap();

    // ML-KEM encapsulate
    let mut mlkem_coins = [0u8; 32];
    random_bytes(&mut mlkem_coins);

    let (mlkem_ct_bytes, ss_mlkem_bytes) = match level {
        SecurityLevel::Cat1 => {
            let ek = EncapsulationKey::<MlKem512>::new(
                mlkem_ek_bytes
                    .try_into()
                    .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-512 ek".into()))?,
            )
            .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-512 encapsulation key".into()))?;
            let (ct, ss) = ek.encapsulate_deterministic(&mlkem_coins.into());
            (ct.as_slice().to_vec(), ss.as_slice().to_vec())
        }
        SecurityLevel::Cat3 => {
            let ek = EncapsulationKey::<MlKem768>::new(
                mlkem_ek_bytes
                    .try_into()
                    .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-768 ek".into()))?,
            )
            .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-768 encapsulation key".into()))?;
            let (ct, ss) = ek.encapsulate_deterministic(&mlkem_coins.into());
            (ct.as_slice().to_vec(), ss.as_slice().to_vec())
        }
        SecurityLevel::Cat5 => {
            let ek = EncapsulationKey::<MlKem1024>::new(
                mlkem_ek_bytes
                    .try_into()
                    .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-1024 ek".into()))?,
            )
            .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-1024 encapsulation key".into()))?;
            let (ct, ss) = ek.encapsulate_deterministic(&mlkem_coins.into());
            (ct.as_slice().to_vec(), ss.as_slice().to_vec())
        }
    };
    mlkem_coins.zeroize();

    // X25519 encapsulate (ephemeral DH)
    let mut x25519_eph_bytes = [0u8; X25519_LEN];
    random_bytes(&mut x25519_eph_bytes);
    let x25519_eph_sk = X25519StaticSecret::from(x25519_eph_bytes);
    let x25519_eph_pk = X25519PublicKey::from(&x25519_eph_sk);
    let x25519_recipient_pk = X25519PublicKey::from(x25519_pk_bytes);
    let ss_x25519 = x25519_eph_sk.diffie_hellman(&x25519_recipient_pk);
    x25519_eph_bytes.zeroize();

    // Combine shared secrets
    let ct_x25519: [u8; X25519_LEN] = *x25519_eph_pk.as_bytes();
    let mut shared_secret = combine(
        &ss_mlkem_bytes,
        ss_x25519.as_bytes(),
        &ct_x25519,
        &x25519_pk_bytes,
    );

    // Encrypt plaintext
    let (secretbox_ct, nonce_buf) = secretbox_encrypt(&shared_secret, plaintext)?;
    shared_secret.zeroize();

    // Assemble: version || mlkem_ct || x25519_eph_pk || nonce || secretbox_ct
    let combined_ct_len = mlkem_ct_bytes.len() + X25519_LEN;
    let mut out = Vec::with_capacity(1 + combined_ct_len + NONCE_LEN + secretbox_ct.len());
    out.push(version_tag);
    out.extend_from_slice(&mlkem_ct_bytes);
    out.extend_from_slice(&ct_x25519);
    out.extend_from_slice(&nonce_buf);
    out.extend_from_slice(&secretbox_ct);

    Ok(b64::encode(&out))
}

// === Internal: Cat-1 open ===

fn hybrid_open_512(combined: &[u8], seed_b64: &str) -> Result<Vec<u8>, CryptoError> {
    let seed_bytes = b64::decode(seed_b64)?;
    if seed_bytes.len() != SEED_LEN {
        return Err(CryptoError::InvalidLength {
            expected: SEED_LEN,
            got: seed_bytes.len(),
        });
    }
    if combined.len() < MIN_HYBRID_512_LEN {
        return Err(CryptoError::TooShort);
    }

    let seed: [u8; SEED_LEN] = seed_bytes.try_into().unwrap();
    let mut expanded = expand_seed(&seed, EXPANDED_SEED_512_LEN);
    let mlkem_seed: [u8; MLKEM512_SEED_LEN] = expanded[..MLKEM512_SEED_LEN].try_into().unwrap();
    let x25519_sk_bytes: [u8; X25519_LEN] = expanded[MLKEM512_SEED_LEN..].try_into().unwrap();
    expanded.zeroize();

    // Parse ciphertext
    let mlkem_ct = &combined[1..1 + MLKEM512_CT_LEN];
    let x25519_eph_pk_bytes: [u8; X25519_LEN] = combined
        [1 + MLKEM512_CT_LEN..1 + COMBINED_CT_512_LEN]
        .try_into()
        .unwrap();
    let nonce_slice = &combined[1 + COMBINED_CT_512_LEN..1 + COMBINED_CT_512_LEN + NONCE_LEN];
    let encrypted = &combined[1 + COMBINED_CT_512_LEN + NONCE_LEN..];

    // ML-KEM-512 decapsulate
    let dk = DecapsulationKey::<MlKem512>::from_seed(mlkem_seed.into());
    let kem_ct = mlkem_ct
        .try_into()
        .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-512 ciphertext".into()))?;
    let ss_mlkem = dk.decapsulate(kem_ct);

    // X25519 decapsulate
    let x25519_sk = X25519StaticSecret::from(x25519_sk_bytes);
    let x25519_eph_pk = X25519PublicKey::from(x25519_eph_pk_bytes);
    let ss_x25519 = x25519_sk.diffie_hellman(&x25519_eph_pk);

    let x25519_pk = X25519PublicKey::from(&x25519_sk);
    let pk_x25519: [u8; X25519_LEN] = *x25519_pk.as_bytes();

    let mut shared_secret = combine(
        ss_mlkem.as_slice(),
        ss_x25519.as_bytes(),
        &x25519_eph_pk_bytes,
        &pk_x25519,
    );

    let result = secretbox_decrypt(&shared_secret, nonce_slice, encrypted);
    shared_secret.zeroize();
    result
}

// === Internal: Cat-3 open ===

fn hybrid_open_768(combined: &[u8], seed_b64: &str) -> Result<Vec<u8>, CryptoError> {
    let seed_bytes = b64::decode(seed_b64)?;
    if seed_bytes.len() != SEED_LEN {
        return Err(CryptoError::InvalidLength {
            expected: SEED_LEN,
            got: seed_bytes.len(),
        });
    }
    if combined.len() < MIN_HYBRID_768_LEN {
        return Err(CryptoError::TooShort);
    }

    let seed: [u8; SEED_LEN] = seed_bytes.try_into().unwrap();
    let mut expanded = expand_seed(&seed, EXPANDED_SEED_768_LEN);
    let mlkem_seed: [u8; MLKEM768_SEED_LEN] = expanded[..MLKEM768_SEED_LEN].try_into().unwrap();
    let x25519_sk_bytes: [u8; X25519_LEN] = expanded[MLKEM768_SEED_LEN..].try_into().unwrap();
    expanded.zeroize();

    // Parse ciphertext
    let mlkem_ct = &combined[1..1 + MLKEM768_CT_LEN];
    let x25519_eph_pk_bytes: [u8; X25519_LEN] = combined
        [1 + MLKEM768_CT_LEN..1 + COMBINED_CT_768_LEN]
        .try_into()
        .unwrap();
    let nonce_slice = &combined[1 + COMBINED_CT_768_LEN..1 + COMBINED_CT_768_LEN + NONCE_LEN];
    let encrypted = &combined[1 + COMBINED_CT_768_LEN + NONCE_LEN..];

    // ML-KEM-768 decapsulate
    let dk = DecapsulationKey::<MlKem768>::from_seed(mlkem_seed.into());
    let kem_ct = mlkem_ct
        .try_into()
        .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-768 ciphertext".into()))?;
    let ss_mlkem = dk.decapsulate(kem_ct);

    // X25519 decapsulate
    let x25519_sk = X25519StaticSecret::from(x25519_sk_bytes);
    let x25519_eph_pk = X25519PublicKey::from(x25519_eph_pk_bytes);
    let ss_x25519 = x25519_sk.diffie_hellman(&x25519_eph_pk);

    let x25519_pk = X25519PublicKey::from(&x25519_sk);
    let pk_x25519: [u8; X25519_LEN] = *x25519_pk.as_bytes();

    let mut shared_secret = combine(
        ss_mlkem.as_slice(),
        ss_x25519.as_bytes(),
        &x25519_eph_pk_bytes,
        &pk_x25519,
    );

    let result = secretbox_decrypt(&shared_secret, nonce_slice, encrypted);
    shared_secret.zeroize();
    result
}

// === Internal: Cat-5 open ===

fn hybrid_open_1024(combined: &[u8], seed_b64: &str) -> Result<Vec<u8>, CryptoError> {
    let seed_bytes = b64::decode(seed_b64)?;
    if seed_bytes.len() != SEED_LEN {
        return Err(CryptoError::InvalidLength {
            expected: SEED_LEN,
            got: seed_bytes.len(),
        });
    }
    if combined.len() < MIN_HYBRID_1024_LEN {
        return Err(CryptoError::TooShort);
    }

    let seed: [u8; SEED_LEN] = seed_bytes.try_into().unwrap();
    let mut expanded = expand_seed(&seed, EXPANDED_SEED_1024_LEN);
    let mlkem_seed: [u8; MLKEM1024_SEED_LEN] = expanded[..MLKEM1024_SEED_LEN].try_into().unwrap();
    let x25519_sk_bytes: [u8; X25519_LEN] = expanded[MLKEM1024_SEED_LEN..].try_into().unwrap();
    expanded.zeroize();

    // Parse ciphertext
    let mlkem_ct = &combined[1..1 + MLKEM1024_CT_LEN];
    let x25519_eph_pk_bytes: [u8; X25519_LEN] = combined
        [1 + MLKEM1024_CT_LEN..1 + COMBINED_CT_1024_LEN]
        .try_into()
        .unwrap();
    let nonce_slice = &combined[1 + COMBINED_CT_1024_LEN..1 + COMBINED_CT_1024_LEN + NONCE_LEN];
    let encrypted = &combined[1 + COMBINED_CT_1024_LEN + NONCE_LEN..];

    // ML-KEM-1024 decapsulate
    let dk = DecapsulationKey::<MlKem1024>::from_seed(mlkem_seed.into());
    let kem_ct = mlkem_ct
        .try_into()
        .map_err(|_| CryptoError::Hybrid("invalid ML-KEM-1024 ciphertext".into()))?;
    let ss_mlkem = dk.decapsulate(kem_ct);

    // X25519 decapsulate
    let x25519_sk = X25519StaticSecret::from(x25519_sk_bytes);
    let x25519_eph_pk = X25519PublicKey::from(x25519_eph_pk_bytes);
    let ss_x25519 = x25519_sk.diffie_hellman(&x25519_eph_pk);

    let x25519_pk = X25519PublicKey::from(&x25519_sk);
    let pk_x25519: [u8; X25519_LEN] = *x25519_pk.as_bytes();

    let mut shared_secret = combine(
        ss_mlkem.as_slice(),
        ss_x25519.as_bytes(),
        &x25519_eph_pk_bytes,
        &pk_x25519,
    );

    let result = secretbox_decrypt(&shared_secret, nonce_slice, encrypted);
    shared_secret.zeroize();
    result
}

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

    // === Cat-3 (existing behavior) ===

    #[test]
    fn cat3_roundtrip() {
        let kp = generate_hybrid_keypair();
        let pt = b"32-byte symmetric context key!!!";
        let ct = hybrid_seal(pt, &kp.public_key).unwrap();
        assert!(is_hybrid_ciphertext(&ct));
        let opened = hybrid_open(&ct, &kp.secret_key).unwrap();
        assert_eq!(opened, pt);
    }

    #[test]
    fn cat3_wrong_key_fails() {
        let kp1 = generate_hybrid_keypair();
        let kp2 = generate_hybrid_keypair();
        let ct = hybrid_seal(b"x", &kp1.public_key).unwrap();
        assert!(hybrid_open(&ct, &kp2.secret_key).is_err());
    }

    #[test]
    fn cat3_version_tag() {
        let kp = generate_hybrid_keypair();
        let raw = b64::decode(&hybrid_seal(b"x", &kp.public_key).unwrap()).unwrap();
        assert_eq!(raw[0], VERSION_HYBRID_768);
    }

    #[test]
    fn cat3_nondeterministic() {
        let kp = generate_hybrid_keypair();
        let c1 = hybrid_seal(b"x", &kp.public_key).unwrap();
        let c2 = hybrid_seal(b"x", &kp.public_key).unwrap();
        assert_ne!(c1, c2);
    }

    #[test]
    fn cat3_empty_plaintext() {
        let kp = generate_hybrid_keypair();
        let ct = hybrid_seal(b"", &kp.public_key).unwrap();
        assert_eq!(hybrid_open(&ct, &kp.secret_key).unwrap(), b"");
    }

    #[test]
    fn cat3_key_sizes() {
        let kp = generate_hybrid_keypair();
        let pk = b64::decode(&kp.public_key).unwrap();
        let sk = b64::decode(&kp.secret_key).unwrap();
        assert_eq!(pk.len(), COMBINED_PK_768_LEN); // 1216
        assert_eq!(sk.len(), SEED_LEN); // 32
    }

    #[test]
    fn cat3_ciphertext_size() {
        let kp = generate_hybrid_keypair();
        let pt = b"exactly 32 bytes of key material";
        let raw = b64::decode(&hybrid_seal(pt, &kp.public_key).unwrap()).unwrap();
        // 1 + 1120 + 24 + 32 + 16 = 1193
        assert_eq!(
            raw.len(),
            1 + COMBINED_CT_768_LEN + NONCE_LEN + 32 + MAC_LEN
        );
    }

    // === Cat-1 (new) ===

    #[test]
    fn cat1_roundtrip() {
        let kp = generate_hybrid_keypair_512();
        let pt = b"32-byte symmetric context key!!!";
        let ct = hybrid_seal_512(pt, &kp.public_key).unwrap();
        assert!(is_hybrid_ciphertext(&ct));
        let opened = hybrid_open(&ct, &kp.secret_key).unwrap();
        assert_eq!(opened, pt);
    }

    #[test]
    fn cat1_version_tag() {
        let kp = generate_hybrid_keypair_512();
        let raw = b64::decode(&hybrid_seal_512(b"x", &kp.public_key).unwrap()).unwrap();
        assert_eq!(raw[0], VERSION_HYBRID_512);
    }

    #[test]
    fn cat1_wrong_key_fails() {
        let kp1 = generate_hybrid_keypair_512();
        let kp2 = generate_hybrid_keypair_512();
        let ct = hybrid_seal_512(b"x", &kp1.public_key).unwrap();
        assert!(hybrid_open(&ct, &kp2.secret_key).is_err());
    }

    #[test]
    fn cat1_key_sizes() {
        let kp = generate_hybrid_keypair_512();
        let pk = b64::decode(&kp.public_key).unwrap();
        let sk = b64::decode(&kp.secret_key).unwrap();
        assert_eq!(pk.len(), COMBINED_PK_512_LEN); // 832
        assert_eq!(sk.len(), SEED_LEN); // 32
    }

    #[test]
    fn cat1_ciphertext_size() {
        let kp = generate_hybrid_keypair_512();
        let pt = b"exactly 32 bytes of key material";
        let raw = b64::decode(&hybrid_seal_512(pt, &kp.public_key).unwrap()).unwrap();
        // 1 + 800 + 24 + 32 + 16 = 873
        assert_eq!(
            raw.len(),
            1 + COMBINED_CT_512_LEN + NONCE_LEN + 32 + MAC_LEN
        );
    }

    #[test]
    fn cat1_nondeterministic() {
        let kp = generate_hybrid_keypair_512();
        let c1 = hybrid_seal_512(b"x", &kp.public_key).unwrap();
        let c2 = hybrid_seal_512(b"x", &kp.public_key).unwrap();
        assert_ne!(c1, c2);
    }

    #[test]
    fn cat1_empty_plaintext() {
        let kp = generate_hybrid_keypair_512();
        let ct = hybrid_seal_512(b"", &kp.public_key).unwrap();
        assert_eq!(hybrid_open(&ct, &kp.secret_key).unwrap(), b"");
    }

    // === Cat-5 (new) ===

    #[test]
    fn cat5_roundtrip() {
        let kp = generate_hybrid_keypair_1024();
        let pt = b"32-byte symmetric context key!!!";
        let ct = hybrid_seal_1024(pt, &kp.public_key).unwrap();
        assert!(is_hybrid_ciphertext(&ct));
        let opened = hybrid_open(&ct, &kp.secret_key).unwrap();
        assert_eq!(opened, pt);
    }

    #[test]
    fn cat5_version_tag() {
        let kp = generate_hybrid_keypair_1024();
        let raw = b64::decode(&hybrid_seal_1024(b"x", &kp.public_key).unwrap()).unwrap();
        assert_eq!(raw[0], VERSION_HYBRID_1024);
    }

    #[test]
    fn cat5_wrong_key_fails() {
        let kp1 = generate_hybrid_keypair_1024();
        let kp2 = generate_hybrid_keypair_1024();
        let ct = hybrid_seal_1024(b"x", &kp1.public_key).unwrap();
        assert!(hybrid_open(&ct, &kp2.secret_key).is_err());
    }

    #[test]
    fn cat5_key_sizes() {
        let kp = generate_hybrid_keypair_1024();
        let pk = b64::decode(&kp.public_key).unwrap();
        let sk = b64::decode(&kp.secret_key).unwrap();
        assert_eq!(pk.len(), COMBINED_PK_1024_LEN); // 1600
        assert_eq!(sk.len(), SEED_LEN); // 32
    }

    #[test]
    fn cat5_ciphertext_size() {
        let kp = generate_hybrid_keypair_1024();
        let pt = b"exactly 32 bytes of key material";
        let raw = b64::decode(&hybrid_seal_1024(pt, &kp.public_key).unwrap()).unwrap();
        // 1 + 1600 + 24 + 32 + 16 = 1673
        assert_eq!(
            raw.len(),
            1 + COMBINED_CT_1024_LEN + NONCE_LEN + 32 + MAC_LEN
        );
    }

    #[test]
    fn cat5_nondeterministic() {
        let kp = generate_hybrid_keypair_1024();
        let c1 = hybrid_seal_1024(b"x", &kp.public_key).unwrap();
        let c2 = hybrid_seal_1024(b"x", &kp.public_key).unwrap();
        assert_ne!(c1, c2);
    }

    #[test]
    fn cat5_empty_plaintext() {
        let kp = generate_hybrid_keypair_1024();
        let ct = hybrid_seal_1024(b"", &kp.public_key).unwrap();
        assert_eq!(hybrid_open(&ct, &kp.secret_key).unwrap(), b"");
    }

    // === Cross-level ===

    #[test]
    fn cat3_ct_cannot_open_with_cat5_key() {
        let kp3 = generate_hybrid_keypair();
        let kp5 = generate_hybrid_keypair_1024();
        let ct = hybrid_seal(b"test", &kp3.public_key).unwrap();
        assert!(hybrid_open(&ct, &kp5.secret_key).is_err());
    }

    #[test]
    fn cat5_ct_cannot_open_with_cat3_key() {
        let kp3 = generate_hybrid_keypair();
        let kp5 = generate_hybrid_keypair_1024();
        let ct = hybrid_seal_1024(b"test", &kp5.public_key).unwrap();
        assert!(hybrid_open(&ct, &kp3.secret_key).is_err());
    }

    #[test]
    fn cat1_ct_cannot_open_with_cat3_key() {
        let kp1 = generate_hybrid_keypair_512();
        let kp3 = generate_hybrid_keypair();
        let ct = hybrid_seal_512(b"test", &kp1.public_key).unwrap();
        assert!(hybrid_open(&ct, &kp3.secret_key).is_err());
    }

    #[test]
    fn cat1_ct_cannot_open_with_cat5_key() {
        let kp1 = generate_hybrid_keypair_512();
        let kp5 = generate_hybrid_keypair_1024();
        let ct = hybrid_seal_512(b"test", &kp1.public_key).unwrap();
        assert!(hybrid_open(&ct, &kp5.secret_key).is_err());
    }

    #[test]
    fn legacy_not_hybrid() {
        // A short blob whose first byte is not any hybrid tag.
        let legacy = b64::encode(&[0x42, 0x02, 0x03]);
        assert!(!is_hybrid_ciphertext(&legacy));
    }

    #[test]
    fn legacy_starting_with_0x01_not_misdetected_as_cat1() {
        // `is_hybrid_ciphertext` is length-aware: a legacy-sized (~80B) blob whose
        // first byte collides with the Cat-1 tag (0x01) is NOT classified as
        // hybrid, because it is far below the Cat-1 minimum length
        // (1 + 768 + 32 + 24 + 16 = 841B). In practice Mosslet legacy cts (~80B
        // sealing a 32B key) can never reach a hybrid length.
        let mut legacy = vec![0x01u8]; // collides with the Cat-1 tag
        legacy.extend_from_slice(&[0u8; 79]); // total 80 bytes, legacy-sized
        let legacy_b64 = b64::encode(&legacy);
        assert!(!is_hybrid_ciphertext(&legacy_b64));
        // And `hybrid_open`'s own length gate independently rejects it.
        let kp = generate_hybrid_keypair_512();
        let err = hybrid_open(&legacy_b64, &kp.secret_key).unwrap_err();
        assert!(matches!(err, CryptoError::TooShort));
    }

    #[test]
    fn long_0x01_blob_below_cat1_min_not_hybrid() {
        // A 0x01-leading blob just under the Cat-1 minimum is still not hybrid.
        let min_cat1 = MIN_HYBRID_512_LEN; // 841
        let mut blob = vec![0x01u8];
        blob.extend_from_slice(&vec![0u8; min_cat1 - 2]); // total = min - 1
        assert!(!is_hybrid_ciphertext(&b64::encode(&blob)));
        // At exactly the minimum, the tag+length check classifies it as hybrid
        // (disambiguation past this point is handled by unseal_from_user's
        // fallback to the legacy opener).
        let mut at_min = vec![0x01u8];
        at_min.extend_from_slice(&vec![0u8; min_cat1 - 1]); // total = min
        assert!(is_hybrid_ciphertext(&b64::encode(&at_min)));
    }

    #[test]
    fn seed_expansion_deterministic() {
        let seed = [0x42u8; SEED_LEN];
        let expanded = expand_seed(&seed, 96);
        let expanded2 = expand_seed(&seed, 96);
        assert_eq!(expanded, expanded2);
    }

    #[test]
    fn combiner_uses_label() {
        let ss_mlkem = [0xAAu8; 32];
        let ss_x25519 = [0xBBu8; 32];
        let ct_x25519 = [0xCCu8; 32];
        let pk_x25519 = [0xDDu8; 32];
        let result = combine(&ss_mlkem, &ss_x25519, &ct_x25519, &pk_x25519);
        assert_eq!(result.len(), 32);

        let ss_mlkem2 = [0xEEu8; 32];
        let result2 = combine(&ss_mlkem2, &ss_x25519, &ct_x25519, &pk_x25519);
        assert_ne!(result, result2);
    }
}