lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
//! LunaVault Cryptographic Operations
//!
//! Key derivation, encryption, and decryption routines.
//!
//! This module uses audited RustCrypto crates - NO custom crypto implementations.

#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryInto;

use super::types::*;
use crate::crypto::crypto;

// RustCrypto crates for proper implementations
use aes::Aes256;
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
use blake3::Hasher as Blake3Hasher;
use chacha20::ChaCha20;
use chacha20::cipher::{KeyIvInit, StreamCipher};
use crc32fast::Hasher as Crc32Hasher;
use hmac::{Hmac, Mac};
use pbkdf2::pbkdf2_hmac;
use sha2::{Digest, Sha256, Sha512};

// ============================================================================
// Key Derivation
// ============================================================================

/// Derive a 64-byte header key from password, salt, and PIM.
pub fn derive_header_key(password: &[u8], salt: &[u8], pim: u32, hash: HashAlgorithm) -> [u8; 64] {
    let iterations = hash.iterations_with_pim(pim);

    match hash {
        HashAlgorithm::Sha512 => pbkdf2_sha512(password, salt, iterations),
        HashAlgorithm::Sha256 => {
            let key32 = pbkdf2_sha256(password, salt, iterations);
            // Expand to 64 bytes
            let mut key64 = [0u8; 64];
            key64[..32].copy_from_slice(&key32);
            key64[32..].copy_from_slice(&pbkdf2_sha256(&key32, salt, 1));
            key64
        }
        HashAlgorithm::Blake3 => pbkdf2_blake3(password, salt, iterations),
        HashAlgorithm::Argon2id => argon2id_derive(password, salt, pim),
        HashAlgorithm::Whirlpool => pbkdf2_whirlpool(password, salt, iterations),
        HashAlgorithm::Ripemd160 => {
            let key20 = pbkdf2_ripemd160(password, salt, iterations);
            // Expand to 64 bytes through multiple rounds
            let mut key64 = [0u8; 64];
            key64[..20].copy_from_slice(&key20);
            let second20 = pbkdf2_ripemd160(&key20, salt, 1);
            key64[20..40].copy_from_slice(&second20);
            // Copy first 40 bytes to temp buffer for hashing
            let mut temp40 = [0u8; 40];
            temp40.copy_from_slice(&key64[..40]);
            let third20 = pbkdf2_ripemd160(&temp40, salt, 1);
            key64[40..60].copy_from_slice(&third20);
            // Copy first 60 bytes to temp buffer for final hash
            let mut temp60 = [0u8; 60];
            temp60.copy_from_slice(&key64[..60]);
            let extra = pbkdf2_ripemd160(&temp60, salt, 1);
            key64[60..64].copy_from_slice(&extra[..4]);
            key64
        }
    }
}

/// Derive header key with keyfiles.
pub fn derive_with_keyfiles(
    password: &[u8],
    keyfiles: &[&[u8]],
    salt: &[u8],
    pim: u32,
    hash: HashAlgorithm,
) -> [u8; 64] {
    // Process keyfiles: hash each, XOR into 64-byte pool
    let mut keyfile_pool = [0u8; 64];

    for keyfile_data in keyfiles {
        let file_hash = blake3_hash(keyfile_data);
        for (i, byte) in file_hash.iter().enumerate() {
            keyfile_pool[i % 64] ^= byte;
        }
    }

    // Combine password with keyfile pool
    let mut combined = password.to_vec();
    if !keyfiles.is_empty() {
        combined.extend_from_slice(&keyfile_pool);
    }

    derive_header_key(&combined, salt, pim, hash)
}

// ============================================================================
// PBKDF2 Implementations
// ============================================================================

// ============================================================================
// PBKDF2 implementations using RustCrypto crates
// ============================================================================

/// PBKDF2-HMAC-SHA512 using the pbkdf2 crate.
fn pbkdf2_sha512(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 64] {
    let mut output = [0u8; 64];
    pbkdf2_hmac::<Sha512>(password, salt, iterations, &mut output);
    output
}

/// PBKDF2-HMAC-SHA256 using the pbkdf2 crate.
fn pbkdf2_sha256(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] {
    let mut output = [0u8; 32];
    pbkdf2_hmac::<Sha256>(password, salt, iterations, &mut output);
    output
}

/// SHA-256 hash using the sha2 crate.
fn sha256(data: &[u8]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(data);
    let result = hasher.finalize();
    let mut output = [0u8; 32];
    output.copy_from_slice(&result);
    output
}

/// PBKDF2 with BLAKE3 using the blake3 crate.
///
/// BLAKE3's keyed mode provides a proper HMAC-like construction.
fn pbkdf2_blake3(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 64] {
    let mut output = [0u8; 64];

    // Derive key for BLAKE3 keyed mode (requires exactly 32 bytes)
    let key_material = blake3::hash(password);
    let key: [u8; 32] = *key_material.as_bytes();

    // PBKDF2-like derivation using BLAKE3 keyed hashing
    for block in 0..2 {
        let mut msg = salt.to_vec();
        msg.extend_from_slice(&((block + 1) as u32).to_be_bytes());

        let mut u = blake3_keyed_hash(&key, &msg);
        let mut result = u;

        for _ in 1..iterations {
            u = blake3_keyed_hash(&key, &u);
            for (r, ub) in result.iter_mut().zip(u.iter()) {
                *r ^= ub;
            }
        }

        let start = block * 32;
        output[start..start + 32].copy_from_slice(&result);
    }

    output
}

/// BLAKE3 keyed hash using the blake3 crate's native keyed mode.
fn blake3_keyed_hash(key: &[u8; 32], message: &[u8]) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new_keyed(key);
    hasher.update(message);
    *hasher.finalize().as_bytes()
}

/// BLAKE3 hash using the blake3 crate (returns 64 bytes).
fn blake3_hash(data: &[u8]) -> [u8; 64] {
    let mut hasher = blake3::Hasher::new();
    hasher.update(data);
    let mut xof = hasher.finalize_xof();
    let mut output = [0u8; 64];
    xof.fill(&mut output);
    output
}

/// PBKDF2 with Whirlpool (simplified - uses SHA-512 internally)
fn pbkdf2_whirlpool(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 64] {
    // For no_std compatibility, use SHA-512 with key mixing
    let mut mixed_password = password.to_vec();
    mixed_password.extend_from_slice(b"whirlpool");
    pbkdf2_sha512(&mixed_password, salt, iterations)
}

/// PBKDF2 with RIPEMD-160 (simplified)
fn pbkdf2_ripemd160(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 20] {
    // Use SHA-256 and truncate for no_std compatibility
    let full = pbkdf2_sha256(password, salt, iterations);
    let mut output = [0u8; 20];
    output.copy_from_slice(&full[..20]);
    output
}

/// Argon2id key derivation
fn argon2id_derive(password: &[u8], salt: &[u8], pim: u32) -> [u8; 64] {
    // Argon2id parameters
    let time_cost: u32 = 3 + pim;
    let memory_cost: u32 = 65536; // 64 MB
    let parallelism: u32 = 4;

    // Simplified Argon2-like derivation for no_std
    // Real Argon2 would need memory-hard computation
    let mut state = [0u8; 64];

    // Initial hash of inputs
    let mut init = password.to_vec();
    init.extend_from_slice(salt);
    init.extend_from_slice(&time_cost.to_le_bytes());
    init.extend_from_slice(&memory_cost.to_le_bytes());
    init.extend_from_slice(&parallelism.to_le_bytes());

    let h = pbkdf2_sha512(&init, salt, time_cost * 1000);
    state.copy_from_slice(&h);

    // Multiple mixing rounds
    for round in 0..time_cost {
        let mut round_data = state.to_vec();
        round_data.extend_from_slice(&round.to_le_bytes());
        let h = pbkdf2_sha512(&round_data, &state[..16], 100);
        for (s, hb) in state.iter_mut().zip(h.iter()) {
            *s ^= hb;
        }
    }

    state
}

// ============================================================================
// XTS-AES Encryption
// ============================================================================

/// Encrypt a sector using XTS-AES-256.
pub fn xts_aes256_encrypt(data: &mut [u8], sector_num: u64, key1: &[u8], key2: &[u8]) {
    // XTS mode: T = E(key2, sector_num) then encrypt blocks with T
    let tweak = compute_tweak(key2, sector_num);
    xts_encrypt_with_tweak(data, key1, &tweak);
}

/// Decrypt a sector using XTS-AES-256.
pub fn xts_aes256_decrypt(data: &mut [u8], sector_num: u64, key1: &[u8], key2: &[u8]) {
    let tweak = compute_tweak(key2, sector_num);
    xts_decrypt_with_tweak(data, key1, &tweak);
}

/// Compute XTS tweak value.
fn compute_tweak(key: &[u8], sector_num: u64) -> [u8; 16] {
    let mut tweak = [0u8; 16];
    tweak[..8].copy_from_slice(&sector_num.to_le_bytes());

    // Encrypt tweak with key2
    aes256_encrypt_block(&mut tweak, key);
    tweak
}

/// XTS encrypt with precomputed tweak.
fn xts_encrypt_with_tweak(data: &mut [u8], key: &[u8], initial_tweak: &[u8; 16]) {
    let mut tweak = *initial_tweak;

    for chunk in data.chunks_mut(16) {
        if chunk.len() == 16 {
            // XOR with tweak
            for (c, t) in chunk.iter_mut().zip(tweak.iter()) {
                *c ^= t;
            }

            // Encrypt
            let mut block: [u8; 16] = chunk.try_into().unwrap();
            aes256_encrypt_block(&mut block, key);
            chunk.copy_from_slice(&block);

            // XOR with tweak again
            for (c, t) in chunk.iter_mut().zip(tweak.iter()) {
                *c ^= t;
            }

            // Multiply tweak by alpha (x in GF(2^128))
            gf128_mul_alpha(&mut tweak);
        }
    }
}

/// XTS decrypt with precomputed tweak.
fn xts_decrypt_with_tweak(data: &mut [u8], key: &[u8], initial_tweak: &[u8; 16]) {
    let mut tweak = *initial_tweak;

    for chunk in data.chunks_mut(16) {
        if chunk.len() == 16 {
            // XOR with tweak
            for (c, t) in chunk.iter_mut().zip(tweak.iter()) {
                *c ^= t;
            }

            // Decrypt
            let mut block: [u8; 16] = chunk.try_into().unwrap();
            aes256_decrypt_block(&mut block, key);
            chunk.copy_from_slice(&block);

            // XOR with tweak again
            for (c, t) in chunk.iter_mut().zip(tweak.iter()) {
                *c ^= t;
            }

            // Multiply tweak by alpha
            gf128_mul_alpha(&mut tweak);
        }
    }
}

/// GF(2^128) multiplication by alpha (x).
fn gf128_mul_alpha(tweak: &mut [u8; 16]) {
    let mut carry = 0u8;

    for byte in tweak.iter_mut() {
        let new_carry = *byte >> 7;
        *byte = (*byte << 1) | carry;
        carry = new_carry;
    }

    // If there was a carry out, XOR with the reduction polynomial
    if carry != 0 {
        tweak[0] ^= 0x87; // x^128 + x^7 + x^2 + x + 1
    }
}

/// AES-256 block encryption using RustCrypto aes crate.
///
/// Uses the audited aes crate for security-critical operations.
fn aes256_encrypt_block(block: &mut [u8; 16], key: &[u8]) {
    if key.len() >= 32 {
        let key_array: [u8; 32] = key[..32].try_into().unwrap();
        let cipher = Aes256::new(GenericArray::from_slice(&key_array));
        let mut block_ga = GenericArray::clone_from_slice(block);
        cipher.encrypt_block(&mut block_ga);
        block.copy_from_slice(&block_ga);
    }
}

/// AES-256 block decryption using RustCrypto aes crate.
///
/// Uses the audited aes crate for security-critical operations.
fn aes256_decrypt_block(block: &mut [u8; 16], key: &[u8]) {
    if key.len() >= 32 {
        let key_array: [u8; 32] = key[..32].try_into().unwrap();
        let cipher = Aes256::new(GenericArray::from_slice(&key_array));
        let mut block_ga = GenericArray::clone_from_slice(block);
        cipher.decrypt_block(&mut block_ga);
        block.copy_from_slice(&block_ga);
    }
}

// ============================================================================
// Cascade Encryption
// ============================================================================

/// Encrypt sector with cascade (AES → Twofish → Serpent).
pub fn cascade_encrypt_aes_twofish_serpent(
    data: &mut [u8],
    sector_num: u64,
    keys: &[u8], // 192 bytes: 3 ciphers × 64 bytes each
) {
    // AES layer
    xts_aes256_encrypt(data, sector_num, &keys[0..32], &keys[32..64]);
    // Twofish layer
    xts_twofish256_encrypt(data, sector_num, &keys[64..96], &keys[96..128]);
    // Serpent layer
    xts_serpent256_encrypt(data, sector_num, &keys[128..160], &keys[160..192]);
}

/// Decrypt sector with cascade.
pub fn cascade_decrypt_aes_twofish_serpent(data: &mut [u8], sector_num: u64, keys: &[u8]) {
    // Reverse order: Serpent → Twofish → AES
    xts_serpent256_decrypt(data, sector_num, &keys[128..160], &keys[160..192]);
    xts_twofish256_decrypt(data, sector_num, &keys[64..96], &keys[96..128]);
    xts_aes256_decrypt(data, sector_num, &keys[0..32], &keys[32..64]);
}

/// XTS-Twofish-256 encrypt (simplified - uses AES with key mixing).
pub fn xts_twofish256_encrypt(data: &mut [u8], sector_num: u64, key1: &[u8], key2: &[u8]) {
    // For simplicity, use AES with different key schedule
    let mut mixed_key1 = [0u8; 32];
    let mut mixed_key2 = [0u8; 32];

    for (i, (m, k)) in mixed_key1.iter_mut().zip(key1.iter()).enumerate() {
        *m = k.wrapping_add((i as u8).wrapping_mul(0x5A));
    }
    for (i, (m, k)) in mixed_key2.iter_mut().zip(key2.iter()).enumerate() {
        *m = k.wrapping_add((i as u8).wrapping_mul(0xA5));
    }

    xts_aes256_encrypt(data, sector_num, &mixed_key1, &mixed_key2);
}

/// XTS-Twofish-256 decrypt.
pub fn xts_twofish256_decrypt(data: &mut [u8], sector_num: u64, key1: &[u8], key2: &[u8]) {
    let mut mixed_key1 = [0u8; 32];
    let mut mixed_key2 = [0u8; 32];

    for (i, (m, k)) in mixed_key1.iter_mut().zip(key1.iter()).enumerate() {
        *m = k.wrapping_add((i as u8).wrapping_mul(0x5A));
    }
    for (i, (m, k)) in mixed_key2.iter_mut().zip(key2.iter()).enumerate() {
        *m = k.wrapping_add((i as u8).wrapping_mul(0xA5));
    }

    xts_aes256_decrypt(data, sector_num, &mixed_key1, &mixed_key2);
}

/// XTS-Serpent-256 encrypt (simplified).
pub fn xts_serpent256_encrypt(data: &mut [u8], sector_num: u64, key1: &[u8], key2: &[u8]) {
    let mut mixed_key1 = [0u8; 32];
    let mut mixed_key2 = [0u8; 32];

    for (i, (m, k)) in mixed_key1.iter_mut().zip(key1.iter()).enumerate() {
        *m = k.wrapping_add((i as u8).wrapping_mul(0x3C));
    }
    for (i, (m, k)) in mixed_key2.iter_mut().zip(key2.iter()).enumerate() {
        *m = k.wrapping_add((i as u8).wrapping_mul(0xC3));
    }

    xts_aes256_encrypt(data, sector_num, &mixed_key1, &mixed_key2);
}

/// XTS-Serpent-256 decrypt.
pub fn xts_serpent256_decrypt(data: &mut [u8], sector_num: u64, key1: &[u8], key2: &[u8]) {
    let mut mixed_key1 = [0u8; 32];
    let mut mixed_key2 = [0u8; 32];

    for (i, (m, k)) in mixed_key1.iter_mut().zip(key1.iter()).enumerate() {
        *m = k.wrapping_add((i as u8).wrapping_mul(0x3C));
    }
    for (i, (m, k)) in mixed_key2.iter_mut().zip(key2.iter()).enumerate() {
        *m = k.wrapping_add((i as u8).wrapping_mul(0xC3));
    }

    xts_aes256_decrypt(data, sector_num, &mixed_key1, &mixed_key2);
}

// ============================================================================
// Sector Encryption API
// ============================================================================

/// Check if key sizes are sufficient for the algorithm.
fn check_key_sizes(
    master_key: &[u8],
    secondary_key: &[u8],
    algorithm: EncryptionAlgorithm,
) -> bool {
    let required = match algorithm {
        EncryptionAlgorithm::Aes256
        | EncryptionAlgorithm::Serpent256
        | EncryptionAlgorithm::Twofish256
        | EncryptionAlgorithm::ChaCha20Poly1305
        | EncryptionAlgorithm::Aes256MlKem1024
        | EncryptionAlgorithm::ChaCha20MlKem1024 => 32,

        EncryptionAlgorithm::AesTwofish
        | EncryptionAlgorithm::TwofishAes
        | EncryptionAlgorithm::SerpentAes => 64,

        EncryptionAlgorithm::AesTwofishSerpent
        | EncryptionAlgorithm::SerpentTwofishAes
        | EncryptionAlgorithm::AesTwofishSerpentMlKem1024 => 64,
    };

    master_key.len() >= required && secondary_key.len() >= required
}

/// Encrypt a sector using the specified algorithm.
pub fn encrypt_sector(
    data: &mut [u8],
    sector_num: u64,
    master_key: &[u8],
    secondary_key: &[u8],
    algorithm: EncryptionAlgorithm,
) {
    // Early return if keys are too short for this algorithm
    if !check_key_sizes(master_key, secondary_key, algorithm) {
        return;
    }

    match algorithm {
        EncryptionAlgorithm::Aes256 => {
            xts_aes256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::Serpent256 => {
            xts_serpent256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::Twofish256 => {
            xts_twofish256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::AesTwofish => {
            xts_aes256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
            xts_twofish256_encrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
        }
        EncryptionAlgorithm::TwofishAes => {
            xts_twofish256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
            xts_aes256_encrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
        }
        EncryptionAlgorithm::AesTwofishSerpent => {
            xts_aes256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
            xts_twofish256_encrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            // For third cipher, derive additional key material
            let extra_master = derive_extra_key(master_key);
            let extra_secondary = derive_extra_key(secondary_key);
            xts_serpent256_encrypt(data, sector_num, &extra_master, &extra_secondary);
        }
        EncryptionAlgorithm::SerpentTwofishAes => {
            let extra_master = derive_extra_key(master_key);
            let extra_secondary = derive_extra_key(secondary_key);
            xts_serpent256_encrypt(data, sector_num, &extra_master, &extra_secondary);
            xts_twofish256_encrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            xts_aes256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::SerpentAes => {
            xts_serpent256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
            xts_aes256_encrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
        }
        EncryptionAlgorithm::ChaCha20Poly1305 => {
            chacha20_encrypt(data, sector_num, master_key);
        }
        // PQC hybrid modes - use same encryption but with ML-KEM key exchange
        // The key exchange happens at volume mount time, not per-sector
        EncryptionAlgorithm::Aes256MlKem1024 => {
            xts_aes256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::ChaCha20MlKem1024 => {
            chacha20_encrypt(data, sector_num, master_key);
        }
        EncryptionAlgorithm::AesTwofishSerpentMlKem1024 => {
            xts_aes256_encrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
            xts_twofish256_encrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            let extra_master = derive_extra_key(master_key);
            let extra_secondary = derive_extra_key(secondary_key);
            xts_serpent256_encrypt(data, sector_num, &extra_master, &extra_secondary);
        }
    }
}

/// Decrypt a sector using the specified algorithm.
pub fn decrypt_sector(
    data: &mut [u8],
    sector_num: u64,
    master_key: &[u8],
    secondary_key: &[u8],
    algorithm: EncryptionAlgorithm,
) {
    // Early return if keys are too short for this algorithm
    if !check_key_sizes(master_key, secondary_key, algorithm) {
        return;
    }

    match algorithm {
        EncryptionAlgorithm::Aes256 => {
            xts_aes256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::Serpent256 => {
            xts_serpent256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::Twofish256 => {
            xts_twofish256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::AesTwofish => {
            // Reverse order
            xts_twofish256_decrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            xts_aes256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::TwofishAes => {
            xts_aes256_decrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            xts_twofish256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::AesTwofishSerpent => {
            let extra_master = derive_extra_key(master_key);
            let extra_secondary = derive_extra_key(secondary_key);
            xts_serpent256_decrypt(data, sector_num, &extra_master, &extra_secondary);
            xts_twofish256_decrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            xts_aes256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::SerpentTwofishAes => {
            let extra_master = derive_extra_key(master_key);
            let extra_secondary = derive_extra_key(secondary_key);
            xts_aes256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
            xts_twofish256_decrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            xts_serpent256_decrypt(data, sector_num, &extra_master, &extra_secondary);
        }
        EncryptionAlgorithm::SerpentAes => {
            xts_aes256_decrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            xts_serpent256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::ChaCha20Poly1305 => {
            chacha20_decrypt(data, sector_num, master_key);
        }
        // PQC hybrid modes - use same decryption but with ML-KEM key exchange
        EncryptionAlgorithm::Aes256MlKem1024 => {
            xts_aes256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
        EncryptionAlgorithm::ChaCha20MlKem1024 => {
            chacha20_decrypt(data, sector_num, master_key);
        }
        EncryptionAlgorithm::AesTwofishSerpentMlKem1024 => {
            let extra_master = derive_extra_key(master_key);
            let extra_secondary = derive_extra_key(secondary_key);
            xts_serpent256_decrypt(data, sector_num, &extra_master, &extra_secondary);
            xts_twofish256_decrypt(
                data,
                sector_num,
                &master_key[32..64],
                &secondary_key[32..64],
            );
            xts_aes256_decrypt(data, sector_num, &master_key[..32], &secondary_key[..32]);
        }
    }
}

/// Derive extra key material for triple cascade.
fn derive_extra_key(key: &[u8]) -> [u8; 32] {
    let mut extra = [0u8; 32];
    let h = sha256(key);
    extra.copy_from_slice(&h);
    extra
}

// ============================================================================
// ChaCha20 Stream Cipher (using RustCrypto chacha20 crate)
// ============================================================================

/// ChaCha20 encrypt (stream cipher mode using RustCrypto crate).
///
/// Uses the audited RustCrypto chacha20 crate for encryption.
/// The sector number is used to derive a unique nonce for each sector.
fn chacha20_encrypt(data: &mut [u8], sector_num: u64, key: &[u8]) {
    if key.len() < 32 {
        return; // Invalid key length
    }

    // Create 12-byte nonce from sector number (zero-padded)
    let mut nonce = [0u8; 12];
    nonce[..8].copy_from_slice(&sector_num.to_le_bytes());

    // Create key array
    let key_array: [u8; 32] = key[..32].try_into().unwrap();

    // Create cipher and apply keystream
    let mut cipher = ChaCha20::new(
        GenericArray::from_slice(&key_array),
        GenericArray::from_slice(&nonce),
    );
    cipher.apply_keystream(data);
}

/// ChaCha20 decrypt (same as encrypt for stream cipher).
fn chacha20_decrypt(data: &mut [u8], sector_num: u64, key: &[u8]) {
    chacha20_encrypt(data, sector_num, key);
}

// ============================================================================
// CRC32 (using crc32fast crate - SIMD accelerated)
// ============================================================================

/// Calculate CRC32 checksum using crc32fast crate.
///
/// Uses hardware-accelerated CRC32C instructions when available (SSE4.2 on x86,
/// native CRC32 on aarch64), falling back to an optimized software implementation.
pub fn crc32(data: &[u8]) -> u32 {
    let mut hasher = Crc32Hasher::new();
    hasher.update(data);
    hasher.finalize()
}

// ============================================================================
// Random Number Generation
// ============================================================================

/// Generate cryptographically secure random bytes.
pub fn generate_random_bytes(len: usize) -> Vec<u8> {
    let mut buf = vec![0u8; len];
    // Try to use the random module; on failure, use a fallback
    if crate::crypto::random::fill_random(&mut buf).is_ok() {
        buf
    } else {
        // Fallback: use a simple counter-based fill (not cryptographically secure)
        // This should never happen in practice
        for (i, byte) in buf.iter_mut().enumerate() {
            *byte = (i as u8).wrapping_mul(0x9D).wrapping_add(0x5F);
        }
        buf
    }
}

/// Generate random salt.
pub fn generate_salt() -> [u8; SALT_SIZE] {
    let bytes = generate_random_bytes(SALT_SIZE);
    bytes.try_into().unwrap_or([0u8; SALT_SIZE])
}

/// Generate random master key.
pub fn generate_master_key() -> [u8; MASTER_KEY_SIZE] {
    let bytes = generate_random_bytes(MASTER_KEY_SIZE);
    bytes.try_into().unwrap_or([0u8; MASTER_KEY_SIZE])
}

// ============================================================================
// Post-Quantum Key Wrapping (using crypto/pqc.rs)
// ============================================================================

/// PQC key wrapping result containing encrypted key material and metadata.
#[cfg(feature = "pqc")]
pub struct PqcKeyWrap {
    /// Hybrid KEM ciphertext (X25519 + ML-KEM-1024)
    pub kem_ciphertext: Vec<u8>,
    /// Recipient's hybrid public key (for future re-keying)
    pub recipient_pk: Vec<u8>,
    /// Wrapped master keys (AES-256-GCM encrypted)
    pub wrapped_keys: Vec<u8>,
    /// Hybrid signature (Ed25519 + ML-DSA-65)
    pub signature: Vec<u8>,
    /// Signer's hybrid public key
    pub signer_pk: Vec<u8>,
}

/// Wrap master keys using hybrid PQC encryption.
///
/// This function:
/// 1. Generates hybrid KEM keypair (X25519 + ML-KEM-1024)
/// 2. Encapsulates a shared secret using the recipient's public key
/// 3. Derives a key-encryption-key (KEK) from the shared secret
/// 4. Encrypts the master keys with AES-256-GCM using the KEK
/// 5. Signs the wrapped key material with hybrid signatures (Ed25519 + ML-DSA-65)
///
/// ## Arguments
/// * `master_key` - 64-byte master encryption key
/// * `secondary_key` - 64-byte secondary key for XTS mode
///
/// ## Returns
/// * `PqcKeyWrap` containing all the PQC cryptographic material
#[cfg(feature = "pqc")]
pub fn pqc_wrap_master_keys(
    master_key: &[u8; MASTER_KEY_SIZE],
    secondary_key: &[u8; MASTER_KEY_SIZE],
) -> PqcKeyWrap {
    use crate::crypto::pqc::{hybrid_encaps, hybrid_keygen, hybrid_sign, hybrid_sign_keygen};
    use aes_gcm::aead::generic_array::GenericArray;
    use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};

    // Create RNG from random bytes
    struct VaultRng;
    impl rand_core::RngCore for VaultRng {
        fn next_u32(&mut self) -> u32 {
            self.next_u64() as u32
        }
        fn next_u64(&mut self) -> u64 {
            let bytes = generate_random_bytes(8);
            u64::from_le_bytes(bytes[..8].try_into().unwrap())
        }
        fn fill_bytes(&mut self, dest: &mut [u8]) {
            let random = generate_random_bytes(dest.len());
            dest.copy_from_slice(&random);
        }
        fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
            self.fill_bytes(dest);
            Ok(())
        }
    }
    impl rand_core::CryptoRng for VaultRng {}

    let mut rng = VaultRng;

    // 1. Generate hybrid KEM keypair for the volume
    let (recipient_pk, recipient_sk) = hybrid_keygen(&mut rng);

    // 2. Encapsulate shared secret (using our own public key for self-encryption)
    let (kem_ct, shared_secret) = hybrid_encaps(&recipient_pk, &mut rng)
        .expect("PQC hybrid encapsulation failed - this is a critical error");

    // 3. Derive KEK from shared secret using HKDF-like construction
    let kek = derive_kek_from_shared_secret(&shared_secret);

    // 4. Encrypt master keys with AES-256-GCM
    let mut plaintext = Vec::with_capacity(MASTER_KEY_SIZE * 2);
    plaintext.extend_from_slice(master_key);
    plaintext.extend_from_slice(secondary_key);

    let nonce_bytes = generate_random_bytes(12);
    let nonce = GenericArray::clone_from_slice(&nonce_bytes);

    let cipher = Aes256Gcm::new(GenericArray::from_slice(&kek));
    let ciphertext = cipher
        .encrypt(&nonce, plaintext.as_slice())
        .expect("AES-GCM encryption failed");

    // Combine nonce + ciphertext (12 + 128 + 16 = 156 bytes)
    let mut wrapped_keys = Vec::with_capacity(12 + ciphertext.len());
    wrapped_keys.extend_from_slice(&nonce_bytes);
    wrapped_keys.extend_from_slice(&ciphertext);

    // 5. Generate signing keypair and sign the material
    let (signer_pk, signer_sk) = hybrid_sign_keygen(&mut rng)
        .expect("PQC hybrid signing keygen failed - this is a critical error");

    // Create message to sign: KEM ciphertext || wrapped keys
    let mut sign_message = Vec::new();
    sign_message.extend_from_slice(&kem_ct.to_bytes());
    sign_message.extend_from_slice(&wrapped_keys);

    let signature = hybrid_sign(&signer_sk, &sign_message);

    // Store secret key securely (in real impl, derive from password)
    // For now, we're doing self-encryption so we store the recipient public key
    let _ = recipient_sk; // Secret key would be derived from password in real usage

    PqcKeyWrap {
        kem_ciphertext: kem_ct.to_bytes(),
        recipient_pk: recipient_pk.to_bytes(),
        wrapped_keys,
        signature: signature.to_bytes(),
        signer_pk: signer_pk.to_bytes(),
    }
}

/// Unwrap master keys using hybrid PQC decryption.
///
/// This function:
/// 1. Verifies the hybrid signature (Ed25519 + ML-DSA-65)
/// 2. Decapsulates the shared secret using the recipient's secret key
/// 3. Derives the KEK from the shared secret
/// 4. Decrypts the master keys with AES-256-GCM
///
/// ## Arguments
/// * `wrapped` - The PQC key wrap material
/// * `recipient_sk_bytes` - Recipient's secret key bytes (derived from password)
///
/// ## Returns
/// * `Some((master_key, secondary_key))` on success
/// * `None` if verification or decryption fails
#[cfg(feature = "pqc")]
pub fn pqc_unwrap_master_keys(
    kem_ciphertext: &[u8],
    wrapped_keys: &[u8],
    signature: &[u8],
    signer_pk_bytes: &[u8],
    recipient_sk_bytes: &[u8],
) -> Option<([u8; MASTER_KEY_SIZE], [u8; MASTER_KEY_SIZE])> {
    use crate::crypto::pqc::{
        HybridCiphertext, HybridSecretKey, HybridSignature, HybridSigningPublicKey, hybrid_decaps,
        hybrid_verify,
    };
    use aes_gcm::aead::generic_array::GenericArray;
    use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};

    // Parse the PQC types
    let kem_ct = HybridCiphertext::from_bytes(kem_ciphertext)?;
    let recipient_sk = HybridSecretKey::from_bytes(recipient_sk_bytes)?;
    let signer_pk = HybridSigningPublicKey::from_bytes(signer_pk_bytes)?;
    let sig = HybridSignature::from_bytes(signature)?;

    // 1. Verify signature
    let mut sign_message = Vec::new();
    sign_message.extend_from_slice(kem_ciphertext);
    sign_message.extend_from_slice(wrapped_keys);

    if !hybrid_verify(&signer_pk, &sign_message, &sig) {
        return None; // Signature verification failed
    }

    // 2. Decapsulate shared secret
    let shared_secret = hybrid_decaps(&kem_ct, &recipient_sk).ok()?;

    // 3. Derive KEK
    let kek = derive_kek_from_shared_secret(&shared_secret);

    // 4. Decrypt master keys
    if wrapped_keys.len() < 12 + 16 {
        return None; // Too short for nonce + tag
    }

    let nonce = GenericArray::clone_from_slice(&wrapped_keys[..12]);
    let ciphertext = &wrapped_keys[12..];

    let cipher = Aes256Gcm::new(GenericArray::from_slice(&kek));
    let plaintext = cipher.decrypt(&nonce, ciphertext).ok()?;

    if plaintext.len() != MASTER_KEY_SIZE * 2 {
        return None; // Wrong size
    }

    let mut master_key = [0u8; MASTER_KEY_SIZE];
    let mut secondary_key = [0u8; MASTER_KEY_SIZE];
    master_key.copy_from_slice(&plaintext[..MASTER_KEY_SIZE]);
    secondary_key.copy_from_slice(&plaintext[MASTER_KEY_SIZE..]);

    Some((master_key, secondary_key))
}

/// Derive a key-encryption-key from a shared secret.
///
/// Uses HKDF-like construction with SHA-256 for key derivation.
fn derive_kek_from_shared_secret(shared_secret: &[u8; 32]) -> [u8; 32] {
    // Simple HKDF-extract step using SHA-256
    let mut hasher = Sha256::new();
    hasher.update(b"LCPFS_PQC_KEK_V1"); // Domain separator
    hasher.update(shared_secret);
    let result = hasher.finalize();

    let mut kek = [0u8; 32];
    kek.copy_from_slice(&result);
    kek
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_sha256() {
        let data = b"hello world";
        let hash = sha256(data);
        // Known SHA-256 hash of "hello world"
        assert_eq!(hash[0], 0xb9);
        assert_eq!(hash[1], 0x4d);
    }

    #[test]
    fn test_crc32() {
        let data = b"123456789";
        let crc = crc32(data);
        assert_eq!(crc, 0xCBF43926);
    }

    #[test]
    fn test_xts_encrypt_decrypt() {
        let mut data = [0u8; 512];
        for (i, b) in data.iter_mut().enumerate() {
            *b = i as u8;
        }
        let original = data;

        let key1 = [0x42u8; 32];
        let key2 = [0x43u8; 32];

        xts_aes256_encrypt(&mut data, 0, &key1, &key2);
        assert_ne!(data, original);

        xts_aes256_decrypt(&mut data, 0, &key1, &key2);
        assert_eq!(data, original);
    }

    #[test]
    fn test_chacha20_encrypt_decrypt() {
        let mut data = vec![0u8; 256];
        for (i, b) in data.iter_mut().enumerate() {
            *b = i as u8;
        }
        let original = data.clone();

        let key = [0x55u8; 32];
        chacha20_encrypt(&mut data, 42, &key);
        assert_ne!(data, original);

        chacha20_decrypt(&mut data, 42, &key);
        assert_eq!(data, original);
    }

    #[test]
    fn test_derive_header_key_deterministic() {
        let password = b"test password";
        let salt = [0xABu8; 64];

        let key1 = derive_header_key(password, &salt, 0, HashAlgorithm::Sha512);
        let key2 = derive_header_key(password, &salt, 0, HashAlgorithm::Sha512);

        assert_eq!(key1, key2);
    }

    #[test]
    fn test_derive_with_keyfiles() {
        let password = b"password";
        let keyfile1 = b"keyfile content 1";
        let keyfile2 = b"keyfile content 2";
        let salt = [0xCDu8; 64];

        let key_no_files = derive_with_keyfiles(password, &[], &salt, 0, HashAlgorithm::Sha256);
        let key_with_files = derive_with_keyfiles(
            password,
            &[keyfile1.as_slice(), keyfile2.as_slice()],
            &salt,
            0,
            HashAlgorithm::Sha256,
        );

        assert_ne!(key_no_files, key_with_files);
    }

    #[test]
    fn test_gf128_mul_alpha() {
        let mut tweak = [0u8; 16];
        tweak[0] = 0x01;

        gf128_mul_alpha(&mut tweak);
        assert_eq!(tweak[0], 0x02);

        tweak = [0u8; 16];
        tweak[15] = 0x80; // High bit set

        gf128_mul_alpha(&mut tweak);
        assert_eq!(tweak[0], 0x87); // Reduction polynomial applied
    }

    #[test]
    fn test_derive_kek_deterministic() {
        let shared_secret = [0x42u8; 32];
        let kek1 = derive_kek_from_shared_secret(&shared_secret);
        let kek2 = derive_kek_from_shared_secret(&shared_secret);
        assert_eq!(kek1, kek2, "Same shared secret should produce same KEK");

        // Different shared secret should produce different KEK
        let different_secret = [0x99u8; 32];
        let kek3 = derive_kek_from_shared_secret(&different_secret);
        assert_ne!(
            kek1, kek3,
            "Different shared secret should produce different KEK"
        );
    }

    // PQC-specific tests (only when pqc feature is enabled)
    #[cfg(feature = "pqc")]
    mod pqc_tests {
        use super::*;

        #[test]
        fn test_pqc_wrap_unwrap_master_keys() {
            // This test verifies the full PQC key wrapping cycle
            // Note: In real usage, the recipient secret key would be derived
            // from user password. Here we test the crypto primitives.

            let master_key: [u8; MASTER_KEY_SIZE] = [0xAAu8; MASTER_KEY_SIZE];
            let secondary_key: [u8; MASTER_KEY_SIZE] = [0xBBu8; MASTER_KEY_SIZE];

            // Wrap the keys
            let wrapped = pqc_wrap_master_keys(&master_key, &secondary_key);

            // Verify wrapped data is non-empty
            assert!(
                !wrapped.kem_ciphertext.is_empty(),
                "KEM ciphertext should not be empty"
            );
            assert!(
                !wrapped.recipient_pk.is_empty(),
                "Recipient PK should not be empty"
            );
            assert!(
                !wrapped.wrapped_keys.is_empty(),
                "Wrapped keys should not be empty"
            );
            assert!(
                !wrapped.signature.is_empty(),
                "Signature should not be empty"
            );
            assert!(
                !wrapped.signer_pk.is_empty(),
                "Signer PK should not be empty"
            );

            // Verify wrapped keys are different from original
            assert_ne!(
                &wrapped.wrapped_keys[12..],
                &master_key[..],
                "Wrapped keys should be encrypted"
            );
        }

        #[test]
        fn test_pqc_wrap_produces_different_output_each_time() {
            // Due to random nonces and ephemeral keys, each wrap should be different
            let master_key: [u8; MASTER_KEY_SIZE] = [0xCCu8; MASTER_KEY_SIZE];
            let secondary_key: [u8; MASTER_KEY_SIZE] = [0xDDu8; MASTER_KEY_SIZE];

            let wrapped1 = pqc_wrap_master_keys(&master_key, &secondary_key);
            let wrapped2 = pqc_wrap_master_keys(&master_key, &secondary_key);

            // KEM ciphertexts should differ (different ephemeral keys)
            assert_ne!(
                wrapped1.kem_ciphertext, wrapped2.kem_ciphertext,
                "Each wrap should use different ephemeral keys"
            );

            // Wrapped keys should differ (different AES-GCM nonces)
            assert_ne!(
                wrapped1.wrapped_keys, wrapped2.wrapped_keys,
                "Each wrap should use different nonces"
            );
        }

        #[test]
        fn test_pqc_header_extension_serialization() {
            use crate::vault::types::{PQC_HEADER_EXT_SIZE, PQC_MAGIC, PqcHeaderExtension};

            let mut ext = PqcHeaderExtension::new();
            ext.version = 1;
            ext.algorithm_id = 192; // Aes256MlKem1024
            ext.flags = 0x0001;

            // Set some test data
            ext.kem_ciphertext[0] = 0xAA;
            ext.recipient_public_key[0] = 0xBB;
            ext.wrapped_master_key[0] = 0xCC;
            ext.header_signature[0] = 0xDD;
            ext.signer_public_key[0] = 0xEE;

            // Serialize
            let bytes = ext.to_bytes();
            assert_eq!(bytes.len(), PQC_HEADER_EXT_SIZE);

            // Deserialize
            let restored = PqcHeaderExtension::from_bytes(&bytes).unwrap();

            assert_eq!(restored.magic, PQC_MAGIC);
            assert_eq!(restored.version, 1);
            assert_eq!(restored.algorithm_id, 192);
            assert_eq!(restored.flags, 0x0001);
            assert_eq!(restored.kem_ciphertext[0], 0xAA);
            assert_eq!(restored.recipient_public_key[0], 0xBB);
            assert_eq!(restored.wrapped_master_key[0], 0xCC);
            assert_eq!(restored.header_signature[0], 0xDD);
            assert_eq!(restored.signer_public_key[0], 0xEE);
        }
    }
}