embassy_stm32/cryp/
mod.rs

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
//! Crypto Accelerator (CRYP)
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
use core::cmp::min;
use core::marker::PhantomData;
use core::ptr;

use embassy_hal_internal::{into_ref, PeripheralRef};
use embassy_sync::waitqueue::AtomicWaker;

use crate::dma::{NoDma, Transfer, TransferOptions};
use crate::interrupt::typelevel::Interrupt;
use crate::{interrupt, pac, peripherals, rcc, Peripheral};

const DES_BLOCK_SIZE: usize = 8; // 64 bits
const AES_BLOCK_SIZE: usize = 16; // 128 bits

static CRYP_WAKER: AtomicWaker = AtomicWaker::new();

/// CRYP interrupt handler.
pub struct InterruptHandler<T: Instance> {
    _phantom: PhantomData<T>,
}

impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
    unsafe fn on_interrupt() {
        let bits = T::regs().misr().read();
        if bits.inmis() {
            T::regs().imscr().modify(|w| w.set_inim(false));
            CRYP_WAKER.wake();
        }
        if bits.outmis() {
            T::regs().imscr().modify(|w| w.set_outim(false));
            CRYP_WAKER.wake();
        }
    }
}

/// This trait encapsulates all cipher-specific behavior/
pub trait Cipher<'c> {
    /// Processing block size. Determined by the processor and the algorithm.
    const BLOCK_SIZE: usize;

    /// Indicates whether the cipher requires the application to provide padding.
    /// If `true`, no partial blocks will be accepted (a panic will occur).
    const REQUIRES_PADDING: bool = false;

    /// Returns the symmetric key.
    fn key(&self) -> &[u8];

    /// Returns the initialization vector.
    fn iv(&self) -> &[u8];

    /// Sets the processor algorithm mode according to the associated cipher.
    fn set_algomode(&self, p: pac::cryp::Cryp);

    /// Performs any key preparation within the processor, if necessary.
    fn prepare_key(&self, _p: pac::cryp::Cryp) {}

    /// Performs any cipher-specific initialization.
    fn init_phase_blocking<T: Instance, DmaIn, DmaOut>(&self, _p: pac::cryp::Cryp, _cryp: &Cryp<T, DmaIn, DmaOut>) {}

    /// Performs any cipher-specific initialization.
    async fn init_phase<T: Instance, DmaIn, DmaOut>(&self, _p: pac::cryp::Cryp, _cryp: &mut Cryp<'_, T, DmaIn, DmaOut>)
    where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
    }

    /// Called prior to processing the last data block for cipher-specific operations.
    fn pre_final(&self, _p: pac::cryp::Cryp, _dir: Direction, _padding_len: usize) -> [u32; 4] {
        return [0; 4];
    }

    /// Called after processing the last data block for cipher-specific operations.
    fn post_final_blocking<T: Instance, DmaIn, DmaOut>(
        &self,
        _p: pac::cryp::Cryp,
        _cryp: &Cryp<T, DmaIn, DmaOut>,
        _dir: Direction,
        _int_data: &mut [u8; AES_BLOCK_SIZE],
        _temp1: [u32; 4],
        _padding_mask: [u8; 16],
    ) {
    }

    /// Called after processing the last data block for cipher-specific operations.
    async fn post_final<T: Instance, DmaIn, DmaOut>(
        &self,
        _p: pac::cryp::Cryp,
        _cryp: &mut Cryp<'_, T, DmaIn, DmaOut>,
        _dir: Direction,
        _int_data: &mut [u8; AES_BLOCK_SIZE],
        _temp1: [u32; 4],
        _padding_mask: [u8; 16],
    ) where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
    }

    /// Returns the AAD header block as required by the cipher.
    fn get_header_block(&self) -> &[u8] {
        return [0; 0].as_slice();
    }
}

/// This trait enables restriction of ciphers to specific key sizes.
pub trait CipherSized {}

/// This trait enables restriction of initialization vectors to sizes compatibile with a cipher mode.
pub trait IVSized {}

/// This trait enables restriction of a header phase to authenticated ciphers only.
pub trait CipherAuthenticated<const TAG_SIZE: usize> {
    /// Defines the authentication tag size.
    const TAG_SIZE: usize = TAG_SIZE;
}

/// TDES-ECB Cipher Mode
pub struct TdesEcb<'c, const KEY_SIZE: usize> {
    iv: &'c [u8; 0],
    key: &'c [u8; KEY_SIZE],
}

impl<'c, const KEY_SIZE: usize> TdesEcb<'c, KEY_SIZE> {
    /// Constructs a new AES-ECB cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE]) -> Self {
        return Self { key: key, iv: &[0; 0] };
    }
}

impl<'c, const KEY_SIZE: usize> Cipher<'c> for TdesEcb<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = DES_BLOCK_SIZE;
    const REQUIRES_PADDING: bool = true;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &'c [u8] {
        self.iv
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(0));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(0));
            p.cr().modify(|w| w.set_algomode3(false));
        }
    }
}

impl<'c> CipherSized for TdesEcb<'c, { 112 / 8 }> {}
impl<'c> CipherSized for TdesEcb<'c, { 168 / 8 }> {}
impl<'c, const KEY_SIZE: usize> IVSized for TdesEcb<'c, KEY_SIZE> {}

/// TDES-CBC Cipher Mode
pub struct TdesCbc<'c, const KEY_SIZE: usize> {
    iv: &'c [u8; 8],
    key: &'c [u8; KEY_SIZE],
}

impl<'c, const KEY_SIZE: usize> TdesCbc<'c, KEY_SIZE> {
    /// Constructs a new TDES-CBC cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 8]) -> Self {
        return Self { key: key, iv: iv };
    }
}

impl<'c, const KEY_SIZE: usize> Cipher<'c> for TdesCbc<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = DES_BLOCK_SIZE;
    const REQUIRES_PADDING: bool = true;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &'c [u8] {
        self.iv
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(1));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(1));
            p.cr().modify(|w| w.set_algomode3(false));
        }
    }
}

impl<'c> CipherSized for TdesCbc<'c, { 112 / 8 }> {}
impl<'c> CipherSized for TdesCbc<'c, { 168 / 8 }> {}
impl<'c, const KEY_SIZE: usize> IVSized for TdesCbc<'c, KEY_SIZE> {}

/// DES-ECB Cipher Mode
pub struct DesEcb<'c, const KEY_SIZE: usize> {
    iv: &'c [u8; 0],
    key: &'c [u8; KEY_SIZE],
}

impl<'c, const KEY_SIZE: usize> DesEcb<'c, KEY_SIZE> {
    /// Constructs a new AES-ECB cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE]) -> Self {
        return Self { key: key, iv: &[0; 0] };
    }
}

impl<'c, const KEY_SIZE: usize> Cipher<'c> for DesEcb<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = DES_BLOCK_SIZE;
    const REQUIRES_PADDING: bool = true;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &'c [u8] {
        self.iv
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(2));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(2));
            p.cr().modify(|w| w.set_algomode3(false));
        }
    }
}

impl<'c> CipherSized for DesEcb<'c, { 56 / 8 }> {}
impl<'c, const KEY_SIZE: usize> IVSized for DesEcb<'c, KEY_SIZE> {}

/// DES-CBC Cipher Mode
pub struct DesCbc<'c, const KEY_SIZE: usize> {
    iv: &'c [u8; 8],
    key: &'c [u8; KEY_SIZE],
}

impl<'c, const KEY_SIZE: usize> DesCbc<'c, KEY_SIZE> {
    /// Constructs a new AES-CBC cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 8]) -> Self {
        return Self { key: key, iv: iv };
    }
}

impl<'c, const KEY_SIZE: usize> Cipher<'c> for DesCbc<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = DES_BLOCK_SIZE;
    const REQUIRES_PADDING: bool = true;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &'c [u8] {
        self.iv
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(3));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(3));
            p.cr().modify(|w| w.set_algomode3(false));
        }
    }
}

impl<'c> CipherSized for DesCbc<'c, { 56 / 8 }> {}
impl<'c, const KEY_SIZE: usize> IVSized for DesCbc<'c, KEY_SIZE> {}

/// AES-ECB Cipher Mode
pub struct AesEcb<'c, const KEY_SIZE: usize> {
    iv: &'c [u8; 0],
    key: &'c [u8; KEY_SIZE],
}

impl<'c, const KEY_SIZE: usize> AesEcb<'c, KEY_SIZE> {
    /// Constructs a new AES-ECB cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE]) -> Self {
        return Self { key: key, iv: &[0; 0] };
    }
}

impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesEcb<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = AES_BLOCK_SIZE;
    const REQUIRES_PADDING: bool = true;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &'c [u8] {
        self.iv
    }

    fn prepare_key(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(7));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(7));
            p.cr().modify(|w| w.set_algomode3(false));
        }
        p.cr().modify(|w| w.set_crypen(true));
        while p.sr().read().busy() {}
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(2));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(2));
            p.cr().modify(|w| w.set_algomode3(false));
        }
    }
}

impl<'c> CipherSized for AesEcb<'c, { 128 / 8 }> {}
impl<'c> CipherSized for AesEcb<'c, { 192 / 8 }> {}
impl<'c> CipherSized for AesEcb<'c, { 256 / 8 }> {}
impl<'c, const KEY_SIZE: usize> IVSized for AesEcb<'c, KEY_SIZE> {}

/// AES-CBC Cipher Mode
pub struct AesCbc<'c, const KEY_SIZE: usize> {
    iv: &'c [u8; 16],
    key: &'c [u8; KEY_SIZE],
}

impl<'c, const KEY_SIZE: usize> AesCbc<'c, KEY_SIZE> {
    /// Constructs a new AES-CBC cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 16]) -> Self {
        return Self { key: key, iv: iv };
    }
}

impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesCbc<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = AES_BLOCK_SIZE;
    const REQUIRES_PADDING: bool = true;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &'c [u8] {
        self.iv
    }

    fn prepare_key(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(7));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(7));
            p.cr().modify(|w| w.set_algomode3(false));
        }
        p.cr().modify(|w| w.set_crypen(true));
        while p.sr().read().busy() {}
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(5));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(5));
            p.cr().modify(|w| w.set_algomode3(false));
        }
    }
}

impl<'c> CipherSized for AesCbc<'c, { 128 / 8 }> {}
impl<'c> CipherSized for AesCbc<'c, { 192 / 8 }> {}
impl<'c> CipherSized for AesCbc<'c, { 256 / 8 }> {}
impl<'c, const KEY_SIZE: usize> IVSized for AesCbc<'c, KEY_SIZE> {}

/// AES-CTR Cipher Mode
pub struct AesCtr<'c, const KEY_SIZE: usize> {
    iv: &'c [u8; 16],
    key: &'c [u8; KEY_SIZE],
}

impl<'c, const KEY_SIZE: usize> AesCtr<'c, KEY_SIZE> {
    /// Constructs a new AES-CTR cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 16]) -> Self {
        return Self { key: key, iv: iv };
    }
}

impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesCtr<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = AES_BLOCK_SIZE;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &'c [u8] {
        self.iv
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        #[cfg(cryp_v1)]
        {
            p.cr().modify(|w| w.set_algomode(6));
        }
        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        {
            p.cr().modify(|w| w.set_algomode0(6));
            p.cr().modify(|w| w.set_algomode3(false));
        }
    }
}

impl<'c> CipherSized for AesCtr<'c, { 128 / 8 }> {}
impl<'c> CipherSized for AesCtr<'c, { 192 / 8 }> {}
impl<'c> CipherSized for AesCtr<'c, { 256 / 8 }> {}
impl<'c, const KEY_SIZE: usize> IVSized for AesCtr<'c, KEY_SIZE> {}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
///AES-GCM Cipher Mode
pub struct AesGcm<'c, const KEY_SIZE: usize> {
    iv: [u8; 16],
    key: &'c [u8; KEY_SIZE],
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize> AesGcm<'c, KEY_SIZE> {
    /// Constucts a new AES-GCM cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 12]) -> Self {
        let mut new_gcm = Self { key: key, iv: [0; 16] };
        new_gcm.iv[..12].copy_from_slice(iv);
        new_gcm.iv[15] = 2;
        new_gcm
    }
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesGcm<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = AES_BLOCK_SIZE;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &[u8] {
        self.iv.as_slice()
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        p.cr().modify(|w| w.set_algomode0(0));
        p.cr().modify(|w| w.set_algomode3(true));
    }

    fn init_phase_blocking<T: Instance, DmaIn, DmaOut>(&self, p: pac::cryp::Cryp, _cryp: &Cryp<T, DmaIn, DmaOut>) {
        p.cr().modify(|w| w.set_gcm_ccmph(0));
        p.cr().modify(|w| w.set_crypen(true));
        while p.cr().read().crypen() {}
    }

    async fn init_phase<T: Instance, DmaIn, DmaOut>(&self, p: pac::cryp::Cryp, _cryp: &mut Cryp<'_, T, DmaIn, DmaOut>) {
        p.cr().modify(|w| w.set_gcm_ccmph(0));
        p.cr().modify(|w| w.set_crypen(true));
        while p.cr().read().crypen() {}
    }

    #[cfg(cryp_v2)]
    fn pre_final(&self, p: pac::cryp::Cryp, dir: Direction, _padding_len: usize) -> [u32; 4] {
        //Handle special GCM partial block process.
        if dir == Direction::Encrypt {
            p.cr().modify(|w| w.set_crypen(false));
            p.cr().modify(|w| w.set_algomode3(false));
            p.cr().modify(|w| w.set_algomode0(6));
            let iv1r = p.csgcmccmr(7).read() - 1;
            p.init(1).ivrr().write_value(iv1r);
            p.cr().modify(|w| w.set_crypen(true));
        }
        [0; 4]
    }

    #[cfg(any(cryp_v3, cryp_v4))]
    fn pre_final(&self, p: pac::cryp::Cryp, _dir: Direction, padding_len: usize) -> [u32; 4] {
        //Handle special GCM partial block process.
        p.cr().modify(|w| w.set_npblb(padding_len as u8));
        [0; 4]
    }

    #[cfg(cryp_v2)]
    fn post_final_blocking<T: Instance, DmaIn, DmaOut>(
        &self,
        p: pac::cryp::Cryp,
        cryp: &Cryp<T, DmaIn, DmaOut>,
        dir: Direction,
        int_data: &mut [u8; AES_BLOCK_SIZE],
        _temp1: [u32; 4],
        padding_mask: [u8; AES_BLOCK_SIZE],
    ) {
        if dir == Direction::Encrypt {
            //Handle special GCM partial block process.
            p.cr().modify(|w| w.set_crypen(false));
            p.cr().modify(|w| w.set_algomode3(true));
            p.cr().modify(|w| w.set_algomode0(0));
            for i in 0..AES_BLOCK_SIZE {
                int_data[i] = int_data[i] & padding_mask[i];
            }
            p.cr().modify(|w| w.set_crypen(true));
            p.cr().modify(|w| w.set_gcm_ccmph(3));

            cryp.write_bytes_blocking(Self::BLOCK_SIZE, int_data);
            cryp.read_bytes_blocking(Self::BLOCK_SIZE, int_data);
        }
    }

    #[cfg(cryp_v2)]
    async fn post_final<T: Instance, DmaIn, DmaOut>(
        &self,
        p: pac::cryp::Cryp,
        cryp: &mut Cryp<'_, T, DmaIn, DmaOut>,
        dir: Direction,
        int_data: &mut [u8; AES_BLOCK_SIZE],
        _temp1: [u32; 4],
        padding_mask: [u8; AES_BLOCK_SIZE],
    ) where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
        if dir == Direction::Encrypt {
            // Handle special GCM partial block process.
            p.cr().modify(|w| w.set_crypen(false));
            p.cr().modify(|w| w.set_algomode3(true));
            p.cr().modify(|w| w.set_algomode0(0));
            for i in 0..AES_BLOCK_SIZE {
                int_data[i] = int_data[i] & padding_mask[i];
            }
            p.cr().modify(|w| w.set_crypen(true));
            p.cr().modify(|w| w.set_gcm_ccmph(3));

            let mut out_data: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE];

            let read = Cryp::<T, DmaIn, DmaOut>::read_bytes(&mut cryp.outdma, Self::BLOCK_SIZE, &mut out_data);
            let write = Cryp::<T, DmaIn, DmaOut>::write_bytes(&mut cryp.indma, Self::BLOCK_SIZE, int_data);

            embassy_futures::join::join(read, write).await;

            int_data.copy_from_slice(&out_data);
        }
    }
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c> CipherSized for AesGcm<'c, { 128 / 8 }> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c> CipherSized for AesGcm<'c, { 192 / 8 }> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c> CipherSized for AesGcm<'c, { 256 / 8 }> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize> CipherAuthenticated<16> for AesGcm<'c, KEY_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize> IVSized for AesGcm<'c, KEY_SIZE> {}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
/// AES-GMAC Cipher Mode
pub struct AesGmac<'c, const KEY_SIZE: usize> {
    iv: [u8; 16],
    key: &'c [u8; KEY_SIZE],
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize> AesGmac<'c, KEY_SIZE> {
    /// Constructs a new AES-GMAC cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 12]) -> Self {
        let mut new_gmac = Self { key: key, iv: [0; 16] };
        new_gmac.iv[..12].copy_from_slice(iv);
        new_gmac.iv[15] = 2;
        new_gmac
    }
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesGmac<'c, KEY_SIZE> {
    const BLOCK_SIZE: usize = AES_BLOCK_SIZE;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &[u8] {
        self.iv.as_slice()
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        p.cr().modify(|w| w.set_algomode0(0));
        p.cr().modify(|w| w.set_algomode3(true));
    }

    fn init_phase_blocking<T: Instance, DmaIn, DmaOut>(&self, p: pac::cryp::Cryp, _cryp: &Cryp<T, DmaIn, DmaOut>) {
        p.cr().modify(|w| w.set_gcm_ccmph(0));
        p.cr().modify(|w| w.set_crypen(true));
        while p.cr().read().crypen() {}
    }

    async fn init_phase<T: Instance, DmaIn, DmaOut>(&self, p: pac::cryp::Cryp, _cryp: &mut Cryp<'_, T, DmaIn, DmaOut>) {
        p.cr().modify(|w| w.set_gcm_ccmph(0));
        p.cr().modify(|w| w.set_crypen(true));
        while p.cr().read().crypen() {}
    }

    #[cfg(cryp_v2)]
    fn pre_final(&self, p: pac::cryp::Cryp, dir: Direction, _padding_len: usize) -> [u32; 4] {
        //Handle special GCM partial block process.
        if dir == Direction::Encrypt {
            p.cr().modify(|w| w.set_crypen(false));
            p.cr().modify(|w| w.set_algomode3(false));
            p.cr().modify(|w| w.set_algomode0(6));
            let iv1r = p.csgcmccmr(7).read() - 1;
            p.init(1).ivrr().write_value(iv1r);
            p.cr().modify(|w| w.set_crypen(true));
        }
        [0; 4]
    }

    #[cfg(any(cryp_v3, cryp_v4))]
    fn pre_final(&self, p: pac::cryp::Cryp, _dir: Direction, padding_len: usize) -> [u32; 4] {
        //Handle special GCM partial block process.
        p.cr().modify(|w| w.set_npblb(padding_len as u8));
        [0; 4]
    }

    #[cfg(cryp_v2)]
    fn post_final_blocking<T: Instance, DmaIn, DmaOut>(
        &self,
        p: pac::cryp::Cryp,
        cryp: &Cryp<T, DmaIn, DmaOut>,
        dir: Direction,
        int_data: &mut [u8; AES_BLOCK_SIZE],
        _temp1: [u32; 4],
        padding_mask: [u8; AES_BLOCK_SIZE],
    ) {
        if dir == Direction::Encrypt {
            //Handle special GCM partial block process.
            p.cr().modify(|w| w.set_crypen(false));
            p.cr().modify(|w| w.set_algomode3(true));
            p.cr().modify(|w| w.set_algomode0(0));
            for i in 0..AES_BLOCK_SIZE {
                int_data[i] = int_data[i] & padding_mask[i];
            }
            p.cr().modify(|w| w.set_crypen(true));
            p.cr().modify(|w| w.set_gcm_ccmph(3));

            cryp.write_bytes_blocking(Self::BLOCK_SIZE, int_data);
            cryp.read_bytes_blocking(Self::BLOCK_SIZE, int_data);
        }
    }

    #[cfg(cryp_v2)]
    async fn post_final<T: Instance, DmaIn, DmaOut>(
        &self,
        p: pac::cryp::Cryp,
        cryp: &mut Cryp<'_, T, DmaIn, DmaOut>,
        dir: Direction,
        int_data: &mut [u8; AES_BLOCK_SIZE],
        _temp1: [u32; 4],
        padding_mask: [u8; AES_BLOCK_SIZE],
    ) where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
        if dir == Direction::Encrypt {
            // Handle special GCM partial block process.
            p.cr().modify(|w| w.set_crypen(false));
            p.cr().modify(|w| w.set_algomode3(true));
            p.cr().modify(|w| w.set_algomode0(0));
            for i in 0..AES_BLOCK_SIZE {
                int_data[i] = int_data[i] & padding_mask[i];
            }
            p.cr().modify(|w| w.set_crypen(true));
            p.cr().modify(|w| w.set_gcm_ccmph(3));

            let mut out_data: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE];

            let read = Cryp::<T, DmaIn, DmaOut>::read_bytes(&mut cryp.outdma, Self::BLOCK_SIZE, &mut out_data);
            let write = Cryp::<T, DmaIn, DmaOut>::write_bytes(&mut cryp.indma, Self::BLOCK_SIZE, int_data);

            embassy_futures::join::join(read, write).await;
        }
    }
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c> CipherSized for AesGmac<'c, { 128 / 8 }> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c> CipherSized for AesGmac<'c, { 192 / 8 }> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c> CipherSized for AesGmac<'c, { 256 / 8 }> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize> CipherAuthenticated<16> for AesGmac<'c, KEY_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize> IVSized for AesGmac<'c, KEY_SIZE> {}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
/// AES-CCM Cipher Mode
pub struct AesCcm<'c, const KEY_SIZE: usize, const TAG_SIZE: usize, const IV_SIZE: usize> {
    key: &'c [u8; KEY_SIZE],
    aad_header: [u8; 6],
    aad_header_len: usize,
    block0: [u8; 16],
    ctr: [u8; 16],
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize, const IV_SIZE: usize> AesCcm<'c, KEY_SIZE, TAG_SIZE, IV_SIZE> {
    /// Constructs a new AES-CCM cipher for a cryptographic operation.
    pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; IV_SIZE], aad_len: usize, payload_len: usize) -> Self {
        let mut aad_header: [u8; 6] = [0; 6];
        let mut aad_header_len = 0;
        let mut block0: [u8; 16] = [0; 16];
        if aad_len != 0 {
            if aad_len < 65280 {
                aad_header[0] = (aad_len >> 8) as u8 & 0xFF;
                aad_header[1] = aad_len as u8 & 0xFF;
                aad_header_len = 2;
            } else {
                aad_header[0] = 0xFF;
                aad_header[1] = 0xFE;
                let aad_len_bytes: [u8; 4] = (aad_len as u32).to_be_bytes();
                aad_header[2] = aad_len_bytes[0];
                aad_header[3] = aad_len_bytes[1];
                aad_header[4] = aad_len_bytes[2];
                aad_header[5] = aad_len_bytes[3];
                aad_header_len = 6;
            }
        }
        let total_aad_len = aad_header_len + aad_len;
        let mut aad_padding_len = 16 - (total_aad_len % 16);
        if aad_padding_len == 16 {
            aad_padding_len = 0;
        }
        aad_header_len += aad_padding_len;
        let total_aad_len_padded = aad_header_len + aad_len;
        if total_aad_len_padded > 0 {
            block0[0] = 0x40;
        }
        block0[0] |= ((((TAG_SIZE as u8) - 2) >> 1) & 0x07) << 3;
        block0[0] |= ((15 - (iv.len() as u8)) - 1) & 0x07;
        block0[1..1 + iv.len()].copy_from_slice(iv);
        let payload_len_bytes: [u8; 4] = (payload_len as u32).to_be_bytes();
        if iv.len() <= 11 {
            block0[12] = payload_len_bytes[0];
        } else if payload_len_bytes[0] > 0 {
            panic!("Message is too large for given IV size.");
        }
        if iv.len() <= 12 {
            block0[13] = payload_len_bytes[1];
        } else if payload_len_bytes[1] > 0 {
            panic!("Message is too large for given IV size.");
        }
        block0[14] = payload_len_bytes[2];
        block0[15] = payload_len_bytes[3];
        let mut ctr: [u8; 16] = [0; 16];
        ctr[0] = block0[0] & 0x07;
        ctr[1..1 + iv.len()].copy_from_slice(&block0[1..1 + iv.len()]);
        ctr[15] = 0x01;

        return Self {
            key: key,
            aad_header: aad_header,
            aad_header_len: aad_header_len,
            block0: block0,
            ctr: ctr,
        };
    }
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize, const IV_SIZE: usize> Cipher<'c>
    for AesCcm<'c, KEY_SIZE, TAG_SIZE, IV_SIZE>
{
    const BLOCK_SIZE: usize = AES_BLOCK_SIZE;

    fn key(&self) -> &'c [u8] {
        self.key
    }

    fn iv(&self) -> &[u8] {
        self.ctr.as_slice()
    }

    fn set_algomode(&self, p: pac::cryp::Cryp) {
        p.cr().modify(|w| w.set_algomode0(1));
        p.cr().modify(|w| w.set_algomode3(true));
    }

    fn init_phase_blocking<T: Instance, DmaIn, DmaOut>(&self, p: pac::cryp::Cryp, cryp: &Cryp<T, DmaIn, DmaOut>) {
        p.cr().modify(|w| w.set_gcm_ccmph(0));

        cryp.write_bytes_blocking(Self::BLOCK_SIZE, &self.block0);

        p.cr().modify(|w| w.set_crypen(true));
        while p.cr().read().crypen() {}
    }

    async fn init_phase<T: Instance, DmaIn, DmaOut>(&self, p: pac::cryp::Cryp, cryp: &mut Cryp<'_, T, DmaIn, DmaOut>)
    where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
        p.cr().modify(|w| w.set_gcm_ccmph(0));

        Cryp::<T, DmaIn, DmaOut>::write_bytes(&mut cryp.indma, Self::BLOCK_SIZE, &self.block0).await;

        p.cr().modify(|w| w.set_crypen(true));
        while p.cr().read().crypen() {}
    }

    fn get_header_block(&self) -> &[u8] {
        return &self.aad_header[0..self.aad_header_len];
    }

    #[cfg(cryp_v2)]
    fn pre_final(&self, p: pac::cryp::Cryp, dir: Direction, _padding_len: usize) -> [u32; 4] {
        //Handle special CCM partial block process.
        let mut temp1 = [0; 4];
        if dir == Direction::Decrypt {
            p.cr().modify(|w| w.set_crypen(false));
            let iv1temp = p.init(1).ivrr().read();
            temp1[0] = p.csgcmccmr(0).read().swap_bytes();
            temp1[1] = p.csgcmccmr(1).read().swap_bytes();
            temp1[2] = p.csgcmccmr(2).read().swap_bytes();
            temp1[3] = p.csgcmccmr(3).read().swap_bytes();
            p.init(1).ivrr().write_value(iv1temp);
            p.cr().modify(|w| w.set_algomode3(false));
            p.cr().modify(|w| w.set_algomode0(6));
            p.cr().modify(|w| w.set_crypen(true));
        }
        return temp1;
    }

    #[cfg(any(cryp_v3, cryp_v4))]
    fn pre_final(&self, p: pac::cryp::Cryp, _dir: Direction, padding_len: usize) -> [u32; 4] {
        //Handle special GCM partial block process.
        p.cr().modify(|w| w.set_npblb(padding_len as u8));
        [0; 4]
    }

    #[cfg(cryp_v2)]
    fn post_final_blocking<T: Instance, DmaIn, DmaOut>(
        &self,
        p: pac::cryp::Cryp,
        cryp: &Cryp<T, DmaIn, DmaOut>,
        dir: Direction,
        int_data: &mut [u8; AES_BLOCK_SIZE],
        temp1: [u32; 4],
        padding_mask: [u8; 16],
    ) {
        if dir == Direction::Decrypt {
            //Handle special CCM partial block process.
            let mut temp2 = [0; 4];
            temp2[0] = p.csgcmccmr(0).read().swap_bytes();
            temp2[1] = p.csgcmccmr(1).read().swap_bytes();
            temp2[2] = p.csgcmccmr(2).read().swap_bytes();
            temp2[3] = p.csgcmccmr(3).read().swap_bytes();
            p.cr().modify(|w| w.set_algomode3(true));
            p.cr().modify(|w| w.set_algomode0(1));
            p.cr().modify(|w| w.set_gcm_ccmph(3));
            // Header phase
            p.cr().modify(|w| w.set_gcm_ccmph(1));
            for i in 0..AES_BLOCK_SIZE {
                int_data[i] = int_data[i] & padding_mask[i];
            }
            let mut in_data: [u32; 4] = [0; 4];
            for i in 0..in_data.len() {
                let mut int_bytes: [u8; 4] = [0; 4];
                int_bytes.copy_from_slice(&int_data[(i * 4)..(i * 4) + 4]);
                let int_word = u32::from_le_bytes(int_bytes);
                in_data[i] = int_word;
                in_data[i] = in_data[i] ^ temp1[i] ^ temp2[i];
            }
            cryp.write_words_blocking(Self::BLOCK_SIZE, &in_data);
        }
    }

    #[cfg(cryp_v2)]
    async fn post_final<T: Instance, DmaIn, DmaOut>(
        &self,
        p: pac::cryp::Cryp,
        cryp: &mut Cryp<'_, T, DmaIn, DmaOut>,
        dir: Direction,
        int_data: &mut [u8; AES_BLOCK_SIZE],
        temp1: [u32; 4],
        padding_mask: [u8; 16],
    ) where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
        if dir == Direction::Decrypt {
            //Handle special CCM partial block process.
            let mut temp2 = [0; 4];
            temp2[0] = p.csgcmccmr(0).read().swap_bytes();
            temp2[1] = p.csgcmccmr(1).read().swap_bytes();
            temp2[2] = p.csgcmccmr(2).read().swap_bytes();
            temp2[3] = p.csgcmccmr(3).read().swap_bytes();
            p.cr().modify(|w| w.set_algomode3(true));
            p.cr().modify(|w| w.set_algomode0(1));
            p.cr().modify(|w| w.set_gcm_ccmph(3));
            // Header phase
            p.cr().modify(|w| w.set_gcm_ccmph(1));
            for i in 0..AES_BLOCK_SIZE {
                int_data[i] = int_data[i] & padding_mask[i];
            }
            let mut in_data: [u32; 4] = [0; 4];
            for i in 0..in_data.len() {
                let mut int_bytes: [u8; 4] = [0; 4];
                int_bytes.copy_from_slice(&int_data[(i * 4)..(i * 4) + 4]);
                let int_word = u32::from_le_bytes(int_bytes);
                in_data[i] = int_word;
                in_data[i] = in_data[i] ^ temp1[i] ^ temp2[i];
            }
            Cryp::<T, DmaIn, DmaOut>::write_words(&mut cryp.indma, Self::BLOCK_SIZE, &in_data).await;
        }
    }
}

#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const TAG_SIZE: usize, const IV_SIZE: usize> CipherSized for AesCcm<'c, { 128 / 8 }, TAG_SIZE, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const TAG_SIZE: usize, const IV_SIZE: usize> CipherSized for AesCcm<'c, { 192 / 8 }, TAG_SIZE, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const TAG_SIZE: usize, const IV_SIZE: usize> CipherSized for AesCcm<'c, { 256 / 8 }, TAG_SIZE, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<4> for AesCcm<'c, KEY_SIZE, 4, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<6> for AesCcm<'c, KEY_SIZE, 6, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<8> for AesCcm<'c, KEY_SIZE, 8, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<10> for AesCcm<'c, KEY_SIZE, 10, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<12> for AesCcm<'c, KEY_SIZE, 12, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<14> for AesCcm<'c, KEY_SIZE, 14, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<16> for AesCcm<'c, KEY_SIZE, 16, IV_SIZE> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 7> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 8> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 9> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 10> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 11> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 12> {}
#[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 13> {}

#[allow(dead_code)]
/// Holds the state information for a cipher operation.
/// Allows suspending/resuming of cipher operations.
pub struct Context<'c, C: Cipher<'c> + CipherSized> {
    phantom_data: PhantomData<&'c C>,
    cipher: &'c C,
    dir: Direction,
    last_block_processed: bool,
    header_processed: bool,
    aad_complete: bool,
    cr: u32,
    iv: [u32; 4],
    csgcmccm: [u32; 8],
    csgcm: [u32; 8],
    header_len: u64,
    payload_len: u64,
    aad_buffer: [u8; 16],
    aad_buffer_len: usize,
}

/// Selects whether the crypto processor operates in encryption or decryption mode.
#[derive(PartialEq, Clone, Copy)]
pub enum Direction {
    /// Encryption mode
    Encrypt,
    /// Decryption mode
    Decrypt,
}

/// Crypto Accelerator Driver
pub struct Cryp<'d, T: Instance, DmaIn = NoDma, DmaOut = NoDma> {
    _peripheral: PeripheralRef<'d, T>,
    indma: PeripheralRef<'d, DmaIn>,
    outdma: PeripheralRef<'d, DmaOut>,
}

impl<'d, T: Instance, DmaIn, DmaOut> Cryp<'d, T, DmaIn, DmaOut> {
    /// Create a new CRYP driver.
    pub fn new(
        peri: impl Peripheral<P = T> + 'd,
        indma: impl Peripheral<P = DmaIn> + 'd,
        outdma: impl Peripheral<P = DmaOut> + 'd,
        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
    ) -> Self {
        rcc::enable_and_reset::<T>();
        into_ref!(peri, indma, outdma);
        let instance = Self {
            _peripheral: peri,
            indma: indma,
            outdma: outdma,
        };

        T::Interrupt::unpend();
        unsafe { T::Interrupt::enable() };

        instance
    }

    /// Start a new encrypt or decrypt operation for the given cipher.
    pub fn start_blocking<'c, C: Cipher<'c> + CipherSized + IVSized>(
        &self,
        cipher: &'c C,
        dir: Direction,
    ) -> Context<'c, C> {
        let mut ctx: Context<'c, C> = Context {
            dir,
            last_block_processed: false,
            cr: 0,
            iv: [0; 4],
            csgcmccm: [0; 8],
            csgcm: [0; 8],
            aad_complete: false,
            header_len: 0,
            payload_len: 0,
            cipher: cipher,
            phantom_data: PhantomData,
            header_processed: false,
            aad_buffer: [0; 16],
            aad_buffer_len: 0,
        };

        T::regs().cr().modify(|w| w.set_crypen(false));

        let key = ctx.cipher.key();

        if key.len() == (128 / 8) {
            T::regs().cr().modify(|w| w.set_keysize(0));
        } else if key.len() == (192 / 8) {
            T::regs().cr().modify(|w| w.set_keysize(1));
        } else if key.len() == (256 / 8) {
            T::regs().cr().modify(|w| w.set_keysize(2));
        }

        self.load_key(key);

        // Set data type to 8-bit. This will match software implementations.
        T::regs().cr().modify(|w| w.set_datatype(2));

        ctx.cipher.prepare_key(T::regs());

        ctx.cipher.set_algomode(T::regs());

        // Set encrypt/decrypt
        if dir == Direction::Encrypt {
            T::regs().cr().modify(|w| w.set_algodir(false));
        } else {
            T::regs().cr().modify(|w| w.set_algodir(true));
        }

        // Load the IV into the registers.
        let iv = ctx.cipher.iv();
        let mut full_iv: [u8; 16] = [0; 16];
        full_iv[0..iv.len()].copy_from_slice(iv);
        let mut iv_idx = 0;
        let mut iv_word: [u8; 4] = [0; 4];
        iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]);
        iv_idx += 4;
        T::regs().init(0).ivlr().write_value(u32::from_be_bytes(iv_word));
        iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]);
        iv_idx += 4;
        T::regs().init(0).ivrr().write_value(u32::from_be_bytes(iv_word));
        iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]);
        iv_idx += 4;
        T::regs().init(1).ivlr().write_value(u32::from_be_bytes(iv_word));
        iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]);
        T::regs().init(1).ivrr().write_value(u32::from_be_bytes(iv_word));

        // Flush in/out FIFOs
        T::regs().cr().modify(|w| w.fflush());

        ctx.cipher.init_phase_blocking(T::regs(), self);

        self.store_context(&mut ctx);

        ctx
    }

    /// Start a new encrypt or decrypt operation for the given cipher.
    pub async fn start<'c, C: Cipher<'c> + CipherSized + IVSized>(
        &mut self,
        cipher: &'c C,
        dir: Direction,
    ) -> Context<'c, C>
    where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
        let mut ctx: Context<'c, C> = Context {
            dir,
            last_block_processed: false,
            cr: 0,
            iv: [0; 4],
            csgcmccm: [0; 8],
            csgcm: [0; 8],
            aad_complete: false,
            header_len: 0,
            payload_len: 0,
            cipher: cipher,
            phantom_data: PhantomData,
            header_processed: false,
            aad_buffer: [0; 16],
            aad_buffer_len: 0,
        };

        T::regs().cr().modify(|w| w.set_crypen(false));

        let key = ctx.cipher.key();

        if key.len() == (128 / 8) {
            T::regs().cr().modify(|w| w.set_keysize(0));
        } else if key.len() == (192 / 8) {
            T::regs().cr().modify(|w| w.set_keysize(1));
        } else if key.len() == (256 / 8) {
            T::regs().cr().modify(|w| w.set_keysize(2));
        }

        self.load_key(key);

        // Set data type to 8-bit. This will match software implementations.
        T::regs().cr().modify(|w| w.set_datatype(2));

        ctx.cipher.prepare_key(T::regs());

        ctx.cipher.set_algomode(T::regs());

        // Set encrypt/decrypt
        if dir == Direction::Encrypt {
            T::regs().cr().modify(|w| w.set_algodir(false));
        } else {
            T::regs().cr().modify(|w| w.set_algodir(true));
        }

        // Load the IV into the registers.
        let iv = ctx.cipher.iv();
        let mut full_iv: [u8; 16] = [0; 16];
        full_iv[0..iv.len()].copy_from_slice(iv);
        let mut iv_idx = 0;
        let mut iv_word: [u8; 4] = [0; 4];
        iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]);
        iv_idx += 4;
        T::regs().init(0).ivlr().write_value(u32::from_be_bytes(iv_word));
        iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]);
        iv_idx += 4;
        T::regs().init(0).ivrr().write_value(u32::from_be_bytes(iv_word));
        iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]);
        iv_idx += 4;
        T::regs().init(1).ivlr().write_value(u32::from_be_bytes(iv_word));
        iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]);
        T::regs().init(1).ivrr().write_value(u32::from_be_bytes(iv_word));

        // Flush in/out FIFOs
        T::regs().cr().modify(|w| w.fflush());

        ctx.cipher.init_phase(T::regs(), self).await;

        self.store_context(&mut ctx);

        ctx
    }

    #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
    /// Controls the header phase of cipher processing.
    /// This function is only valid for authenticated ciphers including GCM, CCM, and GMAC.
    /// All additional associated data (AAD) must be supplied to this function prior to starting the payload phase with `payload_blocking`.
    /// The AAD must be supplied in multiples of the block size (128-bits for AES, 64-bits for DES), except when supplying the last block.
    /// When supplying the last block of AAD, `last_aad_block` must be `true`.
    pub fn aad_blocking<
        'c,
        const TAG_SIZE: usize,
        C: Cipher<'c> + CipherSized + IVSized + CipherAuthenticated<TAG_SIZE>,
    >(
        &self,
        ctx: &mut Context<'c, C>,
        aad: &[u8],
        last_aad_block: bool,
    ) {
        self.load_context(ctx);

        // Perform checks for correctness.
        if ctx.aad_complete {
            panic!("Cannot update AAD after starting payload!")
        }

        ctx.header_len += aad.len() as u64;

        // Header phase
        T::regs().cr().modify(|w| w.set_crypen(false));
        T::regs().cr().modify(|w| w.set_gcm_ccmph(1));
        T::regs().cr().modify(|w| w.set_crypen(true));

        // First write the header B1 block if not yet written.
        if !ctx.header_processed {
            ctx.header_processed = true;
            let header = ctx.cipher.get_header_block();
            ctx.aad_buffer[0..header.len()].copy_from_slice(header);
            ctx.aad_buffer_len += header.len();
        }

        // Fill the header block to make a full block.
        let len_to_copy = min(aad.len(), C::BLOCK_SIZE - ctx.aad_buffer_len);
        ctx.aad_buffer[ctx.aad_buffer_len..ctx.aad_buffer_len + len_to_copy].copy_from_slice(&aad[..len_to_copy]);
        ctx.aad_buffer_len += len_to_copy;
        ctx.aad_buffer[ctx.aad_buffer_len..].fill(0);
        let mut aad_len_remaining = aad.len() - len_to_copy;

        if ctx.aad_buffer_len < C::BLOCK_SIZE {
            // The buffer isn't full and this is the last buffer, so process it as is (already padded).
            if last_aad_block {
                self.write_bytes_blocking(C::BLOCK_SIZE, &ctx.aad_buffer);
                // Block until input FIFO is empty.
                while !T::regs().sr().read().ifem() {}

                // Switch to payload phase.
                ctx.aad_complete = true;
                T::regs().cr().modify(|w| w.set_crypen(false));
                T::regs().cr().modify(|w| w.set_gcm_ccmph(2));
                T::regs().cr().modify(|w| w.fflush());
            } else {
                // Just return because we don't yet have a full block to process.
                return;
            }
        } else {
            // Load the full block from the buffer.
            self.write_bytes_blocking(C::BLOCK_SIZE, &ctx.aad_buffer);
            // Block until input FIFO is empty.
            while !T::regs().sr().read().ifem() {}
        }

        // Handle a partial block that is passed in.
        ctx.aad_buffer_len = 0;
        let leftovers = aad_len_remaining % C::BLOCK_SIZE;
        ctx.aad_buffer[..leftovers].copy_from_slice(&aad[aad.len() - leftovers..aad.len()]);
        ctx.aad_buffer_len += leftovers;
        ctx.aad_buffer[ctx.aad_buffer_len..].fill(0);
        aad_len_remaining -= leftovers;
        assert_eq!(aad_len_remaining % C::BLOCK_SIZE, 0);

        // Load full data blocks into core.
        let num_full_blocks = aad_len_remaining / C::BLOCK_SIZE;
        let start_index = len_to_copy;
        let end_index = start_index + (C::BLOCK_SIZE * num_full_blocks);
        self.write_bytes_blocking(C::BLOCK_SIZE, &aad[start_index..end_index]);

        if last_aad_block {
            if leftovers > 0 {
                self.write_bytes_blocking(C::BLOCK_SIZE, &ctx.aad_buffer);
            }
            // Switch to payload phase.
            ctx.aad_complete = true;
            T::regs().cr().modify(|w| w.set_crypen(false));
            T::regs().cr().modify(|w| w.set_gcm_ccmph(2));
            T::regs().cr().modify(|w| w.fflush());
        }

        self.store_context(ctx);
    }

    #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
    /// Controls the header phase of cipher processing.
    /// This function is only valid for authenticated ciphers including GCM, CCM, and GMAC.
    /// All additional associated data (AAD) must be supplied to this function prior to starting the payload phase with `payload`.
    /// The AAD must be supplied in multiples of the block size (128-bits for AES, 64-bits for DES), except when supplying the last block.
    /// When supplying the last block of AAD, `last_aad_block` must be `true`.
    pub async fn aad<'c, const TAG_SIZE: usize, C: Cipher<'c> + CipherSized + IVSized + CipherAuthenticated<TAG_SIZE>>(
        &mut self,
        ctx: &mut Context<'c, C>,
        aad: &[u8],
        last_aad_block: bool,
    ) where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
        self.load_context(ctx);

        // Perform checks for correctness.
        if ctx.aad_complete {
            panic!("Cannot update AAD after starting payload!")
        }

        ctx.header_len += aad.len() as u64;

        // Header phase
        T::regs().cr().modify(|w| w.set_crypen(false));
        T::regs().cr().modify(|w| w.set_gcm_ccmph(1));
        T::regs().cr().modify(|w| w.set_crypen(true));

        // First write the header B1 block if not yet written.
        if !ctx.header_processed {
            ctx.header_processed = true;
            let header = ctx.cipher.get_header_block();
            ctx.aad_buffer[0..header.len()].copy_from_slice(header);
            ctx.aad_buffer_len += header.len();
        }

        // Fill the header block to make a full block.
        let len_to_copy = min(aad.len(), C::BLOCK_SIZE - ctx.aad_buffer_len);
        ctx.aad_buffer[ctx.aad_buffer_len..ctx.aad_buffer_len + len_to_copy].copy_from_slice(&aad[..len_to_copy]);
        ctx.aad_buffer_len += len_to_copy;
        ctx.aad_buffer[ctx.aad_buffer_len..].fill(0);
        let mut aad_len_remaining = aad.len() - len_to_copy;

        if ctx.aad_buffer_len < C::BLOCK_SIZE {
            // The buffer isn't full and this is the last buffer, so process it as is (already padded).
            if last_aad_block {
                Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &ctx.aad_buffer).await;
                assert_eq!(T::regs().sr().read().ifem(), true);

                // Switch to payload phase.
                ctx.aad_complete = true;
                T::regs().cr().modify(|w| w.set_crypen(false));
                T::regs().cr().modify(|w| w.set_gcm_ccmph(2));
                T::regs().cr().modify(|w| w.fflush());
            } else {
                // Just return because we don't yet have a full block to process.
                return;
            }
        } else {
            // Load the full block from the buffer.
            Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &ctx.aad_buffer).await;
            assert_eq!(T::regs().sr().read().ifem(), true);
        }

        // Handle a partial block that is passed in.
        ctx.aad_buffer_len = 0;
        let leftovers = aad_len_remaining % C::BLOCK_SIZE;
        ctx.aad_buffer[..leftovers].copy_from_slice(&aad[aad.len() - leftovers..aad.len()]);
        ctx.aad_buffer_len += leftovers;
        ctx.aad_buffer[ctx.aad_buffer_len..].fill(0);
        aad_len_remaining -= leftovers;
        assert_eq!(aad_len_remaining % C::BLOCK_SIZE, 0);

        // Load full data blocks into core.
        let num_full_blocks = aad_len_remaining / C::BLOCK_SIZE;
        let start_index = len_to_copy;
        let end_index = start_index + (C::BLOCK_SIZE * num_full_blocks);
        Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &aad[start_index..end_index]).await;

        if last_aad_block {
            if leftovers > 0 {
                Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &ctx.aad_buffer).await;
                assert_eq!(T::regs().sr().read().ifem(), true);
            }
            // Switch to payload phase.
            ctx.aad_complete = true;
            T::regs().cr().modify(|w| w.set_crypen(false));
            T::regs().cr().modify(|w| w.set_gcm_ccmph(2));
            T::regs().cr().modify(|w| w.fflush());
        }

        self.store_context(ctx);
    }

    /// Performs encryption/decryption on the provided context.
    /// The context determines algorithm, mode, and state of the crypto accelerator.
    /// When the last piece of data is supplied, `last_block` should be `true`.
    /// This function panics under various mismatches of parameters.
    /// Output buffer must be at least as long as the input buffer.
    /// Data must be a multiple of block size (128-bits for AES, 64-bits for DES) for CBC and ECB modes.
    /// Padding or ciphertext stealing must be managed by the application for these modes.
    /// Data must also be a multiple of block size unless `last_block` is `true`.
    pub fn payload_blocking<'c, C: Cipher<'c> + CipherSized + IVSized>(
        &self,
        ctx: &mut Context<'c, C>,
        input: &[u8],
        output: &mut [u8],
        last_block: bool,
    ) {
        self.load_context(ctx);

        let last_block_remainder = input.len() % C::BLOCK_SIZE;

        // Perform checks for correctness.
        if !ctx.aad_complete && ctx.header_len > 0 {
            panic!("Additional associated data must be processed first!");
        } else if !ctx.aad_complete {
            #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
            {
                ctx.aad_complete = true;
                T::regs().cr().modify(|w| w.set_crypen(false));
                T::regs().cr().modify(|w| w.set_gcm_ccmph(2));
                T::regs().cr().modify(|w| w.fflush());
                T::regs().cr().modify(|w| w.set_crypen(true));
            }
        }
        if ctx.last_block_processed {
            panic!("The last block has already been processed!");
        }
        if input.len() > output.len() {
            panic!("Output buffer length must match input length.");
        }
        if !last_block {
            if last_block_remainder != 0 {
                panic!("Input length must be a multiple of {} bytes.", C::BLOCK_SIZE);
            }
        }
        if C::REQUIRES_PADDING {
            if last_block_remainder != 0 {
                panic!("Input must be a multiple of {} bytes in ECB and CBC modes. Consider padding or ciphertext stealing.", C::BLOCK_SIZE);
            }
        }
        if last_block {
            ctx.last_block_processed = true;
        }

        // Load data into core, block by block.
        let num_full_blocks = input.len() / C::BLOCK_SIZE;
        for block in 0..num_full_blocks {
            let index = block * C::BLOCK_SIZE;
            // Write block in
            self.write_bytes_blocking(C::BLOCK_SIZE, &input[index..index + C::BLOCK_SIZE]);
            // Read block out
            self.read_bytes_blocking(C::BLOCK_SIZE, &mut output[index..index + C::BLOCK_SIZE]);
        }

        // Handle the final block, which is incomplete.
        if last_block_remainder > 0 {
            let padding_len = C::BLOCK_SIZE - last_block_remainder;
            let temp1 = ctx.cipher.pre_final(T::regs(), ctx.dir, padding_len);

            let mut intermediate_data: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE];
            let mut last_block: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE];
            last_block[..last_block_remainder].copy_from_slice(&input[input.len() - last_block_remainder..input.len()]);
            self.write_bytes_blocking(C::BLOCK_SIZE, &last_block);
            self.read_bytes_blocking(C::BLOCK_SIZE, &mut intermediate_data);

            // Handle the last block depending on mode.
            let output_len = output.len();
            output[output_len - last_block_remainder..output_len]
                .copy_from_slice(&intermediate_data[0..last_block_remainder]);

            let mut mask: [u8; 16] = [0; 16];
            mask[..last_block_remainder].fill(0xFF);
            ctx.cipher
                .post_final_blocking(T::regs(), self, ctx.dir, &mut intermediate_data, temp1, mask);
        }

        ctx.payload_len += input.len() as u64;

        self.store_context(ctx);
    }

    /// Performs encryption/decryption on the provided context.
    /// The context determines algorithm, mode, and state of the crypto accelerator.
    /// When the last piece of data is supplied, `last_block` should be `true`.
    /// This function panics under various mismatches of parameters.
    /// Output buffer must be at least as long as the input buffer.
    /// Data must be a multiple of block size (128-bits for AES, 64-bits for DES) for CBC and ECB modes.
    /// Padding or ciphertext stealing must be managed by the application for these modes.
    /// Data must also be a multiple of block size unless `last_block` is `true`.
    pub async fn payload<'c, C: Cipher<'c> + CipherSized + IVSized>(
        &mut self,
        ctx: &mut Context<'c, C>,
        input: &[u8],
        output: &mut [u8],
        last_block: bool,
    ) where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
        self.load_context(ctx);

        let last_block_remainder = input.len() % C::BLOCK_SIZE;

        // Perform checks for correctness.
        if !ctx.aad_complete && ctx.header_len > 0 {
            panic!("Additional associated data must be processed first!");
        } else if !ctx.aad_complete {
            #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
            {
                ctx.aad_complete = true;
                T::regs().cr().modify(|w| w.set_crypen(false));
                T::regs().cr().modify(|w| w.set_gcm_ccmph(2));
                T::regs().cr().modify(|w| w.fflush());
                T::regs().cr().modify(|w| w.set_crypen(true));
            }
        }
        if ctx.last_block_processed {
            panic!("The last block has already been processed!");
        }
        if input.len() > output.len() {
            panic!("Output buffer length must match input length.");
        }
        if !last_block {
            if last_block_remainder != 0 {
                panic!("Input length must be a multiple of {} bytes.", C::BLOCK_SIZE);
            }
        }
        if C::REQUIRES_PADDING {
            if last_block_remainder != 0 {
                panic!("Input must be a multiple of {} bytes in ECB and CBC modes. Consider padding or ciphertext stealing.", C::BLOCK_SIZE);
            }
        }
        if last_block {
            ctx.last_block_processed = true;
        }

        // Load data into core, block by block.
        let num_full_blocks = input.len() / C::BLOCK_SIZE;
        for block in 0..num_full_blocks {
            let index = block * C::BLOCK_SIZE;
            // Read block out
            let read = Self::read_bytes(
                &mut self.outdma,
                C::BLOCK_SIZE,
                &mut output[index..index + C::BLOCK_SIZE],
            );
            // Write block in
            let write = Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &input[index..index + C::BLOCK_SIZE]);
            embassy_futures::join::join(read, write).await;
        }

        // Handle the final block, which is incomplete.
        if last_block_remainder > 0 {
            let padding_len = C::BLOCK_SIZE - last_block_remainder;
            let temp1 = ctx.cipher.pre_final(T::regs(), ctx.dir, padding_len);

            let mut intermediate_data: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE];
            let mut last_block: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE];
            last_block[..last_block_remainder].copy_from_slice(&input[input.len() - last_block_remainder..input.len()]);
            let read = Self::read_bytes(&mut self.outdma, C::BLOCK_SIZE, &mut intermediate_data);
            let write = Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &last_block);
            embassy_futures::join::join(read, write).await;

            // Handle the last block depending on mode.
            let output_len = output.len();
            output[output_len - last_block_remainder..output_len]
                .copy_from_slice(&intermediate_data[0..last_block_remainder]);

            let mut mask: [u8; 16] = [0; 16];
            mask[..last_block_remainder].fill(0xFF);
            ctx.cipher
                .post_final(T::regs(), self, ctx.dir, &mut intermediate_data, temp1, mask)
                .await;
        }

        ctx.payload_len += input.len() as u64;

        self.store_context(ctx);
    }

    #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
    /// Generates an authentication tag for authenticated ciphers including GCM, CCM, and GMAC.
    /// Called after the all data has been encrypted/decrypted by `payload`.
    pub fn finish_blocking<
        'c,
        const TAG_SIZE: usize,
        C: Cipher<'c> + CipherSized + IVSized + CipherAuthenticated<TAG_SIZE>,
    >(
        &self,
        mut ctx: Context<'c, C>,
    ) -> [u8; TAG_SIZE] {
        self.load_context(&mut ctx);

        T::regs().cr().modify(|w| w.set_crypen(false));
        T::regs().cr().modify(|w| w.set_gcm_ccmph(3));
        T::regs().cr().modify(|w| w.set_crypen(true));

        let headerlen1: u32 = ((ctx.header_len * 8) >> 32) as u32;
        let headerlen2: u32 = (ctx.header_len * 8) as u32;
        let payloadlen1: u32 = ((ctx.payload_len * 8) >> 32) as u32;
        let payloadlen2: u32 = (ctx.payload_len * 8) as u32;

        #[cfg(cryp_v2)]
        let footer: [u32; 4] = [
            headerlen1.swap_bytes(),
            headerlen2.swap_bytes(),
            payloadlen1.swap_bytes(),
            payloadlen2.swap_bytes(),
        ];
        #[cfg(any(cryp_v3, cryp_v4))]
        let footer: [u32; 4] = [headerlen1, headerlen2, payloadlen1, payloadlen2];

        self.write_words_blocking(C::BLOCK_SIZE, &footer);

        while !T::regs().sr().read().ofne() {}

        let mut full_tag: [u8; 16] = [0; 16];
        self.read_bytes_blocking(C::BLOCK_SIZE, &mut full_tag);
        let mut tag: [u8; TAG_SIZE] = [0; TAG_SIZE];
        tag.copy_from_slice(&full_tag[0..TAG_SIZE]);

        T::regs().cr().modify(|w| w.set_crypen(false));

        tag
    }

    #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
    // Generates an authentication tag for authenticated ciphers including GCM, CCM, and GMAC.
    /// Called after the all data has been encrypted/decrypted by `payload`.
    pub async fn finish<
        'c,
        const TAG_SIZE: usize,
        C: Cipher<'c> + CipherSized + IVSized + CipherAuthenticated<TAG_SIZE>,
    >(
        &mut self,
        mut ctx: Context<'c, C>,
    ) -> [u8; TAG_SIZE]
    where
        DmaIn: crate::cryp::DmaIn<T>,
        DmaOut: crate::cryp::DmaOut<T>,
    {
        self.load_context(&mut ctx);

        T::regs().cr().modify(|w| w.set_crypen(false));
        T::regs().cr().modify(|w| w.set_gcm_ccmph(3));
        T::regs().cr().modify(|w| w.set_crypen(true));

        let headerlen1: u32 = ((ctx.header_len * 8) >> 32) as u32;
        let headerlen2: u32 = (ctx.header_len * 8) as u32;
        let payloadlen1: u32 = ((ctx.payload_len * 8) >> 32) as u32;
        let payloadlen2: u32 = (ctx.payload_len * 8) as u32;

        #[cfg(cryp_v2)]
        let footer: [u32; 4] = [
            headerlen1.swap_bytes(),
            headerlen2.swap_bytes(),
            payloadlen1.swap_bytes(),
            payloadlen2.swap_bytes(),
        ];
        #[cfg(any(cryp_v3, cryp_v4))]
        let footer: [u32; 4] = [headerlen1, headerlen2, payloadlen1, payloadlen2];

        let write = Self::write_words(&mut self.indma, C::BLOCK_SIZE, &footer);

        let mut full_tag: [u8; 16] = [0; 16];
        let read = Self::read_bytes(&mut self.outdma, C::BLOCK_SIZE, &mut full_tag);

        embassy_futures::join::join(read, write).await;

        let mut tag: [u8; TAG_SIZE] = [0; TAG_SIZE];
        tag.copy_from_slice(&full_tag[0..TAG_SIZE]);

        T::regs().cr().modify(|w| w.set_crypen(false));

        tag
    }

    fn load_key(&self, key: &[u8]) {
        // Load the key into the registers.
        let mut keyidx = 0;
        let mut keyword: [u8; 4] = [0; 4];
        let keylen = key.len() * 8;
        if keylen > 192 {
            keyword.copy_from_slice(&key[keyidx..keyidx + 4]);
            keyidx += 4;
            T::regs().key(0).klr().write_value(u32::from_be_bytes(keyword));
            keyword.copy_from_slice(&key[keyidx..keyidx + 4]);
            keyidx += 4;
            T::regs().key(0).krr().write_value(u32::from_be_bytes(keyword));
        }
        if keylen > 128 {
            keyword.copy_from_slice(&key[keyidx..keyidx + 4]);
            keyidx += 4;
            T::regs().key(1).klr().write_value(u32::from_be_bytes(keyword));
            keyword.copy_from_slice(&key[keyidx..keyidx + 4]);
            keyidx += 4;
            T::regs().key(1).krr().write_value(u32::from_be_bytes(keyword));
        }
        if keylen > 64 {
            keyword.copy_from_slice(&key[keyidx..keyidx + 4]);
            keyidx += 4;
            T::regs().key(2).klr().write_value(u32::from_be_bytes(keyword));
            keyword.copy_from_slice(&key[keyidx..keyidx + 4]);
            keyidx += 4;
            T::regs().key(2).krr().write_value(u32::from_be_bytes(keyword));
        }
        keyword.copy_from_slice(&key[keyidx..keyidx + 4]);
        keyidx += 4;
        T::regs().key(3).klr().write_value(u32::from_be_bytes(keyword));
        keyword = [0; 4];
        keyword[0..key.len() - keyidx].copy_from_slice(&key[keyidx..key.len()]);
        T::regs().key(3).krr().write_value(u32::from_be_bytes(keyword));
    }

    fn store_context<'c, C: Cipher<'c> + CipherSized>(&self, ctx: &mut Context<'c, C>) {
        // Wait for data block processing to finish.
        while !T::regs().sr().read().ifem() {}
        while T::regs().sr().read().ofne() {}
        while T::regs().sr().read().busy() {}

        // Disable crypto processor.
        T::regs().cr().modify(|w| w.set_crypen(false));

        // Save the peripheral state.
        ctx.cr = T::regs().cr().read().0;
        ctx.iv[0] = T::regs().init(0).ivlr().read();
        ctx.iv[1] = T::regs().init(0).ivrr().read();
        ctx.iv[2] = T::regs().init(1).ivlr().read();
        ctx.iv[3] = T::regs().init(1).ivrr().read();

        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        for i in 0..8 {
            ctx.csgcmccm[i] = T::regs().csgcmccmr(i).read();
            ctx.csgcm[i] = T::regs().csgcmr(i).read();
        }
    }

    fn load_context<'c, C: Cipher<'c> + CipherSized>(&self, ctx: &Context<'c, C>) {
        // Reload state registers.
        T::regs().cr().write(|w| w.0 = ctx.cr);
        T::regs().init(0).ivlr().write_value(ctx.iv[0]);
        T::regs().init(0).ivrr().write_value(ctx.iv[1]);
        T::regs().init(1).ivlr().write_value(ctx.iv[2]);
        T::regs().init(1).ivrr().write_value(ctx.iv[3]);

        #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
        for i in 0..8 {
            T::regs().csgcmccmr(i).write_value(ctx.csgcmccm[i]);
            T::regs().csgcmr(i).write_value(ctx.csgcm[i]);
        }
        self.load_key(ctx.cipher.key());

        // Prepare key if applicable.
        ctx.cipher.prepare_key(T::regs());
        T::regs().cr().write(|w| w.0 = ctx.cr);

        // Enable crypto processor.
        T::regs().cr().modify(|w| w.set_crypen(true));
    }

    fn write_bytes_blocking(&self, block_size: usize, blocks: &[u8]) {
        // Ensure input is a multiple of block size.
        assert_eq!(blocks.len() % block_size, 0);
        let mut index = 0;
        let end_index = blocks.len();
        while index < end_index {
            let mut in_word: [u8; 4] = [0; 4];
            in_word.copy_from_slice(&blocks[index..index + 4]);
            T::regs().din().write_value(u32::from_ne_bytes(in_word));
            index += 4;
            if index % block_size == 0 {
                // Block until input FIFO is empty.
                while !T::regs().sr().read().ifem() {}
            }
        }
    }

    async fn write_bytes(dma: &mut PeripheralRef<'_, DmaIn>, block_size: usize, blocks: &[u8])
    where
        DmaIn: crate::cryp::DmaIn<T>,
    {
        if blocks.len() == 0 {
            return;
        }
        // Ensure input is a multiple of block size.
        assert_eq!(blocks.len() % block_size, 0);
        // Configure DMA to transfer input to crypto core.
        let dma_request = dma.request();
        let dst_ptr = T::regs().din().as_ptr();
        let num_words = blocks.len() / 4;
        let src_ptr = ptr::slice_from_raw_parts(blocks.as_ptr().cast(), num_words);
        let options = TransferOptions {
            #[cfg(not(gpdma))]
            priority: crate::dma::Priority::High,
            ..Default::default()
        };
        let dma_transfer = unsafe { Transfer::new_write_raw(dma, dma_request, src_ptr, dst_ptr, options) };
        T::regs().dmacr().modify(|w| w.set_dien(true));
        // Wait for the transfer to complete.
        dma_transfer.await;
    }

    #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
    fn write_words_blocking(&self, block_size: usize, blocks: &[u32]) {
        assert_eq!((blocks.len() * 4) % block_size, 0);
        let mut byte_counter: usize = 0;
        for word in blocks {
            T::regs().din().write_value(*word);
            byte_counter += 4;
            if byte_counter % block_size == 0 {
                // Block until input FIFO is empty.
                while !T::regs().sr().read().ifem() {}
            }
        }
    }

    #[cfg(any(cryp_v2, cryp_v3, cryp_v4))]
    async fn write_words(dma: &mut PeripheralRef<'_, DmaIn>, block_size: usize, blocks: &[u32])
    where
        DmaIn: crate::cryp::DmaIn<T>,
    {
        if blocks.len() == 0 {
            return;
        }
        // Ensure input is a multiple of block size.
        assert_eq!((blocks.len() * 4) % block_size, 0);
        // Configure DMA to transfer input to crypto core.
        let dma_request = dma.request();
        let dst_ptr = T::regs().din().as_ptr();
        let num_words = blocks.len();
        let src_ptr = ptr::slice_from_raw_parts(blocks.as_ptr().cast(), num_words);
        let options = TransferOptions {
            #[cfg(not(gpdma))]
            priority: crate::dma::Priority::High,
            ..Default::default()
        };
        let dma_transfer = unsafe { Transfer::new_write_raw(dma, dma_request, src_ptr, dst_ptr, options) };
        T::regs().dmacr().modify(|w| w.set_dien(true));
        // Wait for the transfer to complete.
        dma_transfer.await;
    }

    fn read_bytes_blocking(&self, block_size: usize, blocks: &mut [u8]) {
        // Block until there is output to read.
        while !T::regs().sr().read().ofne() {}
        // Ensure input is a multiple of block size.
        assert_eq!(blocks.len() % block_size, 0);
        // Read block out
        let mut index = 0;
        let end_index = blocks.len();
        while index < end_index {
            let out_word: u32 = T::regs().dout().read();
            blocks[index..index + 4].copy_from_slice(u32::to_ne_bytes(out_word).as_slice());
            index += 4;
        }
    }

    async fn read_bytes(dma: &mut PeripheralRef<'_, DmaOut>, block_size: usize, blocks: &mut [u8])
    where
        DmaOut: crate::cryp::DmaOut<T>,
    {
        if blocks.len() == 0 {
            return;
        }
        // Ensure input is a multiple of block size.
        assert_eq!(blocks.len() % block_size, 0);
        // Configure DMA to get output from crypto core.
        let dma_request = dma.request();
        let src_ptr = T::regs().dout().as_ptr();
        let num_words = blocks.len() / 4;
        let dst_ptr = ptr::slice_from_raw_parts_mut(blocks.as_mut_ptr().cast(), num_words);
        let options = TransferOptions {
            #[cfg(not(gpdma))]
            priority: crate::dma::Priority::VeryHigh,
            ..Default::default()
        };
        let dma_transfer = unsafe { Transfer::new_read_raw(dma, dma_request, src_ptr, dst_ptr, options) };
        T::regs().dmacr().modify(|w| w.set_doen(true));
        // Wait for the transfer to complete.
        dma_transfer.await;
    }
}

trait SealedInstance {
    fn regs() -> pac::cryp::Cryp;
}

/// CRYP instance trait.
#[allow(private_bounds)]
pub trait Instance: SealedInstance + Peripheral<P = Self> + crate::rcc::RccPeripheral + 'static + Send {
    /// Interrupt for this CRYP instance.
    type Interrupt: interrupt::typelevel::Interrupt;
}

foreach_interrupt!(
    ($inst:ident, cryp, CRYP, GLOBAL, $irq:ident) => {
        impl Instance for peripherals::$inst {
            type Interrupt = crate::interrupt::typelevel::$irq;
        }

        impl SealedInstance for peripherals::$inst {
            fn regs() -> crate::pac::cryp::Cryp {
                crate::pac::$inst
            }
        }
    };
);

dma_trait!(DmaIn, Instance);
dma_trait!(DmaOut, Instance);