jetdb 0.2.2

Pure Rust library for reading Microsoft Access (.mdb/.accdb) files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
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
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
//! Encryption support for .accdb files (MS-OFFCRYPTO).
//!
//! Supports Agile Encryption, RC4 CryptoAPI, and NonStandard AES.
//! The EncryptionInfo is stored at page 0 offset 0x299.

use crate::file::FileError;
use crate::format::db_header;

use crate::file::rc4_transform;

use aes::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyInit, KeyIvInit};
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use sha1::Sha1;
use sha2::{Digest, Sha256, Sha384, Sha512};
use subtle::ConstantTimeEq;
use zeroize::Zeroizing;

type Aes128CbcDec = cbc::Decryptor<aes::Aes128>;
type Aes192CbcDec = cbc::Decryptor<aes::Aes192>;
type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;
type Aes128EcbDec = ecb::Decryptor<aes::Aes128>;
type Aes192EcbDec = ecb::Decryptor<aes::Aes192>;
type Aes256EcbDec = ecb::Decryptor<aes::Aes256>;

// ---------------------------------------------------------------------------
// EncryptionInfo flags (MS-OFFCRYPTO §2.3.2)
// ---------------------------------------------------------------------------

const FCRYPTO_API_FLAG: u32 = 0x04;
const FAES_FLAG: u32 = 0x20;

// CryptoAlgorithm IDs (MS-OFFCRYPTO §2.3.2)
const ALGID_RC4: u32 = 0x6801;
const ALGID_AES_128: u32 = 0x660E;
const ALGID_AES_192: u32 = 0x660F;
const ALGID_AES_256: u32 = 0x6610;

// ---------------------------------------------------------------------------
// Block key constants for password key encryptor
// ---------------------------------------------------------------------------

const VERIFIER_HASH_INPUT_BLOCK_KEY: [u8; 8] = [0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, 0x79];
const VERIFIER_HASH_VALUE_BLOCK_KEY: [u8; 8] = [0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, 0x4e];
const ENCRYPTED_KEY_VALUE_BLOCK_KEY: [u8; 8] = [0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, 0xd6];

/// Padding byte for key derivation and IV construction (MS-OFFCRYPTO §2.3.6.2).
const HASH_PAD_BYTE: u8 = 0x36;

// ---------------------------------------------------------------------------
// AgileParams
// ---------------------------------------------------------------------------

/// Parameters parsed from the EncryptionInfo XML.
#[derive(Debug, Clone)]
pub(crate) struct AgileParams {
    // Key data (for page decryption)
    pub key_bits: usize,
    pub block_size: usize,
    pub hash_algorithm: HashAlgorithm,
    pub salt_value: Vec<u8>,

    // Password key encryptor
    pub pe_spin_count: u32,
    pub pe_salt_value: Vec<u8>,
    pub pe_hash_algorithm: HashAlgorithm,
    pub pe_key_bits: usize,
    pub pe_block_size: usize,
    pub encrypted_verifier_hash_input: Vec<u8>,
    pub encrypted_verifier_hash_value: Vec<u8>,
    pub encrypted_key_value: Vec<u8>,
}

// ---------------------------------------------------------------------------
// RC4 CryptoAPI params
// ---------------------------------------------------------------------------

/// Parameters parsed from the EncryptionInfo binary header for RC4 CryptoAPI.
#[derive(Debug, Clone)]
pub(crate) struct Rc4CryptoApiParams {
    pub salt: [u8; 16],
    pub encrypted_verifier: [u8; 16],
    pub verifier_hash_size: u32,
    pub encrypted_verifier_hash: Vec<u8>,
    pub key_size: u32, // bits (40 or 128)
}

// ---------------------------------------------------------------------------
// Standard AES params (also used for NonStandard AES with iterations=0)
// ---------------------------------------------------------------------------

/// Parameters for Standard AES / NonStandard AES encryption.
#[derive(Debug, Clone)]
pub(crate) struct StandardAesParams {
    pub salt: [u8; 16],
    pub encrypted_verifier: [u8; 16],
    pub verifier_hash_size: u32,
    pub encrypted_verifier_hash: Vec<u8>, // 32 bytes for AES
    pub key_size: u32,                    // 128, 192, or 256
    pub hash_iterations: u32,             // 50000 (standard) or 0 (non-standard)
}

// ---------------------------------------------------------------------------
// EncryptionParams enum
// ---------------------------------------------------------------------------

/// Parsed encryption parameters from the EncryptionInfo on page 0.
#[derive(Debug, Clone)]
pub(crate) enum EncryptionParams {
    Agile(AgileParams),
    Rc4CryptoApi(Rc4CryptoApiParams),
    StandardAes(StandardAesParams),
}

/// Supported hash algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HashAlgorithm {
    Sha1,
    Sha256,
    Sha384,
    Sha512,
}

impl HashAlgorithm {
    fn from_str(s: &str) -> Result<Self, FileError> {
        match s {
            "SHA1" => Ok(Self::Sha1),
            "SHA256" => Ok(Self::Sha256),
            "SHA384" => Ok(Self::Sha384),
            "SHA512" => Ok(Self::Sha512),
            _ => Err(FileError::UnsupportedEncryption {
                reason: format!("unsupported hash algorithm: {s}"),
            }),
        }
    }

    fn hash_size(&self) -> usize {
        match self {
            Self::Sha1 => 20,
            Self::Sha256 => 32,
            Self::Sha384 => 48,
            Self::Sha512 => 64,
        }
    }
}

// ---------------------------------------------------------------------------
// Generic hash helper
// ---------------------------------------------------------------------------

fn hash_with<D: Digest>(data: &[u8]) -> Vec<u8> {
    let mut h = D::new();
    h.update(data);
    h.finalize().to_vec()
}

fn hash_bytes(algo: HashAlgorithm, data: &[u8]) -> Vec<u8> {
    match algo {
        HashAlgorithm::Sha1 => hash_with::<Sha1>(data),
        HashAlgorithm::Sha256 => hash_with::<Sha256>(data),
        HashAlgorithm::Sha384 => hash_with::<Sha384>(data),
        HashAlgorithm::Sha512 => hash_with::<Sha512>(data),
    }
}

// ---------------------------------------------------------------------------
// XML parsing with quick-xml
// ---------------------------------------------------------------------------

/// Parse an attribute value from a quick-xml `BytesStart` element.
fn get_attr(
    e: &quick_xml::events::BytesStart<'_>,
    name: &[u8],
) -> Result<Option<String>, FileError> {
    for attr in e.attributes() {
        let attr = attr.map_err(|err| FileError::UnsupportedEncryption {
            reason: format!("invalid XML attribute: {err}"),
        })?;
        if attr.key.as_ref() == name {
            let val = attr.unescape_value().map_err(|err| FileError::UnsupportedEncryption {
                reason: format!("invalid XML attribute value: {err}"),
            })?;
            return Ok(Some(val.into_owned()));
        }
    }
    Ok(None)
}

fn require_attr(
    e: &quick_xml::events::BytesStart<'_>,
    name: &[u8],
    tag_name: &str,
) -> Result<String, FileError> {
    get_attr(e, name)?.ok_or_else(|| FileError::UnsupportedEncryption {
        reason: format!(
            "missing {}.{} in EncryptionInfo",
            tag_name,
            String::from_utf8_lossy(name)
        ),
    })
}

fn parse_usize(val: &str, tag: &str, attr: &str) -> Result<usize, FileError> {
    val.parse().map_err(|_| FileError::UnsupportedEncryption {
        reason: format!("invalid {tag}.{attr} value: {val}"),
    })
}

fn parse_u32(val: &str, tag: &str, attr: &str) -> Result<u32, FileError> {
    val.parse().map_err(|_| FileError::UnsupportedEncryption {
        reason: format!("invalid {tag}.{attr} value: {val}"),
    })
}

fn parse_base64(val: &str, tag: &str, attr: &str) -> Result<Vec<u8>, FileError> {
    BASE64.decode(val).map_err(|_| FileError::UnsupportedEncryption {
        reason: format!("invalid base64 in {tag}.{attr}"),
    })
}

/// Data extracted from the `<keyData>` element.
struct KeyDataAttrs {
    key_bits: usize,
    block_size: usize,
    hash_algorithm: HashAlgorithm,
    salt_value: Vec<u8>,
}

/// Data extracted from the `<*:encryptedKey>` element.
struct EncryptedKeyAttrs {
    spin_count: u32,
    salt_value: Vec<u8>,
    hash_algorithm: HashAlgorithm,
    key_bits: usize,
    block_size: usize,
    encrypted_verifier_hash_input: Vec<u8>,
    encrypted_verifier_hash_value: Vec<u8>,
    encrypted_key_value: Vec<u8>,
}

fn parse_key_data(e: &quick_xml::events::BytesStart<'_>) -> Result<KeyDataAttrs, FileError> {
    let tag = "keyData";
    Ok(KeyDataAttrs {
        key_bits: parse_usize(&require_attr(e, b"keyBits", tag)?, tag, "keyBits")?,
        block_size: parse_usize(&require_attr(e, b"blockSize", tag)?, tag, "blockSize")?,
        hash_algorithm: HashAlgorithm::from_str(&require_attr(e, b"hashAlgorithm", tag)?)?,
        salt_value: parse_base64(&require_attr(e, b"saltValue", tag)?, tag, "saltValue")?,
    })
}

fn parse_encrypted_key(
    e: &quick_xml::events::BytesStart<'_>,
) -> Result<EncryptedKeyAttrs, FileError> {
    let tag = "encryptedKey";
    Ok(EncryptedKeyAttrs {
        spin_count: parse_u32(&require_attr(e, b"spinCount", tag)?, tag, "spinCount")?,
        salt_value: parse_base64(&require_attr(e, b"saltValue", tag)?, tag, "saltValue")?,
        hash_algorithm: HashAlgorithm::from_str(&require_attr(e, b"hashAlgorithm", tag)?)?,
        key_bits: parse_usize(&require_attr(e, b"keyBits", tag)?, tag, "keyBits")?,
        block_size: parse_usize(&require_attr(e, b"blockSize", tag)?, tag, "blockSize")?,
        encrypted_verifier_hash_input: parse_base64(
            &require_attr(e, b"encryptedVerifierHashInput", tag)?,
            tag,
            "encryptedVerifierHashInput",
        )?,
        encrypted_verifier_hash_value: parse_base64(
            &require_attr(e, b"encryptedVerifierHashValue", tag)?,
            tag,
            "encryptedVerifierHashValue",
        )?,
        encrypted_key_value: parse_base64(
            &require_attr(e, b"encryptedKeyValue", tag)?,
            tag,
            "encryptedKeyValue",
        )?,
    })
}

// ---------------------------------------------------------------------------
// parse_encryption_info
// ---------------------------------------------------------------------------

/// Parse the EncryptionInfo from page 0.
/// Returns `None` if no encryption is present.
pub(crate) fn parse_encryption_info(page0: &[u8]) -> Result<Option<EncryptionParams>, FileError> {
    let offset = db_header::ENCRYPTION_INFO_OFFSET;
    if page0.len() < offset + 2 {
        return Ok(None);
    }

    // EncryptionInfo length is stored as u16 LE.
    let info_len = u16::from_le_bytes([page0[offset], page0[offset + 1]]) as usize;
    if info_len == 0 {
        return Ok(None);
    }

    let info_start = offset + 2;
    let info_end = info_start + info_len;
    if page0.len() < info_end {
        return Err(FileError::UnsupportedEncryption {
            reason: "EncryptionInfo extends beyond page 0".to_string(),
        });
    }

    let info_data = &page0[info_start..info_end];
    if info_data.len() < 4 {
        return Err(FileError::UnsupportedEncryption {
            reason: "EncryptionInfo too short for version header".to_string(),
        });
    }

    let v_major = u16::from_le_bytes([info_data[0], info_data[1]]);
    let v_minor = u16::from_le_bytes([info_data[2], info_data[3]]);

    match (v_major, v_minor) {
        // Agile Encryption (MS-OFFCRYPTO §2.3.4.10)
        (4, 4) => parse_agile_encryption_info(&info_data[4..]).map(|p| Some(EncryptionParams::Agile(p))),

        // Office Binary Doc RC4 (not supported)
        (1, 1) => Err(FileError::UnsupportedEncryption {
            reason: "Office Binary Doc RC4 encryption (v1.1) is not supported".to_string(),
        }),

        // Extensible Encryption (not supported)
        (3 | 4, 3) => Err(FileError::UnsupportedEncryption {
            reason: "Extensible encryption (v3/4.3) is not supported".to_string(),
        }),

        // RC4 CryptoAPI / Standard AES / NonStandard AES
        (2..=4, 2) => {
            if info_data.len() < 8 {
                return Err(FileError::UnsupportedEncryption {
                    reason: "EncryptionInfo too short for CryptoAPI flags".to_string(),
                });
            }
            let flags = u32::from_le_bytes([info_data[4], info_data[5], info_data[6], info_data[7]]);

            if flags & FCRYPTO_API_FLAG == 0 {
                return Err(FileError::UnsupportedEncryption {
                    reason: format!("CryptoAPI flag not set in EncryptionInfo flags: 0x{flags:08x}"),
                });
            }

            if flags & FAES_FLAG != 0 {
                // Standard AES Encryption (MS-OFFCRYPTO §2.3.4.5)
                parse_standard_aes_info(&info_data[8..], 50_000).map(|p| Some(EncryptionParams::StandardAes(p)))
            } else {
                // Try RC4 CryptoAPI first; if algId is AES, fall back to NonStandard AES
                parse_cryptoapi_info(&info_data[8..])
            }
        }

        _ => Err(FileError::UnsupportedEncryption {
            reason: format!(
                "unsupported EncryptionInfo version: vMajor={v_major}, vMinor={v_minor}"
            ),
        }),
    }
}

/// Parse Agile Encryption XML from the EncryptionInfo payload.
fn parse_agile_encryption_info(xml_bytes: &[u8]) -> Result<AgileParams, FileError> {
    let mut reader = quick_xml::Reader::from_reader(xml_bytes);
    reader.config_mut().trim_text(true);

    let mut key_data: Option<KeyDataAttrs> = None;
    let mut enc_key: Option<EncryptedKeyAttrs> = None;

    let mut buf = Vec::new();
    loop {
        match reader.read_event_into(&mut buf) {
            Ok(quick_xml::events::Event::Start(ref e) | quick_xml::events::Event::Empty(ref e)) => {
                let local = e.local_name();
                match local.as_ref() {
                    b"keyData" => {
                        key_data = Some(parse_key_data(e)?);
                    }
                    b"encryptedKey" => {
                        enc_key = Some(parse_encrypted_key(e)?);
                    }
                    _ => {}
                }
            }
            Ok(quick_xml::events::Event::Eof) => break,
            Err(err) => {
                return Err(FileError::UnsupportedEncryption {
                    reason: format!("EncryptionInfo XML parse error: {err}"),
                });
            }
            _ => {}
        }
        buf.clear();
    }

    let kd = key_data.ok_or_else(|| FileError::UnsupportedEncryption {
        reason: "missing <keyData> in EncryptionInfo XML".to_string(),
    })?;
    let ek = enc_key.ok_or_else(|| FileError::UnsupportedEncryption {
        reason: "missing <encryptedKey> in EncryptionInfo XML".to_string(),
    })?;

    Ok(AgileParams {
        key_bits: kd.key_bits,
        block_size: kd.block_size,
        hash_algorithm: kd.hash_algorithm,
        salt_value: kd.salt_value,
        pe_spin_count: ek.spin_count,
        pe_salt_value: ek.salt_value,
        pe_hash_algorithm: ek.hash_algorithm,
        pe_key_bits: ek.key_bits,
        pe_block_size: ek.block_size,
        encrypted_verifier_hash_input: ek.encrypted_verifier_hash_input,
        encrypted_verifier_hash_value: ek.encrypted_verifier_hash_value,
        encrypted_key_value: ek.encrypted_key_value,
    })
}

// ---------------------------------------------------------------------------
// RC4 CryptoAPI / Standard AES binary parsing
// ---------------------------------------------------------------------------

/// Read a u32 LE from data at the given offset.
fn read_u32(data: &[u8], off: usize) -> Result<u32, FileError> {
    if data.len() < off + 4 {
        return Err(FileError::UnsupportedEncryption {
            reason: "EncryptionHeader/Verifier truncated".to_string(),
        });
    }
    Ok(u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]]))
}

/// Parse a CryptoAPI EncryptionHeader + EncryptionVerifier.
/// Dispatches to Rc4CryptoApi or StandardAes(iterations=0) based on algId.
fn parse_cryptoapi_info(data: &[u8]) -> Result<Option<EncryptionParams>, FileError> {
    // headerSize (4 bytes) followed by EncryptionHeader
    let header_size = read_u32(data, 0)? as usize;
    let header_end = 4usize.checked_add(header_size).ok_or(FileError::UnsupportedEncryption {
        reason: "EncryptionHeader size overflow".to_string(),
    })?;
    if data.len() < header_end {
        return Err(FileError::UnsupportedEncryption {
            reason: "EncryptionHeader extends beyond EncryptionInfo".to_string(),
        });
    }

    let header_data = &data[4..header_end];

    // EncryptionHeader: flags(4) + sizeExtra(4) + algId(4) + algIdHash(4) + keySize(4) + ...
    if header_data.len() < 20 {
        return Err(FileError::UnsupportedEncryption {
            reason: "EncryptionHeader too small".to_string(),
        });
    }
    let alg_id = read_u32(header_data, 8)?;
    let key_size = read_u32(header_data, 16)?;

    // Verifier data follows the header
    let verifier_data = &data[header_end..];

    match alg_id {
        ALGID_RC4 => {
            let key_size = if key_size == 0 { 40 } else { key_size };
            if key_size != 40 && key_size != 128 {
                return Err(FileError::UnsupportedEncryption {
                    reason: format!("invalid RC4 CryptoAPI key size: {key_size}"),
                });
            }
            let v = parse_encryption_verifier(verifier_data, 20)?;
            Ok(Some(EncryptionParams::Rc4CryptoApi(Rc4CryptoApiParams {
                salt: v.salt,
                encrypted_verifier: v.encrypted_verifier,
                verifier_hash_size: v.verifier_hash_size,
                encrypted_verifier_hash: v.encrypted_verifier_hash,
                key_size,
            })))
        }
        ALGID_AES_128 | ALGID_AES_192 | ALGID_AES_256 => {
            // NonStandard AES: same binary format as Standard AES but iterations=0
            let key_size = match alg_id {
                ALGID_AES_128 => if key_size == 0 { 128 } else { key_size },
                ALGID_AES_192 => if key_size == 0 { 192 } else { key_size },
                ALGID_AES_256 => if key_size == 0 { 256 } else { key_size },
                _ => unreachable!(),
            };
            if key_size != 128 && key_size != 192 && key_size != 256 {
                return Err(FileError::UnsupportedEncryption {
                    reason: format!("invalid AES key size: {key_size}"),
                });
            }
            parse_standard_aes_info_from_verifier(verifier_data, key_size, 0)
                .map(|p| Some(EncryptionParams::StandardAes(p)))
        }
        _ => Err(FileError::UnsupportedEncryption {
            reason: format!("unsupported CryptoAPI algorithm ID: 0x{alg_id:04x}"),
        }),
    }
}

/// Parse a Standard AES EncryptionInfo (with headerSize + EncryptionHeader + EncryptionVerifier).
fn parse_standard_aes_info(data: &[u8], hash_iterations: u32) -> Result<StandardAesParams, FileError> {
    let header_size = read_u32(data, 0)? as usize;
    let header_end = 4usize.checked_add(header_size).ok_or(FileError::UnsupportedEncryption {
        reason: "EncryptionHeader size overflow".to_string(),
    })?;
    if data.len() < header_end {
        return Err(FileError::UnsupportedEncryption {
            reason: "EncryptionHeader extends beyond EncryptionInfo".to_string(),
        });
    }

    let header_data = &data[4..header_end];
    if header_data.len() < 20 {
        return Err(FileError::UnsupportedEncryption {
            reason: "EncryptionHeader too small".to_string(),
        });
    }
    let alg_id = read_u32(header_data, 8)?;
    let key_size_raw = read_u32(header_data, 16)?;

    let key_size = match alg_id {
        ALGID_AES_128 => if key_size_raw == 0 { 128 } else { key_size_raw },
        ALGID_AES_192 => if key_size_raw == 0 { 192 } else { key_size_raw },
        ALGID_AES_256 => if key_size_raw == 0 { 256 } else { key_size_raw },
        _ => return Err(FileError::UnsupportedEncryption {
            reason: format!("Standard AES: unexpected algId 0x{alg_id:04x}"),
        }),
    };

    let verifier_data = &data[header_end..];
    parse_standard_aes_info_from_verifier(verifier_data, key_size, hash_iterations)
}

/// Parsed EncryptionVerifier fields.
struct VerifierFields {
    salt: [u8; 16],
    encrypted_verifier: [u8; 16],
    verifier_hash_size: u32,
    encrypted_verifier_hash: Vec<u8>,
}

/// Parse the EncryptionVerifier from binary data.
fn parse_encryption_verifier(
    data: &[u8],
    enc_verifier_hash_len: usize,
) -> Result<VerifierFields, FileError> {
    // saltSize(4) + salt(16) + encryptedVerifier(16) + verifierHashSize(4) + encryptedVerifierHash(N)
    let min_len = 4 + 16 + 16 + 4 + enc_verifier_hash_len;
    if data.len() < min_len {
        return Err(FileError::UnsupportedEncryption {
            reason: "EncryptionVerifier truncated".to_string(),
        });
    }

    let salt_size = read_u32(data, 0)?;
    if salt_size != 16 {
        return Err(FileError::UnsupportedEncryption {
            reason: format!("unexpected salt size: {salt_size} (expected 16)"),
        });
    }

    let mut salt = [0u8; 16];
    salt.copy_from_slice(&data[4..20]);

    let mut encrypted_verifier = [0u8; 16];
    encrypted_verifier.copy_from_slice(&data[20..36]);

    let verifier_hash_size = read_u32(data, 36)?;

    let encrypted_verifier_hash = data[40..40 + enc_verifier_hash_len].to_vec();

    Ok(VerifierFields {
        salt,
        encrypted_verifier,
        verifier_hash_size,
        encrypted_verifier_hash,
    })
}

/// Parse EncryptionVerifier and build StandardAesParams.
fn parse_standard_aes_info_from_verifier(
    verifier_data: &[u8],
    key_size: u32,
    hash_iterations: u32,
) -> Result<StandardAesParams, FileError> {
    // AES encrypted verifier hash is 32 bytes (padded to AES block size)
    let v = parse_encryption_verifier(verifier_data, 32)?;

    Ok(StandardAesParams {
        salt: v.salt,
        encrypted_verifier: v.encrypted_verifier,
        verifier_hash_size: v.verifier_hash_size,
        encrypted_verifier_hash: v.encrypted_verifier_hash,
        key_size,
        hash_iterations,
    })
}

// ---------------------------------------------------------------------------
// Key derivation
// ---------------------------------------------------------------------------

/// Derive an encryption key using the Agile Encryption key derivation scheme.
///
/// 1. H0 = hash(salt + password_utf16le)
/// 2. Hn = hash(n_u32le + H_{n-1}) for spinCount iterations
/// 3. Hfinal = hash(H_last + blockKey)
/// 4. Pad/truncate to cbRequiredKeyLength bytes
fn derive_key(
    password: &str,
    salt: &[u8],
    spin_count: u32,
    block_key: &[u8],
    hash_algo: HashAlgorithm,
    key_bits: usize,
) -> Zeroizing<Vec<u8>> {
    // H0 = hash(salt + password_utf16le)
    let password_utf16: Zeroizing<Vec<u8>> = Zeroizing::new(
        password
            .encode_utf16()
            .flat_map(|c| c.to_le_bytes())
            .collect(),
    );

    let mut buf = Vec::with_capacity(salt.len() + password_utf16.len());
    buf.extend_from_slice(salt);
    buf.extend_from_slice(&password_utf16);
    let mut h = Zeroizing::new(hash_bytes(hash_algo, &buf));

    // Hn = hash(n_u32le + H_{n-1})
    for n in 0..spin_count {
        let mut iter_buf = Vec::with_capacity(4 + h.len());
        iter_buf.extend_from_slice(&n.to_le_bytes());
        iter_buf.extend_from_slice(&h);
        h = Zeroizing::new(hash_bytes(hash_algo, &iter_buf));
    }

    // Hfinal = hash(H_last + blockKey)
    let mut final_buf = Vec::with_capacity(h.len() + block_key.len());
    final_buf.extend_from_slice(&h);
    final_buf.extend_from_slice(block_key);
    let h_final = Zeroizing::new(hash_bytes(hash_algo, &final_buf));

    // Pad or truncate to key_bits / 8
    let key_len = key_bits / 8;
    if h_final.len() >= key_len {
        Zeroizing::new(h_final[..key_len].to_vec())
    } else {
        let mut padded = h_final.to_vec();
        padded.resize(key_len, HASH_PAD_BYTE);
        Zeroizing::new(padded)
    }
}

// ---------------------------------------------------------------------------
// AES-CBC decryption helper
// ---------------------------------------------------------------------------

/// Decrypt data using AES-CBC with the given key and IV.
/// Returns the decrypted data (no PKCS7 unpadding — the caller handles truncation).
fn aes_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, FileError> {
    // AES-CBC requires data to be a multiple of block size (16).
    // Pad input to block boundary if needed.
    let block_size = 16;
    let padded_len = if data.len() % block_size != 0 {
        (data.len() / block_size + 1) * block_size
    } else {
        data.len()
    };
    let mut buf = vec![0u8; padded_len];
    buf[..data.len()].copy_from_slice(data);

    // Ensure IV is exactly 16 bytes
    let mut iv16 = [0u8; 16];
    let copy_len = iv.len().min(16);
    iv16[..copy_len].copy_from_slice(&iv[..copy_len]);

    match key.len() {
        16 => {
            let mut key16 = [0u8; 16];
            key16.copy_from_slice(key);
            Aes128CbcDec::new(&key16.into(), &iv16.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf)
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-128-CBC decryption failed".to_string(),
                })?;
        }
        24 => {
            let mut key24 = [0u8; 24];
            key24.copy_from_slice(key);
            Aes192CbcDec::new(&key24.into(), &iv16.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf)
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-192-CBC decryption failed".to_string(),
                })?;
        }
        32 => {
            let mut key32 = [0u8; 32];
            key32.copy_from_slice(key);
            Aes256CbcDec::new(&key32.into(), &iv16.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf)
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-256-CBC decryption failed".to_string(),
                })?;
        }
        other => {
            return Err(FileError::UnsupportedEncryption {
                reason: format!("unsupported AES key size: {other} bytes"),
            });
        }
    }

    Ok(buf)
}

// ---------------------------------------------------------------------------
// verify_password
// ---------------------------------------------------------------------------

/// Verify the password against the EncryptionInfo parameters.
/// On success, returns the decrypted database key (encryptedKeyValue).
pub(crate) fn verify_password(
    params: &AgileParams,
    password: &str,
) -> Result<Zeroizing<Vec<u8>>, FileError> {
    let algo = params.pe_hash_algorithm;
    let salt = &params.pe_salt_value;
    let spin = params.pe_spin_count;
    let key_bits = params.pe_key_bits;

    // Derive the three keys
    let key_input = derive_key(
        password,
        salt,
        spin,
        &VERIFIER_HASH_INPUT_BLOCK_KEY,
        algo,
        key_bits,
    );
    let key_hash_value = derive_key(
        password,
        salt,
        spin,
        &VERIFIER_HASH_VALUE_BLOCK_KEY,
        algo,
        key_bits,
    );
    let key_enc_key = derive_key(
        password,
        salt,
        spin,
        &ENCRYPTED_KEY_VALUE_BLOCK_KEY,
        algo,
        key_bits,
    );

    // IV for password encryptor decryption: salt padded/truncated to pe_block_size
    let iv = make_iv(salt, params.pe_block_size);

    // Decrypt verifierHashInput
    let verifier = Zeroizing::new(
        aes_cbc_decrypt(&key_input, &iv, &params.encrypted_verifier_hash_input)?,
    );

    // Decrypt verifierHashValue
    let expected_hash_full = Zeroizing::new(
        aes_cbc_decrypt(&key_hash_value, &iv, &params.encrypted_verifier_hash_value)?,
    );

    // Verify: hash(verifier) == expected_hash (truncated to hash size)
    let hash_size = algo.hash_size();
    let actual_hash = Zeroizing::new(hash_bytes(algo, &verifier));

    let expected_hash = if expected_hash_full.len() >= hash_size {
        &expected_hash_full[..hash_size]
    } else {
        &expected_hash_full
    };

    if actual_hash[..hash_size].ct_eq(expected_hash).unwrap_u8() != 1 {
        return Err(FileError::InvalidPassword);
    }

    // Decrypt the database key
    let db_key = Zeroizing::new(
        aes_cbc_decrypt(&key_enc_key, &iv, &params.encrypted_key_value)?,
    );

    // Truncate to keyData keyBits / 8
    let db_key_len = params.key_bits / 8;
    Ok(Zeroizing::new(db_key[..db_key_len].to_vec()))
}

// ---------------------------------------------------------------------------
// Page decryption
// ---------------------------------------------------------------------------

/// Build an IV by padding/truncating data to the target block size.
fn make_iv(data: &[u8], block_size: usize) -> Vec<u8> {
    if data.len() >= block_size {
        data[..block_size].to_vec()
    } else {
        let mut iv = vec![HASH_PAD_BYTE; block_size];
        iv[..data.len()].copy_from_slice(data);
        iv
    }
}

/// Decrypt a data page using Agile Encryption (Access-specific scheme).
///
/// IV = hash(db_salt + block_key_bytes), padded/truncated to blockSize.
/// block_key = page_number XOR db_encoding_key.
pub(crate) fn decrypt_page_agile(
    buf: &mut [u8],
    params: &AgileParams,
    db_key: &[u8],
    db_encoding_key: u32,
    page: u32,
) -> Result<(), FileError> {
    if buf.is_empty() {
        return Ok(());
    }

    let block_key = page ^ db_encoding_key;
    let block_key_bytes = block_key.to_le_bytes();

    // IV = hash(keyData.salt + block_key_bytes)
    let mut iv_input = Vec::with_capacity(params.salt_value.len() + 4);
    iv_input.extend_from_slice(&params.salt_value);
    iv_input.extend_from_slice(&block_key_bytes);
    let iv_hash = hash_bytes(params.hash_algorithm, &iv_input);
    let iv = make_iv(&iv_hash, params.block_size);

    // Decrypt entire page with AES-CBC
    // Ensure buffer is block-aligned for AES
    let aes_block = 16;
    let decrypt_len = (buf.len() / aes_block) * aes_block;
    if decrypt_len == 0 {
        return Ok(());
    }

    let mut iv16 = [0u8; 16];
    let copy_len = iv.len().min(16);
    iv16[..copy_len].copy_from_slice(&iv[..copy_len]);

    match db_key.len() {
        16 => {
            let mut key16 = [0u8; 16];
            key16.copy_from_slice(db_key);
            Aes128CbcDec::new(&key16.into(), &iv16.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf[..decrypt_len])
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-128-CBC page decryption failed".to_string(),
                })?;
        }
        24 => {
            let mut key24 = [0u8; 24];
            key24.copy_from_slice(db_key);
            Aes192CbcDec::new(&key24.into(), &iv16.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf[..decrypt_len])
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-192-CBC page decryption failed".to_string(),
                })?;
        }
        32 => {
            let mut key32 = [0u8; 32];
            key32.copy_from_slice(db_key);
            Aes256CbcDec::new(&key32.into(), &iv16.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf[..decrypt_len])
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-256-CBC page decryption failed".to_string(),
                })?;
        }
        other => {
            return Err(FileError::UnsupportedEncryption {
                reason: format!("unsupported db_key length: {other} bytes"),
            });
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// RC4 CryptoAPI password verification and page decryption
// ---------------------------------------------------------------------------

/// Compute block_bytes for page decryption (MS-OFFCRYPTO applyPageNumber).
/// XORs the encoding key bytes with the little-endian page number.
/// (jackcessencrypt uses LITTLE_ENDIAN ByteBuffer order)
fn apply_page_number(encoding_key: &[u8; 4], page: u32) -> [u8; 4] {
    let page_le = page.to_le_bytes();
    [
        encoding_key[0] ^ page_le[0],
        encoding_key[1] ^ page_le[1],
        encoding_key[2] ^ page_le[2],
        encoding_key[3] ^ page_le[3],
    ]
}

/// Derive an RC4 CryptoAPI encryption key from base_hash and block_bytes.
fn derive_rc4_cryptoapi_key(base_hash: &[u8], block_bytes: &[u8], key_size: u32) -> Vec<u8> {
    let key_byte_size = (key_size / 8) as usize;
    // enc_key = SHA1(base_hash || block_bytes), truncated to key_byte_size
    let mut input = Vec::with_capacity(base_hash.len() + block_bytes.len());
    input.extend_from_slice(base_hash);
    input.extend_from_slice(block_bytes);
    let hash = hash_bytes(HashAlgorithm::Sha1, &input);

    let mut enc_key = hash[..key_byte_size.min(hash.len())].to_vec();
    // For 40-bit keys, zero-pad to 128 bits (16 bytes)
    if key_size == 40 {
        enc_key.resize(16, 0);
    }
    enc_key
}

/// Verify a password for RC4 CryptoAPI encryption.
/// Returns the base_hash on success (used for page decryption).
pub(crate) fn verify_password_rc4_cryptoapi(
    params: &Rc4CryptoApiParams,
    password: &str,
) -> Result<Zeroizing<Vec<u8>>, FileError> {
    // base_hash = SHA1(salt + password_utf16le)
    let password_utf16: Zeroizing<Vec<u8>> = Zeroizing::new(
        password
            .encode_utf16()
            .flat_map(|c| c.to_le_bytes())
            .collect(),
    );

    let mut salt_pw = Vec::with_capacity(16 + password_utf16.len());
    salt_pw.extend_from_slice(&params.salt);
    salt_pw.extend_from_slice(&password_utf16);
    let base_hash = Zeroizing::new(hash_bytes(HashAlgorithm::Sha1, &salt_pw));

    // Verification uses block_bytes = [0, 0, 0, 0]
    let enc_key = derive_rc4_cryptoapi_key(&base_hash, &[0u8; 4], params.key_size);

    // Decrypt verifier and verifier_hash with the same RC4 stream
    let mut combined = Vec::with_capacity(16 + params.encrypted_verifier_hash.len());
    combined.extend_from_slice(&params.encrypted_verifier);
    combined.extend_from_slice(&params.encrypted_verifier_hash);
    rc4_transform(&enc_key, &mut combined);

    let verifier = &combined[..16];
    let verifier_hash = &combined[16..];

    // Compute SHA1(verifier) and compare with decrypted hash
    let actual_hash = hash_bytes(HashAlgorithm::Sha1, verifier);
    let hash_size = params.verifier_hash_size as usize;
    if hash_size == 0 || hash_size > 20 {
        return Err(FileError::UnsupportedEncryption {
            reason: format!("invalid verifier hash size: {hash_size}"),
        });
    }
    let expected = &verifier_hash[..hash_size.min(verifier_hash.len())];
    let actual = &actual_hash[..hash_size.min(actual_hash.len())];

    if actual.ct_eq(expected).unwrap_u8() != 1 {
        return Err(FileError::InvalidPassword);
    }

    Ok(base_hash)
}

/// Decrypt a data page using RC4 CryptoAPI encryption.
pub(crate) fn decrypt_page_rc4_cryptoapi(
    buf: &mut [u8],
    base_hash: &[u8],
    encoding_key: &[u8; 4],
    key_size: u32,
    page: u32,
) {
    if buf.is_empty() {
        return;
    }
    let block_bytes = apply_page_number(encoding_key, page);
    let enc_key = derive_rc4_cryptoapi_key(base_hash, &block_bytes, key_size);
    rc4_transform(&enc_key, buf);
}

// ---------------------------------------------------------------------------
// Standard AES / NonStandard AES password verification and page decryption
// ---------------------------------------------------------------------------

/// Iterate hash: H_n = SHA1(n_u32le + H_{n-1}) for n in 0..iterations.
/// If iterations == 0, returns base_hash unchanged.
fn iterate_hash_sha1(base_hash: &[u8], iterations: u32) -> Vec<u8> {
    if iterations == 0 {
        return base_hash.to_vec();
    }

    let mut h = Zeroizing::new(base_hash.to_vec());
    for i in 0..iterations {
        let mut buf = Vec::with_capacity(4 + h.len());
        buf.extend_from_slice(&i.to_le_bytes());
        buf.extend_from_slice(&h);
        h = Zeroizing::new(hash_bytes(HashAlgorithm::Sha1, &buf));
    }
    h.to_vec()
}

/// Generate XOR-padded bytes for HMAC-like key derivation (MS-OFFCRYPTO §2.3.4.7).
fn gen_x_bytes(final_hash: &[u8], code: u8) -> [u8; 64] {
    let mut x = [code; 64];
    for (i, &b) in final_hash.iter().enumerate() {
        x[i] ^= b;
    }
    x
}

/// Derive a Standard AES encryption key using cryptDeriveKey (MS-OFFCRYPTO §2.3.4.7).
fn derive_standard_aes_key(iter_hash: &[u8], block_bytes: &[u8], key_byte_len: usize) -> Vec<u8> {
    // final_hash = SHA1(iter_hash || block_bytes)
    let mut buf = Vec::with_capacity(iter_hash.len() + block_bytes.len());
    buf.extend_from_slice(iter_hash);
    buf.extend_from_slice(block_bytes);
    let final_hash = Zeroizing::new(hash_bytes(HashAlgorithm::Sha1, &buf));

    // x1 = SHA1(genXBytes(final_hash, 0x36))
    let x1 = Zeroizing::new(hash_bytes(HashAlgorithm::Sha1, &gen_x_bytes(&final_hash, 0x36)));
    // x2 = SHA1(genXBytes(final_hash, 0x5C))
    let x2 = Zeroizing::new(hash_bytes(HashAlgorithm::Sha1, &gen_x_bytes(&final_hash, 0x5C)));

    // enc_key = (x1 || x2)[..key_byte_len]
    let mut full = Vec::with_capacity(x1.len() + x2.len());
    full.extend_from_slice(&x1);
    full.extend_from_slice(&x2);
    full.truncate(key_byte_len);
    // Zero-pad if needed (shouldn't happen for AES-128/192/256 with SHA1)
    full.resize(key_byte_len, 0);
    full
}

/// Decrypt data using AES-ECB (used for Standard AES / NonStandard AES).
fn aes_ecb_decrypt(key: &[u8], data: &[u8]) -> Result<Vec<u8>, FileError> {
    let block_size = 16;
    let padded_len = if data.len() % block_size != 0 {
        (data.len() / block_size + 1) * block_size
    } else {
        data.len()
    };
    let mut buf = vec![0u8; padded_len];
    buf[..data.len()].copy_from_slice(data);

    match key.len() {
        16 => {
            Aes128EcbDec::new(key.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf)
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-128-ECB decryption failed".to_string(),
                })?;
        }
        24 => {
            Aes192EcbDec::new(key.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf)
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-192-ECB decryption failed".to_string(),
                })?;
        }
        32 => {
            Aes256EcbDec::new(key.into())
                .decrypt_padded_mut::<NoPadding>(&mut buf)
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-256-ECB decryption failed".to_string(),
                })?;
        }
        other => {
            return Err(FileError::UnsupportedEncryption {
                reason: format!("unsupported AES key size: {other} bytes"),
            });
        }
    }

    Ok(buf)
}

/// Verify a password for Standard AES / NonStandard AES encryption.
/// Returns the iter_hash on success (precomputed for page decryption).
pub(crate) fn verify_password_standard_aes(
    params: &StandardAesParams,
    password: &str,
) -> Result<Zeroizing<Vec<u8>>, FileError> {
    // base_hash = SHA1(salt + password_utf16le)
    let password_utf16: Zeroizing<Vec<u8>> = Zeroizing::new(
        password
            .encode_utf16()
            .flat_map(|c| c.to_le_bytes())
            .collect(),
    );

    let mut salt_pw = Vec::with_capacity(16 + password_utf16.len());
    salt_pw.extend_from_slice(&params.salt);
    salt_pw.extend_from_slice(&password_utf16);
    let base_hash = Zeroizing::new(hash_bytes(HashAlgorithm::Sha1, &salt_pw));

    // Iterate hash
    let iter_hash = Zeroizing::new(iterate_hash_sha1(&base_hash, params.hash_iterations));

    // Verification uses block_bytes = [0, 0, 0, 0]
    let key_byte_len = (params.key_size / 8) as usize;
    let enc_key = derive_standard_aes_key(&iter_hash, &[0u8; 4], key_byte_len);

    // Decrypt verifier and verifier_hash with AES-ECB
    let verifier = aes_ecb_decrypt(&enc_key, &params.encrypted_verifier)?;
    let verifier_hash_dec = aes_ecb_decrypt(&enc_key, &params.encrypted_verifier_hash)?;

    // SHA1(verifier) == verifier_hash (truncated to verifier_hash_size)
    let actual_hash = hash_bytes(HashAlgorithm::Sha1, &verifier);
    let hash_size = params.verifier_hash_size as usize;
    if hash_size == 0 || hash_size > 20 {
        return Err(FileError::UnsupportedEncryption {
            reason: format!("invalid verifier hash size: {hash_size}"),
        });
    }
    let expected = &verifier_hash_dec[..hash_size.min(verifier_hash_dec.len())];
    let actual = &actual_hash[..hash_size.min(actual_hash.len())];

    if actual.ct_eq(expected).unwrap_u8() != 1 {
        return Err(FileError::InvalidPassword);
    }

    Ok(iter_hash)
}

/// Decrypt a data page using Standard AES / NonStandard AES (AES-ECB).
pub(crate) fn decrypt_page_standard_aes(
    buf: &mut [u8],
    iter_hash: &[u8],
    encoding_key: &[u8; 4],
    key_size: u32,
    page: u32,
) -> Result<(), FileError> {
    if buf.is_empty() {
        return Ok(());
    }

    let block_bytes = apply_page_number(encoding_key, page);
    let key_byte_len = (key_size / 8) as usize;
    let enc_key = derive_standard_aes_key(iter_hash, &block_bytes, key_byte_len);

    // Decrypt in-place using AES-ECB
    let aes_block = 16;
    let decrypt_len = (buf.len() / aes_block) * aes_block;
    if decrypt_len == 0 {
        return Ok(());
    }

    match enc_key.len() {
        16 => {
            Aes128EcbDec::new(enc_key[..].into())
                .decrypt_padded_mut::<NoPadding>(&mut buf[..decrypt_len])
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-128-ECB page decryption failed".to_string(),
                })?;
        }
        24 => {
            Aes192EcbDec::new(enc_key[..].into())
                .decrypt_padded_mut::<NoPadding>(&mut buf[..decrypt_len])
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-192-ECB page decryption failed".to_string(),
                })?;
        }
        32 => {
            Aes256EcbDec::new(enc_key[..].into())
                .decrypt_padded_mut::<NoPadding>(&mut buf[..decrypt_len])
                .map_err(|_| FileError::UnsupportedEncryption {
                    reason: "AES-256-ECB page decryption failed".to_string(),
                })?;
        }
        other => {
            return Err(FileError::UnsupportedEncryption {
                reason: format!("unsupported AES key size for page decryption: {other} bytes"),
            });
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::file::{rc4_transform, HEADER_RC4_KEY};
    use crate::format::JetVersion;

    /// Helper: resolve a test data path, returning None if the file doesn't exist.
    fn test_data_path(relative: &str) -> Option<std::path::PathBuf> {
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let path = std::path::PathBuf::from(manifest_dir)
            .join("../../testdata")
            .join(relative);
        if path.exists() {
            Some(path)
        } else {
            None
        }
    }

    macro_rules! skip_if_missing {
        ($path:expr) => {
            match test_data_path($path) {
                Some(p) => p,
                None => {
                    eprintln!("SKIP: test data not found: {}", $path);
                    return;
                }
            }
        };
    }

    fn hex(data: &[u8]) -> String {
        data.iter().map(|b| format!("{b:02x}")).collect()
    }

    #[test]
    fn hash_algorithm_from_str_valid() {
        assert_eq!(HashAlgorithm::from_str("SHA1").unwrap(), HashAlgorithm::Sha1);
        assert_eq!(HashAlgorithm::from_str("SHA256").unwrap(), HashAlgorithm::Sha256);
        assert_eq!(HashAlgorithm::from_str("SHA384").unwrap(), HashAlgorithm::Sha384);
        assert_eq!(HashAlgorithm::from_str("SHA512").unwrap(), HashAlgorithm::Sha512);
    }

    #[test]
    fn hash_algorithm_from_str_invalid() {
        assert!(HashAlgorithm::from_str("MD5").is_err());
    }

    #[test]
    fn hash_algorithm_hash_size() {
        assert_eq!(HashAlgorithm::Sha1.hash_size(), 20);
        assert_eq!(HashAlgorithm::Sha256.hash_size(), 32);
        assert_eq!(HashAlgorithm::Sha384.hash_size(), 48);
        assert_eq!(HashAlgorithm::Sha512.hash_size(), 64);
    }

    #[test]
    fn hash_bytes_sha256() {
        let data = b"hello";
        let result = hash_bytes(HashAlgorithm::Sha256, data);
        assert_eq!(result.len(), 32);
        // Known SHA-256 of "hello"
        assert_eq!(
            hex(&result),
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
    }

    #[test]
    fn hash_bytes_sha1() {
        let data = b"hello";
        let result = hash_bytes(HashAlgorithm::Sha1, data);
        assert_eq!(result.len(), 20);
        assert_eq!(
            hex(&result),
            "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
        );
    }

    #[test]
    fn derive_key_length() {
        let key = derive_key("test", &[0u8; 16], 100, &[0u8; 8], HashAlgorithm::Sha256, 128);
        assert_eq!(key.len(), 16); // 128 bits / 8
    }

    #[test]
    fn derive_key_length_256() {
        let key = derive_key("test", &[0u8; 16], 100, &[0u8; 8], HashAlgorithm::Sha256, 256);
        assert_eq!(key.len(), 32); // 256 bits / 8
    }

    #[test]
    fn derive_key_deterministic() {
        // Same inputs must produce the same output
        let k1 = derive_key("pw", &[1, 2, 3, 4], 10, &[0xAA; 8], HashAlgorithm::Sha256, 128);
        let k2 = derive_key("pw", &[1, 2, 3, 4], 10, &[0xAA; 8], HashAlgorithm::Sha256, 128);
        assert_eq!(*k1, *k2);

        // Different block key → different output
        let k3 = derive_key("pw", &[1, 2, 3, 4], 10, &[0xBB; 8], HashAlgorithm::Sha256, 128);
        assert_ne!(*k1, *k3);
    }

    #[test]
    fn make_iv_exact() {
        let data = vec![1u8; 16];
        let iv = make_iv(&data, 16);
        assert_eq!(iv.len(), 16);
        assert_eq!(iv, data);
    }

    #[test]
    fn make_iv_truncate() {
        let data = vec![1u8; 32];
        let iv = make_iv(&data, 16);
        assert_eq!(iv.len(), 16);
    }

    #[test]
    fn make_iv_pad() {
        let data = vec![1u8; 8];
        let iv = make_iv(&data, 16);
        assert_eq!(iv.len(), 16);
        assert_eq!(&iv[..8], &[1u8; 8]);
        assert_eq!(&iv[8..], &[HASH_PAD_BYTE; 8]);
    }

    #[test]
    fn aes_cbc_decrypt_roundtrip() {
        // Encrypt with known key/iv, then decrypt and verify
        use aes::cipher::{block_padding::NoPadding, BlockEncryptMut, KeyIvInit};
        type Aes128CbcEnc = cbc::Encryptor<aes::Aes128>;

        let key = [0x42u8; 16];
        let iv = [0u8; 16];
        let plaintext = [0xAAu8; 32]; // 2 AES blocks

        let mut buf = plaintext.to_vec();
        Aes128CbcEnc::new(&key.into(), &iv.into())
            .encrypt_padded_mut::<NoPadding>(&mut buf, 32)
            .unwrap();

        let decrypted = aes_cbc_decrypt(&key, &iv, &buf).unwrap();
        assert_eq!(&decrypted[..32], &plaintext);
    }

    #[test]
    fn parse_encryption_info_no_data() {
        let page0 = vec![0u8; 4096];
        let result = parse_encryption_info(&page0).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn parse_encryption_info_too_small() {
        let page0 = vec![0u8; 0x299];
        let result = parse_encryption_info(&page0).unwrap();
        assert!(result.is_none());
    }

    /// Test with real .accdb file if available
    #[test]
    fn parse_and_verify_enc_v2007() {
        let path = skip_if_missing!("enc_vbaV2007.accdb");

        // Read page 0 manually
        use std::io::Read;
        let mut file = std::fs::File::open(&path).unwrap();
        let mut page0 = vec![0u8; 4096];
        file.read_exact(&mut page0).unwrap();

        // Decrypt header region (RC4)
        let version = JetVersion::from_byte(page0[db_header::VERSION]).unwrap();
        assert!(version.is_accdb());

        // RC4 decrypt header
        let enc_len = 128;
        let end = db_header::ENCRYPTED_START + enc_len;
        rc4_transform(&HEADER_RC4_KEY, &mut page0[db_header::ENCRYPTED_START..end]);

        // Parse EncryptionInfo
        let enc_params = parse_encryption_info(&page0).unwrap();
        assert!(enc_params.is_some(), "EncryptionInfo should be present");
        let enc_params = enc_params.unwrap();

        // Should be Agile encryption
        let agile_params = match &enc_params {
            EncryptionParams::Agile(p) => p,
            other => panic!("expected Agile, got {other:?}"),
        };

        // Verify correct password
        let db_key = verify_password(agile_params, "1234567890");
        assert!(db_key.is_ok(), "correct password should verify: {:?}", db_key.err());
        let db_key = db_key.unwrap();
        assert_eq!(db_key.len(), agile_params.key_bits / 8);

        // Verify incorrect password
        let result = verify_password(agile_params, "wrongpassword");
        assert!(matches!(result, Err(FileError::InvalidPassword)));
    }

    /// Helper: read page 0 and decrypt the header region for EncryptionInfo parsing.
    fn read_and_decrypt_page0(path: &std::path::Path) -> Vec<u8> {
        use std::io::Read;
        let mut file = std::fs::File::open(path).unwrap();
        let mut page0 = vec![0u8; 4096];
        file.read_exact(&mut page0).unwrap();
        let enc_len = 128;
        let end = db_header::ENCRYPTED_START + enc_len;
        rc4_transform(&HEADER_RC4_KEY, &mut page0[db_header::ENCRYPTED_START..end]);
        page0
    }

    #[test]
    fn parse_and_verify_rc4_cryptoapi() {
        let path = skip_if_missing!("db2007-rc4cryptoapi.accdb");
        let page0 = read_and_decrypt_page0(&path);

        let enc_params = parse_encryption_info(&page0).unwrap();
        assert!(enc_params.is_some(), "EncryptionInfo should be present");
        let enc_params = enc_params.unwrap();

        let params = match &enc_params {
            EncryptionParams::Rc4CryptoApi(p) => p,
            other => panic!("expected Rc4CryptoApi, got {other:?}"),
        };

        assert!(params.key_size == 40 || params.key_size == 128);
        assert!(params.verifier_hash_size > 0 && params.verifier_hash_size <= 20);

        // Correct password
        let base_hash = verify_password_rc4_cryptoapi(params, "Test123");
        assert!(base_hash.is_ok(), "correct password should verify: {:?}", base_hash.err());

        // Wrong password
        let result = verify_password_rc4_cryptoapi(params, "WrongPassword");
        assert!(matches!(result, Err(FileError::InvalidPassword)));
    }

    #[test]
    fn parse_and_verify_nonstandard_aes() {
        let path = skip_if_missing!("db-nonstandard-aes.accdb");
        let page0 = read_and_decrypt_page0(&path);

        let enc_params = parse_encryption_info(&page0).unwrap();
        assert!(enc_params.is_some(), "EncryptionInfo should be present");
        let enc_params = enc_params.unwrap();

        let params = match &enc_params {
            EncryptionParams::StandardAes(p) => p,
            other => panic!("expected StandardAes, got {other:?}"),
        };

        assert!(params.key_size == 128 || params.key_size == 192 || params.key_size == 256);
        assert_eq!(params.hash_iterations, 0, "NonStandard AES has 0 iterations");
        assert!(params.verifier_hash_size > 0 && params.verifier_hash_size <= 20);

        // Correct password
        let iter_hash = verify_password_standard_aes(params, "password");
        assert!(iter_hash.is_ok(), "correct password should verify: {:?}", iter_hash.err());

        // Wrong password
        let result = verify_password_standard_aes(params, "WrongPassword");
        assert!(matches!(result, Err(FileError::InvalidPassword)));
    }

    // NOTE: No Standard AES test (hash_iterations > 0) because we lack test data —
    // Access/Office-encrypted files with iterations>0 are not publicly available.
    // The NonStandard AES test above covers the shared code path; the only
    // difference is iterate_hash_sha1 looping (vs. returning base_hash unchanged).

    // -- Validation tests (synthetic data) ------------------------------------

    /// Build a minimal page0 with an EncryptionInfo payload at the correct offset.
    fn build_page0_with_info(info_data: &[u8]) -> Vec<u8> {
        let offset = db_header::ENCRYPTION_INFO_OFFSET;
        let total = offset + 2 + info_data.len();
        let mut page0 = vec![0u8; total.max(4096)];
        let len = info_data.len() as u16;
        page0[offset] = len as u8;
        page0[offset + 1] = (len >> 8) as u8;
        page0[offset + 2..offset + 2 + info_data.len()].copy_from_slice(info_data);
        page0
    }

    #[test]
    fn parse_encryption_info_too_short_for_version() {
        // info_data is non-zero length but < 4 bytes: should error
        let page0 = build_page0_with_info(&[0x01, 0x02]);
        let result = parse_encryption_info(&page0);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(&err, FileError::UnsupportedEncryption { reason } if reason.contains("too short")),
            "expected 'too short' error, got: {err}"
        );
    }

    #[test]
    fn parse_cryptoapi_header_size_huge() {
        // version (3, 2) + flags with FCRYPTO_API_FLAG but no FAES_FLAG
        // header_size = u32::MAX: on 64-bit this exceeds data length,
        // on 32-bit it triggers checked_add overflow. Either way, must error.
        let mut info_data = vec![0u8; 16];
        info_data[0] = 3; // vMajor=3
        info_data[2] = 2; // vMinor=2
        info_data[4] = 0x04; // FCRYPTO_API_FLAG
        // header_size = u32::MAX
        info_data[8] = 0xFF;
        info_data[9] = 0xFF;
        info_data[10] = 0xFF;
        info_data[11] = 0xFF;
        let page0 = build_page0_with_info(&info_data);
        let result = parse_encryption_info(&page0);
        assert!(
            matches!(&result, Err(FileError::UnsupportedEncryption { .. })),
            "expected UnsupportedEncryption error, got: {result:?}"
        );
    }

    #[test]
    fn parse_standard_aes_header_size_huge() {
        // version (3, 2) + flags with FCRYPTO_API_FLAG + FAES_FLAG
        // header_size = u32::MAX
        let mut info_data = vec![0u8; 16];
        info_data[0] = 3; // vMajor=3
        info_data[2] = 2; // vMinor=2
        info_data[4] = 0x24; // FCRYPTO_API_FLAG | FAES_FLAG
        // header_size = u32::MAX
        info_data[8] = 0xFF;
        info_data[9] = 0xFF;
        info_data[10] = 0xFF;
        info_data[11] = 0xFF;
        let page0 = build_page0_with_info(&info_data);
        let result = parse_encryption_info(&page0);
        assert!(
            matches!(&result, Err(FileError::UnsupportedEncryption { .. })),
            "expected UnsupportedEncryption error, got: {result:?}"
        );
    }

    #[test]
    fn parse_cryptoapi_invalid_rc4_key_size() {
        // Build a minimal RC4 CryptoAPI header with invalid key_size=64
        let mut info_data = vec![0u8; 200];
        info_data[0] = 3; // vMajor=3
        info_data[2] = 2; // vMinor=2
        info_data[4] = 0x04; // FCRYPTO_API_FLAG

        // After flags (offset 8 in info_data), CryptoAPI data begins:
        // header_size = 40 (enough for EncryptionHeader)
        info_data[8] = 40;
        // EncryptionHeader at offset 12: flags(4) + sizeExtra(4) + algId(4) + algIdHash(4) + keySize(4)
        // algId = ALGID_RC4 (0x6801) at header offset 8 (info offset 20)
        info_data[20] = 0x01;
        info_data[21] = 0x68;
        // keySize = 64 (invalid for RC4) at header offset 16 (info offset 28)
        info_data[28] = 64;

        let page0 = build_page0_with_info(&info_data);
        let result = parse_encryption_info(&page0);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(&err, FileError::UnsupportedEncryption { reason } if reason.contains("invalid RC4")),
            "expected invalid RC4 key size error, got: {err}"
        );
    }

    #[test]
    fn parse_cryptoapi_invalid_aes_key_size() {
        // Build a minimal NonStandard AES header with invalid key_size=64
        let mut info_data = vec![0u8; 200];
        info_data[0] = 3; // vMajor=3
        info_data[2] = 2; // vMinor=2
        info_data[4] = 0x04; // FCRYPTO_API_FLAG (no FAES_FLAG)

        // header_size = 40
        info_data[8] = 40;
        // algId = ALGID_AES_128 (0x660E) at header offset 8 (info offset 20)
        info_data[20] = 0x0E;
        info_data[21] = 0x66;
        // keySize = 64 (invalid for AES) at header offset 16 (info offset 28)
        info_data[28] = 64;

        let page0 = build_page0_with_info(&info_data);
        let result = parse_encryption_info(&page0);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(&err, FileError::UnsupportedEncryption { reason } if reason.contains("invalid AES")),
            "expected invalid AES key size error, got: {err}"
        );
    }

    #[test]
    fn verify_rc4_cryptoapi_invalid_hash_size_zero() {
        let params = Rc4CryptoApiParams {
            salt: [0u8; 16],
            encrypted_verifier: [0u8; 16],
            verifier_hash_size: 0,
            encrypted_verifier_hash: vec![0u8; 20],
            key_size: 128,
        };
        let result = verify_password_rc4_cryptoapi(&params, "test");
        assert!(
            matches!(&result, Err(FileError::UnsupportedEncryption { reason }) if reason.contains("invalid verifier hash size")),
            "expected invalid verifier hash size error, got: {result:?}"
        );
    }

    #[test]
    fn verify_rc4_cryptoapi_invalid_hash_size_too_large() {
        let params = Rc4CryptoApiParams {
            salt: [0u8; 16],
            encrypted_verifier: [0u8; 16],
            verifier_hash_size: 21,
            encrypted_verifier_hash: vec![0u8; 21],
            key_size: 128,
        };
        let result = verify_password_rc4_cryptoapi(&params, "test");
        assert!(
            matches!(&result, Err(FileError::UnsupportedEncryption { reason }) if reason.contains("invalid verifier hash size")),
            "expected invalid verifier hash size error, got: {result:?}"
        );
    }

    #[test]
    fn verify_standard_aes_invalid_hash_size_zero() {
        let params = StandardAesParams {
            salt: [0u8; 16],
            encrypted_verifier: [0u8; 16],
            verifier_hash_size: 0,
            encrypted_verifier_hash: vec![0u8; 32],
            key_size: 128,
            hash_iterations: 0,
        };
        let result = verify_password_standard_aes(&params, "test");
        assert!(
            matches!(&result, Err(FileError::UnsupportedEncryption { reason }) if reason.contains("invalid verifier hash size")),
            "expected invalid verifier hash size error, got: {result:?}"
        );
    }

    #[test]
    fn verify_standard_aes_invalid_hash_size_too_large() {
        let params = StandardAesParams {
            salt: [0u8; 16],
            encrypted_verifier: [0u8; 16],
            verifier_hash_size: 21,
            encrypted_verifier_hash: vec![0u8; 32],
            key_size: 128,
            hash_iterations: 0,
        };
        let result = verify_password_standard_aes(&params, "test");
        assert!(
            matches!(&result, Err(FileError::UnsupportedEncryption { reason }) if reason.contains("invalid verifier hash size")),
            "expected invalid verifier hash size error, got: {result:?}"
        );
    }
}