luks 0.4.3

Pure-Rust Library for the Linux Unified Key Setup
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
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
#[cfg(feature = "_write")]
use byteorder::WriteBytesExt;
use byteorder::{BigEndian, ReadBytesExt};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fmt;
use std::io::{Read, Seek, Write};
use std::str::FromStr;
use thiserror::Error;

#[cfg(feature = "_challenge_response")]
pub mod challenge_response;

#[cfg(feature = "_challenge_response")]
use crate::challenge_response::ChallengeResponseSlot;

use aes::cipher::KeyInit;
use base64::Engine as _;
#[cfg(feature = "_write")]
use rand::RngExt;
use sha2::Sha512;
use std::io::SeekFrom;
use std::path::Path;
use std::process::{Command, Stdio};
use xts_mode::{Xts128, get_tweak_default};

pub mod af;
pub mod hash;
pub mod kdf;
pub mod key;
pub mod keyslot;

pub use af::{LUKS1_AF_STRIPES, Luks2Af, Luks2AfType};
pub use hash::{
    HASH_SHA256, HASH_SHA512, LUKS2_CHECKSUM_ALG_ID_LEN, Luks2HashAlg, SHA256_DIGEST_SIZE, SHA512_DIGEST_SIZE,
};
pub use kdf::Luks2Kdf;
pub use key::{UnlockKey, VolumeKey};
pub use keyslot::{
    KeySlotId, Luks2Area, Luks2AreaEncryption, Luks2KeySize, Luks2Keyslot, Luks2KeyslotPriority,
    Luks2ReencryptDirection, Luks2ReencryptMode,
};

/// A representation of a LUKS device, including its header and keyslots.
///
/// This structure holds the primary metadata for the encrypted device.
#[derive(Serialize, Deserialize)]
pub struct LuksDevice {
    /// The LUKS header (either version 1 or 2).
    pub header: LuksHeader,
    /// A map of keyslot IDs to their raw, encrypted data area.
    pub keyslots: HashMap<KeySlotId, Vec<u8>>,
    /// The volume key, if the device has been successfully unlocked.
    #[serde(skip)]
    pub unlocked_key: Option<VolumeKey>,
}

impl LuksDevice {
    /// Returns a list of keyslot IDs that are associated with a challenge-response token.
    #[cfg(feature = "_challenge_response")]
    pub fn get_challenge_response_keyslots(&self) -> Vec<(KeySlotId, Option<u32>, ChallengeResponseSlot)> {
        let mut results = Vec::new();
        match &self.header {
            LuksHeader::V1 => {}
            LuksHeader::V2(h) => {
                for token in h.metadata.tokens.values() {
                    if let Luks2Token::ChallengeResponse {
                        keyslots,
                        serial,
                        slot,
                    } = token
                    {
                        for id in keyslots {
                            results.push((id.clone(), *serial, slot.clone()));
                        }
                    }
                }
            }
        }
        results
    }

    /// Unlocks the device with a passphrase, storing the volume key in the device.
    pub fn unlock(&mut self, keyslot_id: &KeySlotId, key: &UnlockKey) -> Result<(), LuksError> {
        let volume_key = self.get_volume_key(keyslot_id, key)?;
        self.unlocked_key = Some(volume_key);

        if self.verify(keyslot_id)? {
            Ok(())
        } else {
            self.unlocked_key = None;
            Err(LuksError::Kdf("Passphrase verification failed".to_string()))
        }
    }

    /// Writes the LUKS device to a writer.
    #[cfg(feature = "_write")]
    pub fn to_writer<W: Write + Seek>(&self, mut writer: W) -> Result<(), LuksError> {
        self.header.to_writer(&mut writer)?;

        match &self.header {
            LuksHeader::V1 => return Err(LuksError::UnsupportedVersion(1)),
            LuksHeader::V2(h) => {
                for (id, slot) in &h.metadata.keyslots {
                    let area = slot.area();
                    let data = self.keyslots.get(id).ok_or_else(|| {
                        LuksError::InvalidHeader(format!("Data for keyslot {} not found", id))
                    })?;
                    writer.seek(std::io::SeekFrom::Start(area.offset()))?;
                    writer.write_all(data)?;
                }
            }
        }

        Ok(())
    }

    /// Verifies that the current unlocked volume key matches a specific keyslot.
    ///
    /// # Errors
    ///
    /// Returns `LuksError::Locked` if the device has not been unlocked.
    pub fn verify(&self, keyslot_id: &KeySlotId) -> Result<bool, LuksError> {
        let volume_key = self.unlocked_key.as_ref().ok_or(LuksError::Locked)?;

        let h2 = match &self.header {
            LuksHeader::V1 => return Err(LuksError::UnsupportedVersion(1)),
            LuksHeader::V2(h) => h,
        };

        // Find the digest associated with this keyslot
        let (_digest_id, digest) = h2
            .metadata
            .digests
            .iter()
            .find(|(_, d)| match d {
                Luks2Digest::Pbkdf2 { keyslots, .. } => keyslots.contains(keyslot_id),
            })
            .ok_or_else(|| LuksError::InvalidHeader(format!("No digest found for keyslot {}", keyslot_id)))?;

        let (digest_hash, digest_salt, expected_digest, digest_iterations) = match digest {
            Luks2Digest::Pbkdf2 {
                hash,
                salt,
                digest,
                iterations,
                ..
            } => (hash, salt, digest, iterations),
        };

        // 5. Verify the volume key using the digest
        let kdf_digest_salt = base64::engine::general_purpose::STANDARD
            .decode(digest_salt)
            .map_err(|e| LuksError::Kdf(format!("Invalid salt base64 in digest: {}", e)))?;

        let expected_bytes = base64::engine::general_purpose::STANDARD
            .decode(expected_digest)
            .map_err(|e| LuksError::Kdf(format!("Invalid digest base64 in digest: {}", e)))?;

        let mut verification_output = vec![0u8; expected_bytes.len()];
        if digest_hash == &Luks2HashAlg::Sha256 {
            pbkdf2::pbkdf2::<hmac::Hmac<Sha256>>(
                volume_key.expose_bytes(),
                &kdf_digest_salt,
                *digest_iterations,
                &mut verification_output,
            )
            .map_err(|e| LuksError::Kdf(format!("PBKDF2 SHA256 error: {}", e)))?;
        } else if digest_hash == &Luks2HashAlg::Sha512 {
            pbkdf2::pbkdf2::<hmac::Hmac<Sha512>>(
                volume_key.expose_bytes(),
                &kdf_digest_salt,
                *digest_iterations,
                &mut verification_output,
            )
            .map_err(|e| LuksError::Kdf(format!("PBKDF2 SHA512 error: {}", e)))?;
        } else {
            return Err(LuksError::UnsupportedChecksumAlg(digest_hash.to_string()));
        }

        Ok(verification_output == expected_bytes)
    }

    /// Derives the volume key using a passphrase and a specific keyslot.
    pub fn get_volume_key(&self, keyslot_id: &KeySlotId, key: &UnlockKey) -> Result<VolumeKey, LuksError> {
        let h2 = match &self.header {
            LuksHeader::V1 => return Err(LuksError::UnsupportedVersion(1)),
            LuksHeader::V2(h) => h,
        };

        let keyslot = h2
            .metadata
            .keyslots
            .get(keyslot_id)
            .ok_or_else(|| LuksError::InvalidHeader(format!("Keyslot {} not found", keyslot_id)))?;

        let (kdf, key_size, area, af) = match keyslot {
            Luks2Keyslot::Luks2 {
                kdf,
                key_size,
                area,
                af,
                ..
            } => (kdf, u64::from(*key_size), area, af),
            Luks2Keyslot::Reencrypt { .. } => {
                return Err(LuksError::Kdf(
                    "Verification for reencrypt keyslots not yet supported".to_string(),
                ));
            }
        };

        let Luks2Area::Raw { encryption, .. } = area else {
            return Err(LuksError::InvalidHeader(
                "LUKS2 keyslot must have area type 'raw'".to_string(),
            ));
        };

        // 1. Derive the keyslot key from the passphrase
        let keyslot_key = kdf.derive_key(key, &h2.salt, key_size as usize)?;
        // 2. Get the encrypted data from the captured keyslots
        let encrypted_data = self
            .keyslots
            .get(keyslot_id)
            .ok_or_else(|| LuksError::InvalidHeader(format!("Data for keyslot {} not captured", keyslot_id)))?;

        // 3. Decrypt the area
        if *encryption != Luks2AreaEncryption::AesXtsPlain64 {
            return Err(LuksError::UnsupportedChecksumAlg(format!(
                "Area encryption {} is not supported",
                encryption
            )));
        }

        let mut decrypted_data = encrypted_data.clone();
        if key_size == (AES128_KEY_SIZE as u64 * 2) {
            let cipher_1 = aes::Aes128::new_from_slice(&keyslot_key[0..AES128_KEY_SIZE])
                .map_err(|e| LuksError::Kdf(format!("Cipher error: {}", e)))?;
            let cipher_2 = aes::Aes128::new_from_slice(&keyslot_key[AES128_KEY_SIZE..AES128_KEY_SIZE * 2])
                .map_err(|e| LuksError::Kdf(format!("Cipher error: {}", e)))?;
            let xts = Xts128::new(cipher_1, cipher_2);

            for (i, chunk) in decrypted_data.chunks_mut(SECTOR_SIZE).enumerate() {
                xts.decrypt_area(chunk, SECTOR_SIZE, (i as u64).into(), |t| get_tweak_default(t));
            }
        } else if key_size == (AES256_KEY_SIZE as u64 * 2) {
            let cipher_1 = aes::Aes256::new_from_slice(&keyslot_key[0..AES256_KEY_SIZE])
                .map_err(|e| LuksError::Kdf(format!("Cipher error: {}", e)))?;
            let cipher_2 = aes::Aes256::new_from_slice(&keyslot_key[AES256_KEY_SIZE..AES256_KEY_SIZE * 2])
                .map_err(|e| LuksError::Kdf(format!("Cipher error: {}", e)))?;
            let xts = Xts128::new(cipher_1, cipher_2);

            for (i, chunk) in decrypted_data.chunks_mut(SECTOR_SIZE).enumerate() {
                xts.decrypt_area(chunk, SECTOR_SIZE, (i as u64).into(), |t| get_tweak_default(t));
            }
        } else {
            return Err(LuksError::Kdf(format!(
                "Unsupported key size {} for AES-XTS",
                key_size
            )));
        }

        // 4. Merge AF stripes to get the volume key
        let volume_key_bytes = crate::af::merge(
            &decrypted_data[0..(key_size as u64 * af.stripes as u64) as usize],
            &af.hash,
            af.stripes,
            key_size as usize,
        )?;
        VolumeKey::new(volume_key_bytes)
    }

    /// Maps the LUKS device using dmsetup.
    pub fn map_with_dmsetup(&self, name: &str, backing_device: &Path) -> Result<(), LuksError> {
        let volume_key = self.unlocked_key.as_ref().ok_or(LuksError::Locked)?;

        let h2 = match &self.header {
            LuksHeader::V1 => return Err(LuksError::UnsupportedVersion(1)),
            LuksHeader::V2(h) => h,
        };

        // Find the crypt segment
        let segment = h2
            .metadata
            .segments
            .iter()
            .find_map(|(_, s)| match s {
                Luks2Segment::Crypt { .. } => Some(s),
            })
            .ok_or_else(|| LuksError::InvalidHeader("No crypt segment found".to_string()))?;

        let Luks2Segment::Crypt {
            offset,
            iv_tweak,
            size,
            encryption,
            ..
        } = segment;

        // Calculate sectors
        let num_sectors = match size {
            Luks2SegmentSize::U64(s) => s / SECTOR_SIZE as u64,
            Luks2SegmentSize::Dynamic => {
                let mut file = std::fs::File::open(backing_device)?;
                let total_size = file.seek(SeekFrom::End(0))?;
                (total_size - offset.0) / SECTOR_SIZE as u64
            }
        };

        // Construct the table string
        // Table format: <start> <length> <target_type> <cipher> <key> <iv_offset> <device_path> <offset>
        let table = format!(
            "0 {} crypt {} {} {} {} {}\n",
            num_sectors,
            encryption,
            to_hex(volume_key.expose_bytes()),
            iv_tweak.0,
            backing_device.to_string_lossy(),
            offset.0 / SECTOR_SIZE as u64
        );

        // Call dmsetup create <name>
        let mut child = Command::new("dmsetup")
            .arg("create")
            .arg(name)
            .stdin(Stdio::piped())
            .spawn()?;

        // Pipe the table to stdin
        if let Some(mut child_stdin) = child.stdin.take() {
            child_stdin.write_all(table.as_bytes())?;
        }

        let status = child.wait()?;
        if !status.success() {
            return Err(LuksError::DmSetup(format!("exit code {}", status)));
        }

        Ok(())
    }

    /// Changes the unlock key for a specific keyslot without changing the volume key.
    ///
    /// This only updates the metadata in memory. You must call [`to_writer`] to persist the changes.
    #[cfg(feature = "_write")]
    pub fn change_unlock_key(
        &mut self,
        keyslot_id: &KeySlotId,
        old_key: &UnlockKey,
        new_key: &UnlockKey,
    ) -> Result<(), LuksError> {
        let volume_key = self.get_volume_key(keyslot_id, old_key)?;
        self.update_keyslot(keyslot_id, new_key, &volume_key)
    }

    #[cfg(feature = "_write")]
    fn update_keyslot(
        &mut self,
        keyslot_id: &KeySlotId,
        key: &UnlockKey,
        volume_key: &VolumeKey,
    ) -> Result<(), LuksError> {
        let h2 = match &mut self.header {
            LuksHeader::V1 => return Err(LuksError::UnsupportedVersion(1)),
            LuksHeader::V2(h) => h,
        };

        let keyslot = h2
            .metadata
            .keyslots
            .get_mut(keyslot_id)
            .ok_or_else(|| LuksError::InvalidHeader(format!("Keyslot {} not found", keyslot_id)))?;

        let (kdf, key_size, area, af) = match keyslot {
            Luks2Keyslot::Luks2 {
                kdf,
                key_size,
                area,
                af,
                ..
            } => (kdf, u64::from(*key_size), area, af),
            Luks2Keyslot::Reencrypt { .. } => {
                return Err(LuksError::Kdf(
                    "Changing passphrase for reencrypt keyslots not supported".to_string(),
                ));
            }
        };

        let Luks2Area::Raw { encryption, .. } = area else {
            return Err(LuksError::InvalidHeader(
                "LUKS2 keyslot must have area type 'raw'".to_string(),
            ));
        };

        // 1. Generate new KDF salt
        let mut new_salt = vec![0u8; KDF_SALT_SIZE];
        rand::rng().fill(&mut new_salt[..]);
        let new_salt_b64 = base64::engine::general_purpose::STANDARD.encode(new_salt);

        // Update salt in KDF
        match kdf {
            Luks2Kdf::Argon2i { salt, .. } => *salt = new_salt_b64,
            Luks2Kdf::Argon2id { salt, .. } => *salt = new_salt_b64,
            Luks2Kdf::Pbkdf2 { salt, .. } => *salt = new_salt_b64,
        }

        // 2. Derive the new keyslot key
        let keyslot_key = kdf.derive_key(key, &h2.salt, key_size as usize)?;
        // 3. AF-split the volume key
        let mut random_stripes =
            vec![0u8; (volume_key.expose_bytes().len() as u32 * (af.stripes - 1)) as usize];
        rand::rng().fill(&mut random_stripes[..]);
        let split_data = crate::af::split(
            volume_key.expose_bytes(),
            &af.hash,
            af.stripes,
            volume_key.expose_bytes().len(),
            random_stripes,
        )?;

        // 4. Encrypt the area
        if *encryption != Luks2AreaEncryption::AesXtsPlain64 {
            return Err(LuksError::UnsupportedChecksumAlg(format!(
                "Area encryption {} is not supported",
                encryption
            )));
        }

        let mut encrypted_data = split_data.clone();
        if key_size == (AES128_KEY_SIZE as u64 * 2) {
            let cipher_1 = aes::Aes128::new_from_slice(&keyslot_key[0..AES128_KEY_SIZE])
                .map_err(|e| LuksError::Kdf(format!("Cipher error: {}", e)))?;
            let cipher_2 = aes::Aes128::new_from_slice(&keyslot_key[AES128_KEY_SIZE..AES128_KEY_SIZE * 2])
                .map_err(|e| LuksError::Kdf(format!("Cipher error: {}", e)))?;
            let xts = Xts128::new(cipher_1, cipher_2);

            for (i, chunk) in encrypted_data.chunks_mut(SECTOR_SIZE).enumerate() {
                xts.encrypt_area(chunk, SECTOR_SIZE, (i as u64).into(), |t| get_tweak_default(t));
            }
        } else if key_size == (AES256_KEY_SIZE as u64 * 2) {
            let cipher_1 = aes::Aes256::new_from_slice(&keyslot_key[0..AES256_KEY_SIZE])
                .map_err(|e| LuksError::Kdf(format!("Cipher error: {}", e)))?;
            let cipher_2 = aes::Aes256::new_from_slice(&keyslot_key[AES256_KEY_SIZE..AES256_KEY_SIZE * 2])
                .map_err(|e| LuksError::Kdf(format!("Cipher error: {}", e)))?;
            let xts = Xts128::new(cipher_1, cipher_2);

            for (i, chunk) in encrypted_data.chunks_mut(SECTOR_SIZE).enumerate() {
                xts.encrypt_area(chunk, SECTOR_SIZE, (i as u64).into(), |t| get_tweak_default(t));
            }
        } else {
            return Err(LuksError::Kdf(format!(
                "Unsupported key size {} for AES-XTS",
                key_size
            )));
        }

        // 5. Update self.keyslots
        self.keyslots.insert(keyslot_id.clone(), encrypted_data);

        // Add/remove tokens if necessary
        #[cfg(feature = "_challenge_response")]
        {
            if let Some(cr) = key.challenge_response() {
                // Check if a token already exists for this keyslot
                let h2 = match &mut self.header {
                    LuksHeader::V2(h) => h,
                    _ => unreachable!(),
                };

                let mut found = false;
                for token in h2.metadata.tokens.values_mut() {
                    if let Luks2Token::ChallengeResponse {
                        keyslots,
                        serial: _,
                        slot: _,
                    } = token
                    {
                        if keyslots.contains(keyslot_id) {
                            found = true;
                            break;
                        }
                    }
                }

                if !found {
                    // Create a new token
                    let mut next_id = 0;
                    while h2.metadata.tokens.contains_key(&next_id.to_string()) {
                        next_id += 1;
                    }

                    match cr {
                        crate::key::ChallengeResponseKey::Hardware { serial, slot } => {
                            h2.metadata.tokens.insert(
                                next_id.to_string(),
                                Luks2Token::ChallengeResponse {
                                    keyslots: vec![keyslot_id.clone()],
                                    serial: *serial,
                                    slot: slot.clone(),
                                },
                            );
                        }
                        crate::key::ChallengeResponseKey::Software { .. } => {
                            h2.metadata.tokens.insert(
                                next_id.to_string(),
                                Luks2Token::ChallengeResponse {
                                    keyslots: vec![keyslot_id.clone()],
                                    serial: None,
                                    slot: ChallengeResponseSlot::Slot1, // Default slot for software
                                },
                            );
                        }
                    }
                }
            } else {
                // Remove token if it exists and only points to this keyslot
                let h2 = match &mut self.header {
                    LuksHeader::V2(h) => h,
                    _ => unreachable!(),
                };

                let mut token_to_remove = None;
                for (id, token) in &mut h2.metadata.tokens {
                    if let Luks2Token::ChallengeResponse {
                        keyslots,
                        serial: _,
                        slot: _,
                    } = token
                    {
                        if keyslots.contains(keyslot_id) {
                            keyslots.retain(|k| k != keyslot_id);
                            if keyslots.is_empty() {
                                token_to_remove = Some(id.clone());
                            }
                        }
                    }
                }
                if let Some(id) = token_to_remove {
                    h2.metadata.tokens.remove(&id);
                }
            }
        }

        Ok(())
    }
}

/// Returns true if the device at the given path is a LUKS device.
///
/// This only checks the magic signature at the beginning of the device.
pub fn is_luks_device<P: AsRef<Path>>(path: P) -> Result<bool, LuksError> {
    let mut file = std::fs::File::open(path)?;
    let mut buffer = [0u8; LUKS_MAGIC_SIZE];
    match file.read_exact(&mut buffer) {
        Ok(_) => Ok(buffer == LUKS_MAGIC),
        Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(false),
        Err(e) => Err(LuksError::Io(e)),
    }
}

/// The magic signature for LUKS devices: "LUKS\xBA\xBE".
pub const LUKS_MAGIC: [u8; 6] = *b"LUKS\xBA\xBE";

/// Size of the LUKS magic signature in bytes.
pub const LUKS_MAGIC_SIZE: usize = 6;
/// Size of the LUKS version field in bytes.
pub const LUKS_VERSION_SIZE: usize = 2;

/// Size of the LUKS2 label field in bytes.
pub const LUKS2_LABEL_SIZE: usize = 48;
/// Size of the LUKS2 salt field in bytes.
pub const LUKS2_SALT_SIZE: usize = 64;
/// Size of the LUKS2 uuid field in bytes.
pub const LUKS2_UUID_SIZE: usize = 40;
/// Size of the LUKS2 subsystem field in bytes.
pub const LUKS2_SUBSYSTEM_SIZE: usize = 48;
/// Size of the LUKS2 checksum field in bytes.
pub const LUKS2_CHECKSUM_SIZE: usize = 64;

/// The standard sector size in bytes.
pub const SECTOR_SIZE: usize = 512;

/// The size of a KDF salt in bytes.
pub const KDF_SALT_SIZE: usize = 32;

/// The offset in bytes where the LUKS2 checksum field begins.
pub const LUKS2_CHECKSUM_OFFSET: usize = 448;
/// The size of the LUKS2 binary header area in bytes.
pub const LUKS2_BINARY_HEADER_SIZE: usize = 4096;

/// The block size for the AES cipher in bytes.
pub const AES_BLOCK_SIZE: usize = 16;
/// The key size for AES-128 in bytes.
pub const AES128_KEY_SIZE: usize = 16;
/// The key size for AES-256 in bytes.
pub const AES256_KEY_SIZE: usize = 32;

/// The number of anti-forensic stripes used by the LUKS1 AF feature.
///
/// For historical reasons, this value is always 4000.
/// Default size of the LUKS2 JSON area in bytes.
pub const LUKS2_DEFAULT_JSON_SIZE: u64 = 12288;
/// Default size of the LUKS2 keyslots area in bytes.
pub const LUKS2_DEFAULT_KEYSLOTS_SIZE: u64 = 4161536;

/// Errors that can occur when working with LUKS devices.
#[derive(Error, Debug)]
pub enum LuksError {
    /// An I/O error occurred.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    /// The LUKS magic signature is invalid or missing.
    #[error("Invalid LUKS magic: {0:?}")]
    InvalidMagic([u8; LUKS_MAGIC_SIZE]),
    /// The LUKS version is not supported by this library.
    #[error("Unsupported LUKS version: {0}")]
    UnsupportedVersion(u16),
    /// An error occurred while parsing JSON metadata.
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    /// The LUKS2 header or metadata is malformed or invalid.
    #[error("Invalid LUKS2 header: {0}")]
    InvalidHeader(String),
    /// The header checksum verification failed.
    #[error("Checksum verification failed: expected {expected}, got {actual}")]
    InvalidChecksum { expected: String, actual: String },
    /// The requested checksum or hash algorithm is not supported.
    #[error("Unsupported checksum algorithm: {0}")]
    UnsupportedChecksumAlg(String),
    /// An error occurred during key derivation (KDF).
    #[error("KDF error: {0}")]
    Kdf(String),
    /// An error occurred when interacting with `dmsetup`.
    #[error("dmsetup failed: {0}")]
    DmSetup(String),
    /// The operation requires an unlocked device, but it is currently locked.
    #[error("Device is locked")]
    Locked,
    #[cfg(feature = "_challenge_response")]
    /// An error occurred during challenge-response authentication.
    #[error("Challenge-response error: {0}")]
    ChallengeResponse(String),
}

/// A 64-bit unsigned integer that is represented as a decimal string in JSON.
///
/// This is necessary because JSON's standard number type is a double-precision floating point
/// value (IEEE 754), which cannot accurately represent the full range of 64-bit integers
/// without losing precision. By encoding large integers as strings, LUKS2 ensures that
/// values like offsets and sizes remain exact.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Luks2U64(pub u64);

impl Serialize for Luks2U64 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0.to_string())
    }
}

impl<'de> Deserialize<'de> for Luks2U64 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse::<u64>().map(Luks2U64).map_err(serde::de::Error::custom)
    }
}

/// A LUKS2 token, used to store additional metadata or references to external keys.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Luks2Token {
    /// A standard Linux kernel keyring token.
    #[serde(rename = "luks2-keyring")]
    Keyring {
        /// The IDs of the keyslots associated with this token.
        keyslots: Vec<KeySlotId>,
        /// The description of the key in the keyring.
        key_description: String,
    },
    /// A `luks-rs` specific keyring token.
    #[serde(rename = "luks-rs-keyring")]
    LuksRsKeyring {
        /// The IDs of the keyslots associated with this token.
        keyslots: Vec<KeySlotId>,
        /// The description of the key in the keyring.
        key_description: String,
    },
    #[cfg(feature = "_challenge_response")]
    /// A challenge-response token.
    #[serde(rename = "luks2-challenge-response")]
    ChallengeResponse {
        /// The IDs of the keyslots associated with this token.
        keyslots: Vec<KeySlotId>,
        /// The serial number of the challenge-response device.
        serial: Option<u32>,
        /// The slot on the device to use.
        slot: ChallengeResponseSlot,
    },
}

/// The size of a LUKS2 segment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Luks2SegmentSize {
    /// A fixed size in bytes.
    U64(u64),
    /// A dynamic size that occupies all remaining space on the device.
    Dynamic,
}

impl Serialize for Luks2SegmentSize {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Luks2SegmentSize::U64(v) => serializer.serialize_str(&v.to_string()),
            Luks2SegmentSize::Dynamic => serializer.serialize_str("dynamic"),
        }
    }
}

impl<'de> Deserialize<'de> for Luks2SegmentSize {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        if s == "dynamic" {
            Ok(Luks2SegmentSize::Dynamic)
        } else {
            s.parse::<u64>()
                .map(Luks2SegmentSize::U64)
                .map_err(serde::de::Error::custom)
        }
    }
}

/// A LUKS2 segment, representing a range of data on the device.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Luks2Segment {
    /// A cryptographic segment.
    Crypt {
        /// The offset of the segment in bytes.
        offset: Luks2U64,
        /// The IV tweak for the segment.
        iv_tweak: Luks2U64,
        /// The size of the segment.
        size: Luks2SegmentSize,
        /// The encryption algorithm used for this segment.
        encryption: String,
        /// The sector size in bytes.
        sector_size: u32,
    },
}

/// A LUKS2 digest, used to verify the volume key.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Luks2Digest {
    /// A PBKDF2-based digest.
    Pbkdf2 {
        /// The IDs of the keyslots associated with this digest.
        keyslots: Vec<KeySlotId>,
        /// The IDs of the segments associated with this digest.
        segments: Vec<String>,
        /// The hash algorithm used.
        hash: Luks2HashAlg,
        /// The number of iterations.
        iterations: u32,
        /// The base64-encoded salt.
        salt: String,
        /// The base64-encoded expected digest.
        digest: String,
    },
}

/// Global configuration for a LUKS2 device.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Luks2Config {
    /// The size of the JSON area in bytes.
    pub json_size: Luks2U64,
    /// The size of the keyslots area in bytes.
    pub keyslots_size: Luks2U64,
    /// Any global flags set on the device.
    pub flags: Option<Vec<String>>,
}

/// The complete LUKS2 metadata, typically stored in the JSON area of the header.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Luks2Metadata {
    /// A map of keyslot IDs to their settings.
    #[serde(deserialize_with = "crate::keyslot::deserialize_and_validate_keyslots")]
    pub keyslots: HashMap<KeySlotId, Luks2Keyslot>,
    /// A map of token IDs to their settings.
    pub tokens: HashMap<String, Luks2Token>,
    /// A map of segment IDs to their settings.
    pub segments: HashMap<String, Luks2Segment>,
    /// A map of digest IDs to their settings.
    pub digests: HashMap<String, Luks2Digest>,
    /// Global device configuration.
    pub config: Luks2Config,
}

/// A LUKS device UUID.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LuksDeviceUuid(String);

impl LuksDeviceUuid {
    /// Returns the UUID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for LuksDeviceUuid {
    type Err = LuksError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim_matches('\0');
        if s.is_empty() {
            return Err(LuksError::InvalidHeader("UUID is empty".to_string()));
        }
        if s.len() >= LUKS2_UUID_SIZE {
            return Err(LuksError::InvalidHeader(format!(
                "UUID too long: {} (max {})",
                s.len(),
                LUKS2_UUID_SIZE - 1
            )));
        }
        if !s.chars().all(|c| c.is_ascii_hexdigit() || c == '-') {
            return Err(LuksError::InvalidHeader(format!(
                "UUID contains invalid characters: {}",
                s
            )));
        }
        Ok(LuksDeviceUuid(s.to_string()))
    }
}

impl fmt::Display for LuksDeviceUuid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl PartialEq<&str> for LuksDeviceUuid {
    fn eq(&self, other: &&str) -> bool {
        &self.0 == *other
    }
}

/// The primary binary header for LUKS2.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Luks2Header {
    /// The LUKS version (should be 2).
    pub version: u16,
    /// The total size of the header, including the binary part and the JSON area.
    pub hdr_size: u64,
    /// The sequence ID, incremented on each header update.
    pub seqid: u64,
    /// An optional label for the device.
    pub label: String,
    /// The hash algorithm used for calculating the header checksum.
    pub checksum_alg: Luks2HashAlg,
    /// The salt used for the header.
    #[serde(with = "serde_arrays")]
    pub salt: [u8; LUKS2_SALT_SIZE],
    /// The UUID of the device.
    pub uuid: LuksDeviceUuid,
    /// An optional subsystem label for the device.
    pub subsystem: String,
    /// The offset of this header in bytes from the start of the device.
    pub hdr_offset: u64,
    /// The header checksum.
    #[serde(with = "serde_arrays")]
    pub checksum: [u8; LUKS2_CHECKSUM_SIZE],
    /// The associated JSON metadata.
    pub metadata: Luks2Metadata,
}

mod serde_arrays {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S>(bytes: &[u8; 64], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        bytes.as_slice().serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 64], D::Error>
    where
        D: Deserializer<'de>,
    {
        let v: Vec<u8> = Vec::deserialize(deserializer)?;
        v.try_into()
            .map_err(|_| serde::de::Error::custom("expected array of length 64"))
    }
}

impl Luks2Header {
    /// Returns the number of configured keyslots.
    pub fn num_keyslots(&self) -> usize {
        self.metadata.keyslots.len()
    }

    /// Writes the header and its metadata to a writer.
    #[cfg(feature = "_write")]
    pub fn to_writer<W: Write + Seek>(&self, mut writer: W) -> Result<(), LuksError> {
        // Serialize JSON metadata
        let json_str = serde_json::to_string(&self.metadata)?;
        let json_bytes = json_str.as_bytes();
        let json_size = json_bytes.len() as u64;

        // Calculate binary header size (fixed at 4096)
        let binary_header_size = LUKS2_BINARY_HEADER_SIZE as u64;

        // Prepare binary header buffer
        let mut binary_header = vec![0u8; LUKS2_BINARY_HEADER_SIZE];
        let mut cursor = std::io::Cursor::new(&mut binary_header);

        // Write magic
        cursor.write_all(&LUKS_MAGIC)?;

        // Write version
        cursor.write_u16::<BigEndian>(self.version)?;

        // Write hdr_size (binary_header_size + JSON size)
        cursor.write_u64::<BigEndian>(binary_header_size + json_size)?;

        // Write seqid
        cursor.write_u64::<BigEndian>(self.seqid)?;

        // Write label (48 bytes)
        let mut label_buf = [0u8; LUKS2_LABEL_SIZE];
        let label_bytes = self.label.as_bytes();
        let label_len = std::cmp::min(label_bytes.len(), LUKS2_LABEL_SIZE);
        label_buf[..label_len].copy_from_slice(&label_bytes[..label_len]);
        cursor.write_all(&label_buf)?;

        // Write checksum algorithm (32 bytes)
        cursor.write_all(&self.checksum_alg.to_bytes())?;

        // Write salt (64 bytes)
        cursor.write_all(&self.salt)?;

        // Write uuid (40 bytes)
        let mut uuid_buf = [0u8; LUKS2_UUID_SIZE];
        let uuid_bytes = self.uuid.as_str().as_bytes();
        let uuid_len = std::cmp::min(uuid_bytes.len(), LUKS2_UUID_SIZE);
        uuid_buf[..uuid_len].copy_from_slice(&uuid_bytes[..uuid_len]);
        cursor.write_all(&uuid_buf)?;

        // Write subsystem (48 bytes)
        let mut subsystem_buf = [0u8; LUKS2_SUBSYSTEM_SIZE];
        let subsystem_bytes = self.subsystem.as_bytes();
        let subsystem_len = std::cmp::min(subsystem_bytes.len(), LUKS2_SUBSYSTEM_SIZE);
        subsystem_buf[..subsystem_len].copy_from_slice(&subsystem_bytes[..subsystem_len]);
        cursor.write_all(&subsystem_buf)?;

        // Write hdr_offset
        cursor.write_u64::<BigEndian>(self.hdr_offset)?;

        // Calculate checksum
        if self.checksum_alg == Luks2HashAlg::Sha256 {
            let mut hasher = Sha256::new();
            // The checksum is calculated with the checksum field zeroed out
            // binary_header already has it as zeroed out because it was initialized with vec![0u8; LUKS2_BINARY_HEADER_SIZE]
            hasher.update(&binary_header);
            hasher.update(json_bytes);
            let calculated = hasher.finalize();

            // Store checksum in the buffer
            binary_header[LUKS2_CHECKSUM_OFFSET..LUKS2_CHECKSUM_OFFSET + SHA256_DIGEST_SIZE]
                .copy_from_slice(calculated.as_slice());
        } else {
            return Err(LuksError::UnsupportedChecksumAlg(self.checksum_alg.to_string()));
        }

        // Write binary header to writer
        writer.seek(std::io::SeekFrom::Start(self.hdr_offset))?;
        writer.write_all(&binary_header)?;

        // Write JSON metadata
        writer.write_all(json_bytes)?;

        Ok(())
    }
}

/// A LUKS header, either version 1 or 2.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LuksHeader {
    /// A LUKS1 header. Currently only used as a placeholder.
    V1,
    /// A LUKS2 header.
    V2(Luks2Header),
}

impl LuksHeader {
    /// Returns the number of configured keyslots.
    pub fn num_keyslots(&self) -> usize {
        match self {
            LuksHeader::V1 => 8, // LUKS1 always has 8 keyslot entries in the header
            LuksHeader::V2(h) => h.num_keyslots(),
        }
    }

    /// Writes the header to a writer.
    #[cfg(feature = "_write")]
    pub fn to_writer<W: Write + Seek>(&self, writer: W) -> Result<(), LuksError> {
        match self {
            LuksHeader::V1 => Err(LuksError::UnsupportedVersion(1)),
            LuksHeader::V2(h) => h.to_writer(writer),
        }
    }

    /// Opens a LUKS device from a reader.
    ///
    /// This reads the header and all keyslot data areas from the reader.
    pub fn open<R: Read + Seek>(mut reader: R) -> Result<LuksDevice, LuksError> {
        let header = Self::from_reader(&mut reader)?;
        let mut keyslots = HashMap::new();

        match &header {
            LuksHeader::V1 => return Err(LuksError::UnsupportedVersion(1)),
            LuksHeader::V2(h) => {
                for (id, slot) in &h.metadata.keyslots {
                    let area = slot.area();
                    let mut data = vec![0u8; area.size() as usize];
                    reader.seek(SeekFrom::Start(area.offset()))?;
                    reader.read_exact(&mut data)?;
                    keyslots.insert(id.clone(), data);
                }
            }
        }

        Ok(LuksDevice {
            header,
            keyslots,
            unlocked_key: None,
        })
    }

    /// Reads a LUKS header from a reader.
    ///
    /// This only reads the header metadata, not the keyslot data areas.
    pub fn from_reader<R: Read + Seek>(mut reader: R) -> Result<Self, LuksError> {
        let mut magic = [0u8; LUKS_MAGIC_SIZE];
        reader.read_exact(&mut magic)?;

        if magic != LUKS_MAGIC {
            return Err(LuksError::InvalidMagic(magic));
        }

        let version = reader.read_u16::<BigEndian>()?;
        match version {
            1 => Ok(LuksHeader::V1),
            2 => {
                // Read the rest of the 4096-byte binary header
                let mut binary_header = vec![0u8; LUKS2_BINARY_HEADER_SIZE];
                binary_header[0..LUKS_MAGIC_SIZE].copy_from_slice(&magic);
                binary_header[LUKS_MAGIC_SIZE..LUKS_MAGIC_SIZE + LUKS_VERSION_SIZE]
                    .copy_from_slice(&version.to_be_bytes());

                reader.read_exact(&mut binary_header[LUKS_MAGIC_SIZE + LUKS_VERSION_SIZE..])?;

                let mut cursor = std::io::Cursor::new(&binary_header[LUKS_MAGIC_SIZE + LUKS_VERSION_SIZE..]);

                let hdr_size = cursor.read_u64::<BigEndian>()?;
                let seqid = cursor.read_u64::<BigEndian>()?;

                let mut label_buf = [0u8; LUKS2_LABEL_SIZE];
                cursor.read_exact(&mut label_buf)?;
                let label = String::from_utf8_lossy(&label_buf).trim_matches('\0').to_string();

                let mut checksum_alg_buf = [0u8; LUKS2_CHECKSUM_ALG_ID_LEN];
                cursor.read_exact(&mut checksum_alg_buf)?;
                let checksum_alg = Luks2HashAlg::from_str(&String::from_utf8_lossy(&checksum_alg_buf))?;

                let mut salt = [0u8; LUKS2_SALT_SIZE];
                cursor.read_exact(&mut salt)?;

                let mut uuid_buf = [0u8; LUKS2_UUID_SIZE];
                cursor.read_exact(&mut uuid_buf)?;
                let uuid = LuksDeviceUuid::from_str(&String::from_utf8_lossy(&uuid_buf))?;

                let mut subsystem_buf = [0u8; LUKS2_SUBSYSTEM_SIZE];
                cursor.read_exact(&mut subsystem_buf)?;
                let subsystem = String::from_utf8_lossy(&subsystem_buf)
                    .trim_matches('\0')
                    .to_string();

                // TODO must match the physical header offset on the device (in bytes). If it does
                // not match, the header is misplaced and must not be used. It is a prevention to
                // partition resize or manipulation with the device start offset.
                let hdr_offset = cursor.read_u64::<BigEndian>()?;

                let mut checksum = [0u8; LUKS2_CHECKSUM_SIZE];
                checksum.copy_from_slice(
                    &binary_header[LUKS2_CHECKSUM_OFFSET..LUKS2_CHECKSUM_OFFSET + LUKS2_CHECKSUM_SIZE],
                );

                // Read JSON area
                if hdr_size < LUKS2_BINARY_HEADER_SIZE as u64 {
                    return Err(LuksError::InvalidHeader(format!(
                        "Header size {} is too small",
                        hdr_size
                    )));
                }
                let json_size = hdr_size - LUKS2_BINARY_HEADER_SIZE as u64;
                let mut json_buf = vec![0u8; json_size as usize];
                reader.read_exact(&mut json_buf)?;

                // Verify checksum
                if checksum_alg == Luks2HashAlg::Sha256 {
                    let mut hasher = Sha256::new();

                    // The checksum is calculated with the checksum field itself zeroed out
                    let mut csum_buf = binary_header.clone();
                    for i in 0..LUKS2_CHECKSUM_SIZE {
                        csum_buf[LUKS2_CHECKSUM_OFFSET + i] = 0;
                    }
                    hasher.update(&csum_buf);
                    hasher.update(&json_buf);

                    let calculated = hasher.finalize();
                    // SHA256 is 32 bytes, but the checksum field is 64 bytes (padded with zeros)
                    if calculated.as_slice() != &checksum[0..SHA256_DIGEST_SIZE] {
                        return Err(LuksError::InvalidChecksum {
                            expected: to_hex(&checksum[0..SHA256_DIGEST_SIZE]),
                            actual: to_hex(calculated.as_slice()),
                        });
                    }
                } else {
                    return Err(LuksError::UnsupportedChecksumAlg(checksum_alg.to_string()));
                }

                // Parse JSON
                let json_str = String::from_utf8_lossy(&json_buf).trim_matches('\0').to_string();
                let metadata: Luks2Metadata = serde_json::from_str(&json_str)?;

                Ok(LuksHeader::V2(Luks2Header {
                    version,
                    hdr_size,
                    seqid,
                    label,
                    checksum_alg,
                    salt,
                    uuid,
                    subsystem,
                    hdr_offset,
                    checksum,
                    metadata,
                }))
            }
            _ => Err(LuksError::UnsupportedVersion(version)),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "_write")]
    use byteorder::BigEndian;
    #[cfg(feature = "_write")]
    use byteorder::WriteBytesExt;
    #[cfg(feature = "_write")]
    use std::io::{Cursor, Write};

    #[test]
    #[cfg(feature = "_write")]
    fn test_detect_luks2_with_checksum() {
        let mut binary_header = vec![0u8; LUKS2_BINARY_HEADER_SIZE];
        let json_data = format!(
            r#"{{
            "keyslots": {{}},
            "tokens": {{}},
            "segments": {{}},
            "digests": {{}},
            "config": {{
                "json_size": "{}",
                "keyslots_size": "{}"
            }}
        }}"#,
            LUKS2_DEFAULT_JSON_SIZE, LUKS2_DEFAULT_KEYSLOTS_SIZE
        );
        let hdr_size = LUKS2_BINARY_HEADER_SIZE as u64 + json_data.len() as u64;

        {
            let mut cursor = Cursor::new(&mut binary_header);
            cursor.write_all(&LUKS_MAGIC).unwrap();
            cursor.write_u16::<BigEndian>(2).unwrap();
            cursor.write_u64::<BigEndian>(hdr_size).unwrap();
            cursor.write_u64::<BigEndian>(1).unwrap(); // seqid

            let mut label = [0u8; LUKS2_LABEL_SIZE];
            label[..4].copy_from_slice(b"test");
            cursor.write_all(&label).unwrap();

            cursor.write_all(&Luks2HashAlg::Sha256.to_bytes()).unwrap();

            cursor.write_all(&[0u8; LUKS2_SALT_SIZE]).unwrap();

            let mut uuid = [0u8; LUKS2_UUID_SIZE];
            uuid[..4].copy_from_slice(b"abcd");
            cursor.write_all(&uuid).unwrap();

            let subsystem = [0u8; LUKS2_SUBSYSTEM_SIZE];
            cursor.write_all(&subsystem).unwrap();

            cursor.write_u64::<BigEndian>(0).unwrap(); // hdr_offset
        }

        // Calculate checksum (with csum field as zeros, which it already is in our buffer)
        let mut hasher = Sha256::new();
        hasher.update(&binary_header);
        hasher.update(json_data.as_bytes());
        let result = hasher.finalize();

        // Put checksum into binary header
        binary_header[LUKS2_CHECKSUM_OFFSET..LUKS2_CHECKSUM_OFFSET + SHA256_DIGEST_SIZE]
            .copy_from_slice(&result);

        let mut buf = binary_header;
        buf.extend_from_slice(json_data.as_bytes());

        let cursor = Cursor::new(buf);
        let header = LuksHeader::from_reader(cursor).unwrap();

        if let LuksHeader::V2(h) = header {
            assert_eq!(h.version, 2);
            assert_eq!(h.label, "test");
            assert_eq!(h.uuid, "abcd");
        } else {
            panic!("Expected LUKS2 header");
        }
    }

    #[test]
    #[cfg(feature = "_write")]
    fn test_device_roundtrip() {
        use aes::cipher::KeyInit;
        use base64::Engine;
        use rand::RngExt;
        use xts_mode::{Xts128, get_tweak_default};
        let mut rng = rand::rng();

        // 1. Setup metadata
        let mut salt = [0u8; LUKS2_SALT_SIZE];
        rng.fill(&mut salt);

        let volume_key_size = AES128_KEY_SIZE * 2;
        let volume_key = vec![0x42u8; volume_key_size];
        let passphrase = "correct horse battery staple";
        let unlock_key = UnlockKey::from(passphrase);

        // Keyslot 0
        let mut keyslot_salt = [0u8; 32];
        rng.fill(&mut keyslot_salt);
        let keyslot_salt_b64 = base64::engine::general_purpose::STANDARD.encode(keyslot_salt);

        let kdf = Luks2Kdf::Pbkdf2 {
            hash: Luks2HashAlg::Sha256,
            iterations: 1000,
            salt: keyslot_salt_b64,
        };

        let keyslot_key = kdf.derive_key(&unlock_key, &salt, volume_key_size).unwrap();

        // AF split the volume key
        let mut random_stripes = vec![0u8; volume_key_size * (LUKS1_AF_STRIPES - 1) as usize];
        rng.fill(&mut random_stripes[..]);
        let encrypted_keyslot_data = crate::af::split(
            &volume_key,
            &Luks2HashAlg::Sha256,
            LUKS1_AF_STRIPES,
            volume_key_size,
            random_stripes,
        )
        .unwrap();

        // Encrypt the AF stripes with the keyslot key
        let mut encrypted_data = encrypted_keyslot_data.clone();
        let cipher_1 = aes::Aes128::new_from_slice(&keyslot_key[0..AES128_KEY_SIZE]).unwrap();
        let cipher_2 = aes::Aes128::new_from_slice(&keyslot_key[AES128_KEY_SIZE..AES128_KEY_SIZE * 2]).unwrap();
        let xts = Xts128::new(cipher_1, cipher_2);
        for (i, chunk) in encrypted_data.chunks_mut(SECTOR_SIZE).enumerate() {
            xts.encrypt_area(chunk, SECTOR_SIZE, (i as u64).into(), |t| get_tweak_default(t));
        }

        let keyslot = Luks2Keyslot::Luks2 {
            key_size: Luks2KeySize::Size32,
            priority: Some(Luks2KeyslotPriority::Normal),
            af: Luks2Af {
                af_type: Luks2AfType::Luks1,
                stripes: LUKS1_AF_STRIPES,
                hash: Luks2HashAlg::Sha256,
            },
            area: Luks2Area::Raw {
                encryption: Luks2AreaEncryption::AesXtsPlain64,
                key_size: Luks2KeySize::Size32,
                offset: Luks2U64(32768),
                size: Luks2U64(encrypted_data.len() as u64),
            },
            kdf,
        };

        // Digest
        let mut digest_salt = [0u8; 32];
        rng.fill(&mut digest_salt);
        let digest_salt_b64 = base64::engine::general_purpose::STANDARD.encode(digest_salt);

        let mut expected_digest = vec![0u8; 32];
        pbkdf2::pbkdf2::<hmac::Hmac<Sha256>>(&volume_key, &digest_salt, 1000, &mut expected_digest).unwrap();
        let expected_digest_b64 = base64::engine::general_purpose::STANDARD.encode(expected_digest);

        let digest = Luks2Digest::Pbkdf2 {
            keyslots: vec![KeySlotId::new("0")],
            segments: vec!["0".to_string()],
            hash: Luks2HashAlg::Sha256,
            iterations: 1000,
            salt: digest_salt_b64,
            digest: expected_digest_b64,
        };

        let segment = Luks2Segment::Crypt {
            offset: Luks2U64(16777216), // 16MB offset
            iv_tweak: Luks2U64(0),
            size: Luks2SegmentSize::Dynamic,
            encryption: "aes-xts-plain64".to_string(),
            sector_size: 512,
        };

        let mut keyslots = HashMap::new();
        keyslots.insert(KeySlotId::new("0"), keyslot);

        let mut digests = HashMap::new();
        digests.insert("0".to_string(), digest);

        let mut segments = HashMap::new();
        segments.insert("0".to_string(), segment);

        let header = Luks2Header {
            version: 2,
            hdr_size: 0, // Will be recalculated
            seqid: 1,
            label: "test".to_string(),
            checksum_alg: Luks2HashAlg::Sha256,
            salt,
            uuid: LuksDeviceUuid::from_str("00000000-0000-0000-0000-000000000000").unwrap(),
            subsystem: "test".to_string(),
            hdr_offset: 0,
            checksum: [0u8; LUKS2_CHECKSUM_SIZE],
            metadata: Luks2Metadata {
                keyslots,
                tokens: HashMap::new(),
                segments,
                digests,
                config: Luks2Config {
                    json_size: Luks2U64(LUKS2_DEFAULT_JSON_SIZE),
                    keyslots_size: Luks2U64(LUKS2_DEFAULT_KEYSLOTS_SIZE),
                    flags: None,
                },
            },
        };

        let mut captured_keyslots = HashMap::new();
        captured_keyslots.insert(KeySlotId::new("0"), encrypted_data);

        let device = LuksDevice {
            header: LuksHeader::V2(header),
            keyslots: captured_keyslots,
            unlocked_key: None,
        };

        // 2. Write to buffer
        let mut buf = Cursor::new(Vec::new());
        device.to_writer(&mut buf).expect("to_writer failed");

        // 3. Read back and verify
        buf.set_position(0);
        let mut read_device = LuksHeader::open(&mut buf).expect("open failed");

        let key = UnlockKey::from(passphrase);
        read_device
            .unlock(&KeySlotId::new("0"), &key)
            .expect("unlock failed");
        assert!(read_device.verify(&KeySlotId::new("0")).expect("verify failed"));
    }

    #[test]
    #[cfg(feature = "_write")]
    fn test_change_unlock_key() {
        use aes::cipher::KeyInit;
        use base64::Engine;
        use rand::RngExt;
        use xts_mode::{Xts128, get_tweak_default};
        let mut rng = rand::rng();

        const TEST_ITERATIONS: u32 = 1000;

        // 1. Setup metadata
        let mut salt = [0u8; LUKS2_SALT_SIZE];
        rng.fill(&mut salt);

        let volume_key_size = AES128_KEY_SIZE * 2;
        let volume_key = vec![0x42u8; volume_key_size];
        let old_passphrase = "old passphrase";
        let new_passphrase = "new passphrase";
        let old_key = UnlockKey::from(old_passphrase);
        let new_key = UnlockKey::from(new_passphrase);

        // Keyslot 0
        let mut keyslot_salt = [0u8; KDF_SALT_SIZE];
        rng.fill(&mut keyslot_salt);
        let keyslot_salt_b64 = base64::engine::general_purpose::STANDARD.encode(keyslot_salt);

        let kdf = Luks2Kdf::Pbkdf2 {
            hash: Luks2HashAlg::Sha256,
            iterations: TEST_ITERATIONS,
            salt: keyslot_salt_b64,
        };

        let keyslot_key = kdf.derive_key(&old_key, &salt, volume_key_size).unwrap();

        // AF split the volume key
        let mut random_stripes = vec![0u8; volume_key_size * (LUKS1_AF_STRIPES - 1) as usize];
        rng.fill(&mut random_stripes[..]);
        let encrypted_keyslot_data = crate::af::split(
            &volume_key,
            &Luks2HashAlg::Sha256,
            LUKS1_AF_STRIPES,
            volume_key_size,
            random_stripes,
        )
        .unwrap();

        // Encrypt the AF stripes with the keyslot key
        let mut encrypted_data = encrypted_keyslot_data.clone();
        let cipher_1 = aes::Aes128::new_from_slice(&keyslot_key[0..AES128_KEY_SIZE]).unwrap();
        let cipher_2 = aes::Aes128::new_from_slice(&keyslot_key[AES128_KEY_SIZE..AES128_KEY_SIZE * 2]).unwrap();
        let xts = Xts128::new(cipher_1, cipher_2);
        for (i, chunk) in encrypted_data.chunks_mut(SECTOR_SIZE).enumerate() {
            xts.encrypt_area(chunk, SECTOR_SIZE, (i as u64).into(), |t| get_tweak_default(t));
        }

        let keyslot = Luks2Keyslot::Luks2 {
            key_size: Luks2KeySize::Size32,
            priority: Some(Luks2KeyslotPriority::Normal),
            af: Luks2Af {
                af_type: Luks2AfType::Luks1,
                stripes: LUKS1_AF_STRIPES,
                hash: Luks2HashAlg::Sha256,
            },
            area: Luks2Area::Raw {
                encryption: Luks2AreaEncryption::AesXtsPlain64,
                key_size: Luks2KeySize::Size32,
                offset: Luks2U64(32768),
                size: Luks2U64(encrypted_data.len() as u64),
            },
            kdf,
        };

        // Digest
        let mut digest_salt = [0u8; KDF_SALT_SIZE];
        rng.fill(&mut digest_salt);
        let digest_salt_b64 = base64::engine::general_purpose::STANDARD.encode(digest_salt);

        let mut expected_digest = vec![0u8; SHA256_DIGEST_SIZE];
        pbkdf2::pbkdf2::<hmac::Hmac<Sha256>>(&volume_key, &digest_salt, TEST_ITERATIONS, &mut expected_digest)
            .unwrap();
        let expected_digest_b64 = base64::engine::general_purpose::STANDARD.encode(expected_digest);

        let ks0 = KeySlotId::new("0");
        let digest = Luks2Digest::Pbkdf2 {
            keyslots: vec![ks0.clone()],
            segments: vec!["0".to_string()],
            hash: Luks2HashAlg::Sha256,
            iterations: TEST_ITERATIONS,
            salt: digest_salt_b64,
            digest: expected_digest_b64,
        };

        let mut keyslots = HashMap::new();
        keyslots.insert(ks0.clone(), keyslot);

        let mut digests = HashMap::new();
        digests.insert("0".to_string(), digest);

        let header = Luks2Header {
            version: 2,
            hdr_size: 0,
            seqid: 1,
            label: "test".to_string(),
            checksum_alg: Luks2HashAlg::Sha256,
            salt,
            uuid: LuksDeviceUuid::from_str("00000000-0000-0000-0000-000000000000").unwrap(),
            subsystem: "test".to_string(),
            hdr_offset: 0,
            checksum: [0u8; LUKS2_CHECKSUM_SIZE],
            metadata: Luks2Metadata {
                keyslots,
                tokens: HashMap::new(),
                segments: HashMap::new(),
                digests,
                config: Luks2Config {
                    json_size: Luks2U64(LUKS2_DEFAULT_JSON_SIZE),
                    keyslots_size: Luks2U64(LUKS2_DEFAULT_KEYSLOTS_SIZE),
                    flags: None,
                },
            },
        };

        let mut captured_keyslots = HashMap::new();
        captured_keyslots.insert(ks0.clone(), encrypted_data);

        let mut device = LuksDevice {
            header: LuksHeader::V2(header),
            keyslots: captured_keyslots,
            unlocked_key: None,
        };

        // 2. Change unlock key
        device
            .change_unlock_key(&ks0, &old_key, &new_key)
            .expect("change_unlock_key failed");

        // 3. Verify
        device.unlock(&ks0, &new_key).expect("unlock failed");
        assert!(device.verify(&ks0).expect("verify with new passphrase failed"));

        device
            .unlock(&ks0, &old_key)
            .expect_err("unlock with old passphrase should fail");

        // 4. Verify volume key is still the same
        let derived_volume_key = device
            .get_volume_key(&ks0, &new_key)
            .expect("get_volume_key failed");
        assert_eq!(volume_key, derived_volume_key.expose_bytes());
    }

    #[test]
    #[cfg(feature = "_write")]
    fn test_unlock() {
        use aes::cipher::KeyInit;
        use base64::Engine;
        use rand::RngExt;
        use xts_mode::{Xts128, get_tweak_default};
        let mut rng = rand::rng();

        // 1. Setup metadata
        let mut salt = [0u8; LUKS2_SALT_SIZE];
        rng.fill(&mut salt);

        let volume_key_size = AES128_KEY_SIZE * 2;
        let volume_key = vec![0x42u8; volume_key_size];
        let passphrase = "correct horse battery staple";
        let key = UnlockKey::from(passphrase);

        // Keyslot 0
        let mut keyslot_salt = [0u8; KDF_SALT_SIZE];
        rng.fill(&mut keyslot_salt);
        let keyslot_salt_b64 = base64::engine::general_purpose::STANDARD.encode(keyslot_salt);

        let kdf = Luks2Kdf::Pbkdf2 {
            hash: Luks2HashAlg::Sha256,
            iterations: 1000,
            salt: keyslot_salt_b64,
        };

        let keyslot_key = kdf.derive_key(&key, &salt, volume_key_size).unwrap();

        // AF split the volume key
        let mut random_stripes = vec![0u8; volume_key_size * (LUKS1_AF_STRIPES - 1) as usize];
        rng.fill(&mut random_stripes[..]);
        let encrypted_keyslot_data = crate::af::split(
            &volume_key,
            &Luks2HashAlg::Sha256,
            LUKS1_AF_STRIPES,
            volume_key_size,
            random_stripes,
        )
        .unwrap();

        // Encrypt the AF stripes with the keyslot key
        let mut encrypted_data = encrypted_keyslot_data.clone();
        let cipher_1 = aes::Aes128::new_from_slice(&keyslot_key[0..AES128_KEY_SIZE]).unwrap();
        let cipher_2 = aes::Aes128::new_from_slice(&keyslot_key[AES128_KEY_SIZE..AES128_KEY_SIZE * 2]).unwrap();
        let xts = Xts128::new(cipher_1, cipher_2);
        for (i, chunk) in encrypted_data.chunks_mut(SECTOR_SIZE).enumerate() {
            xts.encrypt_area(chunk, SECTOR_SIZE, (i as u64).into(), |t| get_tweak_default(t));
        }

        let keyslot = Luks2Keyslot::Luks2 {
            key_size: Luks2KeySize::Size32,
            priority: Some(Luks2KeyslotPriority::Normal),
            af: Luks2Af {
                af_type: Luks2AfType::Luks1,
                stripes: LUKS1_AF_STRIPES,
                hash: Luks2HashAlg::Sha256,
            },
            area: Luks2Area::Raw {
                encryption: Luks2AreaEncryption::AesXtsPlain64,
                key_size: Luks2KeySize::Size32,
                offset: Luks2U64(32768),
                size: Luks2U64(encrypted_data.len() as u64),
            },
            kdf,
        };

        // Digest
        let mut digest_salt = [0u8; KDF_SALT_SIZE];
        rng.fill(&mut digest_salt);
        let digest_salt_b64 = base64::engine::general_purpose::STANDARD.encode(digest_salt);

        let mut expected_digest = vec![0u8; SHA256_DIGEST_SIZE];
        pbkdf2::pbkdf2::<hmac::Hmac<Sha256>>(&volume_key, &digest_salt, 1000, &mut expected_digest).unwrap();
        let expected_digest_b64 = base64::engine::general_purpose::STANDARD.encode(expected_digest);

        let ks0 = KeySlotId::new("0");
        let digest = Luks2Digest::Pbkdf2 {
            keyslots: vec![ks0.clone()],
            segments: vec!["0".to_string()],
            hash: Luks2HashAlg::Sha256,
            iterations: 1000,
            salt: digest_salt_b64,
            digest: expected_digest_b64,
        };

        let mut keyslots = HashMap::new();
        keyslots.insert(ks0.clone(), keyslot);

        let mut digests = HashMap::new();
        digests.insert("0".to_string(), digest);

        let header = Luks2Header {
            version: 2,
            hdr_size: 0,
            seqid: 1,
            label: "test".to_string(),
            checksum_alg: Luks2HashAlg::Sha256,
            salt,
            uuid: LuksDeviceUuid::from_str("00000000-0000-0000-0000-000000000000").unwrap(),
            subsystem: "test".to_string(),
            hdr_offset: 0,
            checksum: [0u8; LUKS2_CHECKSUM_SIZE],
            metadata: Luks2Metadata {
                keyslots,
                tokens: HashMap::new(),
                segments: HashMap::new(),
                digests,
                config: Luks2Config {
                    json_size: Luks2U64(LUKS2_DEFAULT_JSON_SIZE),
                    keyslots_size: Luks2U64(LUKS2_DEFAULT_KEYSLOTS_SIZE),
                    flags: None,
                },
            },
        };

        let mut captured_keyslots = HashMap::new();
        captured_keyslots.insert(ks0.clone(), encrypted_data);

        let mut device = LuksDevice {
            header: LuksHeader::V2(header),
            keyslots: captured_keyslots,
            unlocked_key: None,
        };

        // 2. Unlock
        device.unlock(&ks0, &key).expect("unlock failed");

        // 3. Verify
        assert!(device.unlocked_key.is_some());
        assert_eq!(volume_key, device.unlocked_key.as_ref().unwrap().expose_bytes());
    }

    #[test]
    #[cfg(feature = "_write")]
    fn test_header_roundtrip() {
        let mut salt = [0u8; LUKS2_SALT_SIZE];
        salt[0..4].copy_from_slice(b"salt");
        let header = Luks2Header {
            version: 2,
            hdr_size: 16384, // Will be recalculated in to_writer anyway
            seqid: 1,
            label: "test".to_string(),
            checksum_alg: Luks2HashAlg::Sha256,
            salt,
            uuid: LuksDeviceUuid::from_str("00000000-0000-0000-0000-000000000000").unwrap(),
            subsystem: "test".to_string(),
            hdr_offset: 0,
            checksum: [0u8; LUKS2_CHECKSUM_SIZE], // Will be calculated in to_writer
            metadata: Luks2Metadata {
                keyslots: HashMap::new(),
                tokens: HashMap::new(),
                segments: HashMap::new(),
                digests: HashMap::new(),
                config: Luks2Config {
                    json_size: Luks2U64(LUKS2_DEFAULT_JSON_SIZE),
                    keyslots_size: Luks2U64(LUKS2_DEFAULT_KEYSLOTS_SIZE),
                    flags: None,
                },
            },
        };

        let mut buf = Cursor::new(Vec::new());
        header.to_writer(&mut buf).expect("to_writer failed");

        buf.set_position(0);
        let read_header = LuksHeader::from_reader(&mut buf).expect("from_reader failed");

        if let LuksHeader::V2(h) = read_header {
            assert_eq!(h.version, header.version);
            assert_eq!(h.label, header.label);
            assert_eq!(h.uuid, header.uuid);
            assert_eq!(h.subsystem, header.subsystem);
            assert_eq!(h.checksum_alg, header.checksum_alg);
            assert_eq!(h.salt, header.salt);
            assert_eq!(h.hdr_offset, header.hdr_offset);
            // hdr_size is recalculated, so check if it's correct
            assert!(h.hdr_size >= LUKS2_BINARY_HEADER_SIZE as u64);
        } else {
            panic!("Expected LUKS2 header");
        }
    }

    #[test]
    #[cfg(feature = "_write")]
    fn test_num_keyslots() {
        let mut binary_header = vec![0u8; LUKS2_BINARY_HEADER_SIZE];
        let json_data = format!(
            r#"{{
            "keyslots": {{
                "0": {{
                    "type": "luks2",
                    "key_size": 64,
                    "priority": 1,
                    "af": {{ "type": "luks1", "stripes": 4000, "hash": "{}" }},
                    "area": {{ "type": "raw", "encryption": "aes-xts-plain64", "key_size": 64, "offset": "32768", "size": "131072" }},
                    "kdf": {{ "type": "argon2i", "time": 4, "memory": 235980, "cpus": 2, "salt": "z6vz4xK7cjan92rDA5JF8O6Jk2HouV0O8DMB6GlztVk=" }}
                }},
                "1": {{
                    "type": "luks2",
                    "key_size": 64,
                    "priority": 1,
                    "af": {{ "type": "luks1", "stripes": 4000, "hash": "{}" }},
                    "area": {{ "type": "raw", "encryption": "aes-xts-plain64", "key_size": 64, "offset": "163840", "size": "131072" }},
                    "kdf": {{ "type": "pbkdf2", "hash": "sha256", "iterations": 1774240, "salt": "vWcwY3rx2fKpXW2Q6oSCNf8j5bvdJyEzB6BNXECGDsI=" }}
                }}
            }},
            "tokens": {{}},
            "segments": {{}},
            "digests": {{}},
            "config": {{
                "json_size": "{}",
                "keyslots_size": "{}"
            }}
        }}"#,
            HASH_SHA256, HASH_SHA256, LUKS2_DEFAULT_JSON_SIZE, LUKS2_DEFAULT_KEYSLOTS_SIZE
        );
        let hdr_size = LUKS2_BINARY_HEADER_SIZE as u64 + json_data.len() as u64;

        {
            let mut cursor = Cursor::new(&mut binary_header);
            cursor.write_all(&LUKS_MAGIC).unwrap();
            cursor.write_u16::<BigEndian>(2).unwrap();
            cursor.write_u64::<BigEndian>(hdr_size).unwrap();
            cursor.write_u64::<BigEndian>(1).unwrap();

            let label = [0u8; LUKS2_LABEL_SIZE];
            cursor.write_all(&label).unwrap();

            cursor.write_all(&Luks2HashAlg::Sha256.to_bytes()).unwrap();

            cursor.write_all(&[0u8; LUKS2_SALT_SIZE]).unwrap();

            let mut uuid = [0u8; LUKS2_UUID_SIZE];
            uuid[..4].copy_from_slice(b"abcd");
            cursor.write_all(&uuid).unwrap();

            let subsystem = [0u8; LUKS2_SUBSYSTEM_SIZE];
            cursor.write_all(&subsystem).unwrap();

            cursor.write_u64::<BigEndian>(0).unwrap();
        }

        let mut hasher = Sha256::new();
        hasher.update(&binary_header);
        hasher.update(json_data.as_bytes());
        let result = hasher.finalize();

        binary_header[LUKS2_CHECKSUM_OFFSET..LUKS2_CHECKSUM_OFFSET + SHA256_DIGEST_SIZE]
            .copy_from_slice(&result);

        let mut buf = binary_header;
        buf.extend_from_slice(json_data.as_bytes());

        let cursor = Cursor::new(buf);
        let header = LuksHeader::from_reader(cursor).unwrap();

        assert_eq!(header.num_keyslots(), 2);
    }

    #[test]
    fn test_luks_uuid_parsing() {
        assert!(LuksDeviceUuid::from_str("550e8400-e29b-41d4-a716-446655440000").is_ok());
        assert!(LuksDeviceUuid::from_str("abcd").is_ok());
        assert!(LuksDeviceUuid::from_str("").is_err());
        assert!(LuksDeviceUuid::from_str("invalid-char!").is_err());
        assert!(LuksDeviceUuid::from_str(&"a".repeat(40)).is_err());
    }

    #[test]
    fn test_parse_full_example_json() {
        let json_data = r#"{
            "keyslots": {
                "0": {
                    "type": "luks2",
                    "key_size": 32,
                    "af": {
                        "type": "luks1",
                        "stripes": 4000,
                        "hash": "sha256"
                    },
                    "area": {
                        "type": "raw",
                        "encryption": "aes-xts-plain64",
                        "key_size": 32,
                        "offset": "32768",
                        "size": "131072"
                    },
                    "kdf": {
                        "type": "argon2i",
                        "time": 4,
                        "memory": 235980,
                        "cpus": 2,
                        "salt": "z6vz4xK7cjan92rDA5JF8O6Jk2HouV0O8DMB6GlztVk="
                    }
                },
                "1": {
                    "type": "luks2",
                    "key_size": 32,
                    "af": {
                        "type": "luks1",
                        "stripes": 4000,
                        "hash": "sha256"
                    },
                    "area": {
                        "type": "raw",
                        "encryption": "aes-xts-plain64",
                        "key_size": 32,
                        "offset": "163840",
                        "size": "131072"
                    },
                    "kdf": {
                        "type": "pbkdf2",
                        "hash": "sha256",
                        "iterations": 1774240,
                        "salt": "vWcwY3rx2fKpXW2Q6oSCNf8j5bvdJyEzB6BNXECGDsI="
                    }
                }
            },
            "tokens": {
                "0": {
                    "type": "luks2-keyring",
                    "keyslots": [
                        "1"
                    ],
                    "key_description": "MyKeyringKeyID"
                }
            },
            "segments": {
                "0": {
                    "type": "crypt",
                    "offset": "4194304",
                    "iv_tweak": "0",
                    "size": "dynamic",
                    "encryption": "aes-xts-plain64",
                    "sector_size": 512
                }
            },
            "digests": {
                "0": {
                    "type": "pbkdf2",
                    "keyslots": [
                        "0",
                        "1"
                    ],
                    "segments": [
                        "0"
                    ],
                    "hash": "sha256",
                    "iterations": 110890,
                    "salt": "G8gqtKhS96IbogHyJLO+t9kmjLkx+DM3HHJqQtgc2Dk=",
                    "digest": "C9JWko5m+oYmjg6R0t/98cGGzLr/4UaG3hImSJMivfc="
                }
            },
            "config": {
                "json_size": "12288",
                "keyslots_size": "4161536",
                "flags": [
                    "allow-discards"
                ]
            }
        }"#;
        let metadata: Luks2Metadata = serde_json::from_str(json_data).unwrap();
        assert_eq!(metadata.keyslots.len(), 2);
        assert_eq!(metadata.tokens.len(), 1);
        assert_eq!(metadata.segments.len(), 1);
        assert_eq!(metadata.digests.len(), 1);
        assert_eq!(metadata.config.json_size, Luks2U64(12288));

        let ks0 = metadata.keyslots.get(&KeySlotId::new("0")).unwrap();
        let Luks2Keyslot::Luks2 { key_size, kdf, .. } = ks0 else {
            panic!("Expected Luks2 keyslot")
        };
        assert_eq!(*key_size, Luks2KeySize::Size32);
        assert!(matches!(kdf, Luks2Kdf::Argon2i { .. }));

        let ks1 = metadata.keyslots.get(&KeySlotId::new("1")).unwrap();
        let Luks2Keyslot::Luks2 { kdf, .. } = ks1 else {
            panic!("Expected Luks2 keyslot")
        };
        assert!(matches!(kdf, Luks2Kdf::Pbkdf2 { .. }));

        let token0 = metadata.tokens.get("0").unwrap();
        assert!(matches!(token0, Luks2Token::Keyring { .. }));

        let segment0 = metadata.segments.get("0").unwrap();
        let Luks2Segment::Crypt { size, .. } = segment0;
        assert_eq!(size, &Luks2SegmentSize::Dynamic);

        let digest0 = metadata.digests.get("0").unwrap();
        assert!(matches!(digest0, Luks2Digest::Pbkdf2 { .. }));
    }

    #[test]
    fn test_parse_luks_rs_keyring_token() {
        let json_data = r#"{
            "keyslots": {},
            "tokens": {
                "0": {
                    "type": "luks-rs-keyring",
                    "keyslots": ["0"],
                    "key_description": "MyLuksRsKey"
                }
            },
            "segments": {},
            "digests": {},
            "config": { "json_size": "12288", "keyslots_size": "4161536" }
        }"#;
        let metadata: Luks2Metadata = serde_json::from_str(json_data).unwrap();
        let token = metadata.tokens.get("0").unwrap();
        if let Luks2Token::LuksRsKeyring {
            keyslots,
            key_description,
        } = token
        {
            assert_eq!(keyslots, &vec![KeySlotId::new("0")]);
            assert_eq!(key_description, "MyLuksRsKey");
        } else {
            panic!("Expected LuksRsKeyring token");
        }
    }

    #[test]
    fn test_invalid_keyslot_area_type() {
        let json_data = r#"{
            "keyslots": {
                "0": {
                    "type": "luks2",
                    "key_size": 32,
                    "af": { "type": "luks1", "stripes": 4000, "hash": "sha256" },
                    "area": { "type": "none", "encryption": "aes-xts-plain64", "key_size": 32, "offset": "32768", "size": "131072" },
                    "kdf": { "type": "argon2i", "time": 4, "memory": 235980, "cpus": 2, "salt": "salt" }
                }
            },
            "tokens": {},
            "segments": {},
            "digests": {},
            "config": { "json_size": "12288", "keyslots_size": "4161536" }
        }"#;
        let result: Result<Luks2Metadata, _> = serde_json::from_str(json_data);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("LUKS2 keyslot must have area type 'raw'")
        );
    }

    #[test]
    fn test_parse_reencrypt_keyslot() {
        let json_data = r#"{
            "keyslots": {
                "0": {
                    "type": "reencrypt",
                    "mode": "reencrypt",
                    "direction": "forward",
                    "key_size": "1",
                    "priority": 1,
                    "af": { "type": "luks1", "stripes": 4000, "hash": "sha256" },
                    "area": { "type": "none", "encryption": "aes-xts-plain64", "key_size": 32, "offset": "32768", "size": "131072" },
                    "kdf": { "type": "argon2i", "time": 4, "memory": 235980, "cpus": 2, "salt": "salt" }
                }
            },
            "tokens": {},
            "segments": {},
            "digests": {},
            "config": { "json_size": "12288", "keyslots_size": "4161536" }
        }"#;
        let metadata: Luks2Metadata = serde_json::from_str(json_data).unwrap();
        let slot = metadata.keyslots.get(&KeySlotId::new("0")).unwrap();
        let Luks2Keyslot::Reencrypt {
            mode,
            direction,
            key_size,
            ..
        } = slot
        else {
            panic!("Expected Reencrypt keyslot")
        };
        assert_eq!(*mode, Luks2ReencryptMode::Reencrypt);
        assert_eq!(*direction, Luks2ReencryptDirection::Forward);
        assert_eq!(key_size, "1");
    }

    #[test]
    fn test_parse_reencrypt_area_types() {
        let json_data = r#"{
            "keyslots": {
                "checksum_slot": {
                    "type": "reencrypt",
                    "mode": "reencrypt",
                    "direction": "forward",
                    "key_size": "1",
                    "af": { "type": "luks1", "stripes": 4000, "hash": "sha256" },
                    "area": { "type": "checksum", "hash": "sha256", "sector_size": 512, "offset": "32768", "size": "131072" },
                    "kdf": { "type": "argon2i", "time": 4, "memory": 235980, "cpus": 2, "salt": "salt" }
                },
                "datashift_slot": {
                    "type": "reencrypt",
                    "mode": "reencrypt",
                    "direction": "forward",
                    "key_size": "1",
                    "af": { "type": "luks1", "stripes": 4000, "hash": "sha256" },
                    "area": { "type": "datashift", "shift_size": "4096", "offset": "32768", "size": "131072" },
                    "kdf": { "type": "argon2i", "time": 4, "memory": 235980, "cpus": 2, "salt": "salt" }
                },
                "datashift_checksum_slot": {
                    "type": "reencrypt",
                    "mode": "reencrypt",
                    "direction": "forward",
                    "key_size": "1",
                    "af": { "type": "luks1", "stripes": 4000, "hash": "sha256" },
                    "area": { "type": "datashift-checksum", "hash": "sha256", "sector_size": 512, "shift_size": "4096", "offset": "32768", "size": "131072" },
                    "kdf": { "type": "argon2i", "time": 4, "memory": 235980, "cpus": 2, "salt": "salt" }
                }
            },
            "tokens": {},
            "segments": {},
            "digests": {},
            "config": { "json_size": "12288", "keyslots_size": "4161536" }
        }"#;
        let metadata: Luks2Metadata = serde_json::from_str(json_data).unwrap();

        let checksum_slot = metadata.keyslots.get(&KeySlotId::new("checksum_slot")).unwrap();
        if let Luks2Keyslot::Reencrypt { area, .. } = checksum_slot {
            assert!(matches!(area, Luks2Area::Checksum { .. }));
        } else {
            panic!("Expected Reencrypt keyslot")
        }

        let datashift_slot = metadata.keyslots.get(&KeySlotId::new("datashift_slot")).unwrap();
        if let Luks2Keyslot::Reencrypt { area, .. } = datashift_slot {
            assert!(matches!(area, Luks2Area::Datashift { .. }));
        } else {
            panic!("Expected Reencrypt keyslot")
        }

        let datashift_checksum_slot = metadata
            .keyslots
            .get(&KeySlotId::new("datashift_checksum_slot"))
            .unwrap();
        if let Luks2Keyslot::Reencrypt { area, .. } = datashift_checksum_slot {
            assert!(matches!(area, Luks2Area::DatashiftChecksum { .. }));
        } else {
            panic!("Expected Reencrypt keyslot")
        }
    }

    #[test]
    fn test_parse_argon2id_kdf() {
        let json_data = r#"{
                    "keyslots": {
                        "0": {
                            "type": "luks2",
                            "key_size": 32,
                            "af": { "type": "luks1", "stripes": 4000, "hash": "sha256" },
                            "area": { "type": "raw", "encryption": "aes-xts-plain64", "key_size": 32, "offset": "32768", "size": "131072" },
                            "kdf": { "type": "argon2id", "time": 4, "memory": 235980, "cpus": 2, "salt": "salt" }
                        }
                    },
                    "tokens": {},
                    "segments": {},
                    "digests": {},
                    "config": { "json_size": "12288", "keyslots_size": "4161536" }
                }"#;
        let metadata: Luks2Metadata = serde_json::from_str(json_data).unwrap();
        let slot = metadata.keyslots.get(&KeySlotId::new("0")).unwrap();
        let Luks2Keyslot::Luks2 { kdf, .. } = slot else {
            panic!("Expected Luks2 keyslot")
        };
        assert!(matches!(
            kdf,
            Luks2Kdf::Argon2id {
                time: 4,
                memory: 235980,
                cpus: 2,
                ..
            }
        ));
    }

    #[test]
    fn test_is_luks_device() {
        let path = std::env::temp_dir().join("test_luks_magic");
        std::fs::write(&path, &LUKS_MAGIC).unwrap();
        assert!(is_luks_device(&path).unwrap());
        std::fs::remove_file(&path).unwrap();

        let path = std::env::temp_dir().join("test_not_luks_magic");
        std::fs::write(&path, b"NOTLUK").unwrap();
        assert!(!is_luks_device(&path).unwrap());
        std::fs::remove_file(&path).unwrap();

        let path = std::env::temp_dir().join("test_short_luks_magic");
        std::fs::write(&path, b"LUKS").unwrap();
        assert!(!is_luks_device(&path).unwrap());
        std::fs::remove_file(&path).unwrap();
    }

    #[test]
    #[cfg(feature = "_challenge_response")]
    fn test_challenge_response_e2e() {
        use crate::hash::SHA256_DIGEST_SIZE;
        use std::collections::HashMap;

        const TEST_KEY_SIZE: usize = 64;
        const TEST_AREA_SIZE: usize = 131072;
        const TEST_ITERATIONS: u32 = 1000;
        const TEST_VOL_KEY_SIZE: usize = 64;
        const TEST_CR_SECRET: &[u8] = &[0x01, 0x02, 0x03, 0x04];

        // 1. Setup a mock LuksDevice with a password-only keyslot
        let json_metadata = format!(
            r#"{{
            "keyslots": {{
                "0": {{
                    "type": "luks2",
                    "key_size": {key_size},
                    "af": {{ "type": "luks1", "stripes": 4000, "hash": "sha256" }},
                    "area": {{ "type": "raw", "encryption": "aes-xts-plain64", "key_size": {key_size}, "offset": "{area_offset}", "size": "{area_size}" }},
                    "kdf": {{ "type": "argon2id", "time": 1, "memory": 1024, "cpus": 1, "salt": "c2FsdA==" }}
                }}
            }},
            "tokens": {{}},
            "segments": {{}},
            "digests": {{
                "0": {{
                    "type": "pbkdf2",
                    "keyslots": ["0"],
                    "segments": [],
                    "hash": "sha256",
                    "iterations": {iterations},
                    "salt": "c2FsdA==",
                    "digest": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
                }}
            }},
            "config": {{ "json_size": "{json_size}", "keyslots_size": "{keyslots_size}" }}
        }}"#,
            key_size = TEST_KEY_SIZE,
            area_offset = LUKS2_BINARY_HEADER_SIZE * 8,
            area_size = TEST_AREA_SIZE,
            iterations = TEST_ITERATIONS,
            json_size = LUKS2_DEFAULT_JSON_SIZE,
            keyslots_size = LUKS2_DEFAULT_KEYSLOTS_SIZE
        );

        let metadata: Luks2Metadata = serde_json::from_str(&json_metadata).unwrap();
        let header = LuksHeader::V2(Luks2Header {
            version: 2,
            hdr_size: (LUKS2_BINARY_HEADER_SIZE * 4) as u64,
            seqid: 1,
            label: "test".to_string(),
            checksum_alg: Luks2HashAlg::Sha256,
            salt: [0u8; LUKS2_SALT_SIZE],
            uuid: LuksDeviceUuid::from_str("00000000-0000-0000-0000-000000000000").unwrap(),
            subsystem: "".to_string(),
            hdr_offset: 0,
            checksum: [0u8; LUKS2_CHECKSUM_SIZE],
            metadata,
        });

        // Initialize keyslot data with some dummy data (enough for AF-split area)
        let mut keyslots = HashMap::new();
        let slot0 = KeySlotId::from("0");
        keyslots.insert(slot0.clone(), vec![0u8; TEST_AREA_SIZE]);

        let mut device = LuksDevice {
            header,
            keyslots: keyslots.clone(),
            unlocked_key: None,
        };

        // We need a real volume key that would "decrypt" our dummy area to something verifiable
        // But since we are testing the KDF/CR flow, we can manually set the digest to match
        // what PBKDF2(volume_key) would produce.
        let volume_key_bytes = vec![0x42u8; TEST_VOL_KEY_SIZE];
        let volume_key = VolumeKey::new(volume_key_bytes.clone()).unwrap();

        // Update the digest to match our volume key so verify() works
        if let LuksHeader::V2(ref mut h) = device.header {
            if let Some(crate::Luks2Digest::Pbkdf2 { digest, salt, .. }) = h.metadata.digests.get_mut("0") {
                let salt_bytes = base64::engine::general_purpose::STANDARD.decode(&salt).unwrap();
                let mut expected_digest = vec![0u8; SHA256_DIGEST_SIZE];
                pbkdf2::pbkdf2::<hmac::Hmac<sha2::Sha256>>(
                    &volume_key_bytes,
                    &salt_bytes,
                    TEST_ITERATIONS,
                    &mut expected_digest,
                )
                .unwrap();
                *digest = base64::engine::general_purpose::STANDARD.encode(expected_digest);
            }
        }

        let old_password = "old-password".to_string();
        let old_key = UnlockKey::from_passphrase(old_password);

        // Manually "encrypt" the volume key into the keyslot area so get_volume_key works
        // This is necessary because we don't have a real disk.
        device.update_keyslot(&slot0, &old_key, &volume_key).unwrap();

        // 2. Add challenge-response by changing the passphrase
        let new_password = "new-password".to_string();
        let new_key =
            UnlockKey::from_passphrase(new_password).with_software_challenge_response(TEST_CR_SECRET.to_vec());

        device.change_unlock_key(&slot0, &old_key, &new_key).unwrap();

        // 3. Verify unlocking works with both password and CR
        let mut device_to_unlock = device;

        // Verify the library automatically created the challenge-response token
        let cr_slots = device_to_unlock.get_challenge_response_keyslots();
        assert_eq!(cr_slots.len(), 1, "Token should be automatically created");
        let (slot_id, _serial, _slot) = &cr_slots[0];
        assert_eq!(slot_id, &slot0);

        device_to_unlock
            .unlock(&slot0, &new_key)
            .expect("Should unlock with CR");
        assert!(device_to_unlock.unlocked_key.is_some());

        // 4. Verify that changing BACK to a simple password removes the token
        let password_only_key = UnlockKey::from_passphrase("simple-password".to_string());
        device_to_unlock
            .change_unlock_key(&slot0, &new_key, &password_only_key)
            .unwrap();
        assert_eq!(
            device_to_unlock.get_challenge_response_keyslots().len(),
            0,
            "Token should be removed"
        );

        // 5. Verify unlocking fails with wrong CR secret (re-enroll first)
        device_to_unlock
            .change_unlock_key(&slot0, &password_only_key, &new_key)
            .unwrap();
        let wrong_cr_key = UnlockKey::from_passphrase("new-password".to_string())
            .with_software_challenge_response(vec![0x00, 0x00, 0x00, 0x00]);
        let result = device_to_unlock.get_volume_key(&slot0, &wrong_cr_key);
        let vk = result.unwrap();
        device_to_unlock.unlocked_key = Some(vk);
        assert!(!device_to_unlock.verify(&slot0).unwrap());
    }
}