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
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
/// AES
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_ecb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
///println!("data:{:?}",&data);
///println!("enc_data:{:?}",&enc_data);
///println!("dec_data:{:?}",&dec_data);
/// ```
#[allow(warnings)]
#[cfg(feature = "crypto")]
pub mod crypto {
/// AES
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_ecb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
///println!("data:{:?}",&data);
///println!("enc_data:{:?}",&enc_data);
///println!("dec_data:{:?}",&dec_data);
/// ```
///
pub mod aes {
pub use aes_siv::*;
pub use ::aes::*;
pub use xts_mode::*;
pub use block_modes::*;
pub use aes_gcm::*;
pub use ctr::*;
pub mod aes_128 {
/// AES SIV Encrypt (AES-128)
/// key: 必须是 32 字节
/// nonce: 16 字节 (必需参数)
/// aad: 关联数据
/// data: 明文
pub fn aes_siv_encrypt(
key: &[u8],
nonce: &[u8],
aad: &[u8],
data: &[u8],
) -> Result<Vec<u8>, String> {
use aes_siv::aead::generic_array::GenericArray;
use aes_siv::aead::{Aead, KeyInit, Payload};
use aes_siv::Aes128SivAead;
if key.len() != 32 {
return Err("SIV AES-128 requires a 32-byte key".to_string());
}
if nonce.len() != 16 {
return Err(format!(
"SIV AES-128 requires a 16-byte nonce, got {}",
nonce.len()
));
}
let cipher = Aes128SivAead::new_from_slice(key)
.map_err(|e| format!("Failed to create SIV cipher: {}", e))?;
let nonce_array = GenericArray::from_slice(nonce);
let payload = Payload {
msg: data,
aad: aad,
};
cipher
.encrypt(nonce_array, payload)
.map_err(|e| format!("SIV encryption failed: {}", e))
}
/// AES SIV Decrypt (AES-128)
pub fn aes_siv_decrypt(
key: &[u8],
nonce: &[u8],
aad: &[u8],
ciphertext_with_siv: &[u8],
) -> Result<Vec<u8>, String> {
use aes_siv::aead::generic_array::GenericArray;
use aes_siv::aead::{Aead, KeyInit, Payload};
use aes_siv::Aes128SivAead;
if key.len() != 32 {
return Err("SIV AES-128 requires a 32-byte key".to_string());
}
if nonce.len() != 16 {
return Err(format!(
"SIV AES-128 requires a 16-byte nonce, got {}",
nonce.len()
));
}
let cipher = Aes128SivAead::new_from_slice(key)
.map_err(|e| format!("Failed to create SIV cipher: {}", e))?;
let nonce_array = GenericArray::from_slice(nonce);
let payload = Payload {
msg: ciphertext_with_siv,
aad: aad,
};
cipher
.decrypt(nonce_array, payload)
.map_err(|_| "SIV authentication failed".to_string())
}
/// AES XTS Encrypt (AES-128)
///
/// key: 必须是 32 字节 (两个 16 字节的 AES-128 密钥拼接)
/// tweak: 16 字节 (通常代表磁盘扇区号)
/// data: 必须大于等于 16 字节
pub fn aes_xts_encrypt(
key: &[u8],
tweak: &[u8],
data: &[u8],
) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::generic_array::GenericArray;
use aes::Aes128;
use aes::NewBlockCipher;
use xts_mode::Xts128;
if key.len() != 32 {
return Err(format!(
"XTS AES-128 requires a 32-byte key, got {}",
key.len()
));
}
if tweak.len() != 16 {
return Err(format!("Tweak must be 16 bytes, got {}", tweak.len()));
}
if data.len() < 16 {
return Err(format!(
"Data must be at least 16 bytes for XTS, got {}",
data.len()
));
}
// 分别初始化两个密钥,每个16字节
let cipher_1 = Aes128::new(GenericArray::<u8, U16>::from_slice(&key[..16]));
let cipher_2 = Aes128::new(GenericArray::<u8, U16>::from_slice(&key[16..]));
// 组合成 XTS 模式
let xts = Xts128::<Aes128>::new(cipher_1, cipher_2);
let mut buffer = data.to_vec();
let mut tweak_arr: [u8; 16] = [0u8; 16];
tweak_arr.copy_from_slice(tweak);
xts.encrypt_sector(&mut buffer, tweak_arr);
Ok(buffer)
}
/// AES XTS Decrypt (AES-128)
///
/// key: 必须是 32 字节 (两个 16 字节的 AES-128 密钥拼接)
/// tweak: 16 字节 (通常代表磁盘扇区号)
/// data: 必须大于等于 16 字节
pub fn aes_xts_decrypt(
key: &[u8],
tweak: &[u8],
data: &[u8],
) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::generic_array::GenericArray;
use aes::Aes128;
use aes::NewBlockCipher;
use xts_mode::Xts128;
if key.len() != 32 {
return Err(format!(
"XTS AES-128 requires a 32-byte key, got {}",
key.len()
));
}
if tweak.len() != 16 {
return Err(format!("Tweak must be 16 bytes, got {}", tweak.len()));
}
if data.len() < 16 {
return Err(format!(
"Data must be at least 16 bytes for XTS, got {}",
data.len()
));
}
// 分别初始化两个密钥,每个16字节
let cipher_1 = Aes128::new(GenericArray::<u8, U16>::from_slice(&key[..16]));
let cipher_2 = Aes128::new(GenericArray::<u8, U16>::from_slice(&key[16..]));
// 组合成 XTS 模式
let xts = Xts128::<Aes128>::new(cipher_1, cipher_2);
let mut buffer = data.to_vec();
let mut tweak_arr: [u8; 16] = [0u8; 16];
tweak_arr.copy_from_slice(tweak);
xts.decrypt_sector(&mut buffer, tweak_arr);
Ok(buffer)
}
/// AES PCBC Encrypt (AES-128)
/// key: 16 bytes, iv: 16 bytes
pub fn aes_pcbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::generic_array::typenum::U32;
use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
use aes::Aes128;
if key.len() != 16 {
return Err(format!(
"Invalid key length: expected 16 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid iv length: expected 16 bytes, got {}",
iv.len()
));
}
if data.is_empty() {
return Err("Data cannot be empty".to_string());
}
use aes::NewBlockCipher;
let cipher = Aes128::new(GenericArray::<u8, U16>::from_slice(key));
let mut padded_data = data.to_vec();
// 手动添加 PKCS7 填充
let pad_len = 16 - (padded_data.len() % 16);
padded_data.extend(vec![pad_len as u8; pad_len]);
let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
let mut ciphertext = Vec::with_capacity(padded_data.len());
for chunk in padded_data.chunks(16) {
let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
// PCBC 核心逻辑: 异或前一个密文块 AND 前一个明文块
for i in 0..16 {
block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
}
cipher.encrypt_block(&mut block);
prev_plaintext.copy_from_slice(chunk);
prev_ciphertext.copy_from_slice(&block);
ciphertext.extend_from_slice(&block);
}
Ok(ciphertext)
}
/// AES PCBC Decrypt (AES-128)
/// key: 16 bytes, iv: 16 bytes
pub fn aes_pcbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::generic_array::typenum::U32;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt};
use aes::Aes128;
use aes::NewBlockCipher;
if key.len() != 16 {
return Err(format!(
"Invalid key length: expected 16 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid iv length: expected 16 bytes, got {}",
iv.len()
));
}
if data.len() % 16 != 0 {
return Err(format!(
"Invalid data length: must be multiple of 16 bytes, got {}",
data.len()
));
}
if data.is_empty() {
return Err("Data cannot be empty".to_string());
}
let cipher = Aes128::new(GenericArray::<u8, U16>::from_slice(key));
let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
let mut plaintext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
cipher.decrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
}
prev_plaintext.copy_from_slice(&block);
prev_ciphertext.copy_from_slice(chunk);
plaintext.extend_from_slice(&block);
}
// 手动移除 PKCS7 填充
if let Some(&pad_byte) = plaintext.last() {
if pad_byte >= 1 && pad_byte <= 16 {
let pad_len = pad_byte as usize;
if plaintext.len() >= pad_len {
let padding = &plaintext[plaintext.len() - pad_len..];
if padding.iter().all(|&b| b == pad_byte) {
plaintext.truncate(plaintext.len() - pad_len);
return Ok(plaintext);
}
}
}
}
Err("Invalid PKCS7 padding".to_string())
}
/// AES ECB Encrypt
///
/// key must be 16 bytes
///
/// iv must be 0 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_ecb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes128;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Ecb};
type Aes128Ecb = Ecb<Aes128, Pkcs7>;
let cipher = Aes128Ecb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create ECB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES ECB Decrypt
///
/// key must be 16 bytes
///
/// iv must be 0 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_128::aes_ecb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_ecb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes128;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Ecb};
type Aes128Ecb = Ecb<Aes128, Pkcs7>;
let cipher = Aes128Ecb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create ECB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES ECB decryption failed: {}", e))
}
/// AES CBC Encrypt
///
/// key must be 16 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_cbc_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_cbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes128;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
// 验证密钥长度(AES-128需要16字节)
if key.len() != 16 {
return Err(format!(
"Invalid key length: expected 16 bytes, got {}",
key.len()
));
}
// 验证IV长度(AES块大小为16字节)
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
type Aes128Cbc = Cbc<Aes128, Pkcs7>;
let cipher = Aes128Cbc::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CBC cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES CBC Decrypt
///
/// key must be 16 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_cbc_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_128::aes_cbc_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes128;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
// 验证密钥长度(AES-128需要16字节)
if key.len() != 16 {
return Err(format!(
"Invalid key length: expected 16 bytes, got {}",
key.len()
));
}
// 验证IV长度(AES块大小为16字节)
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
type Aes128Cbc = Cbc<Aes128, Pkcs7>;
let cipher = Aes128Cbc::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CBC cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES CBC decryption failed: {}", e))
}
/// AES CFB Encrypt
///
/// key must be 16 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_cfb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_cfb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes128;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Cfb};
type Aes128Cfb = Cfb<Aes128, NoPadding>;
// 参数验证
if key.len() != 16 {
return Err(format!(
"Invalid key length: expected 16 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
let cipher = Aes128Cfb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CFB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES CFB Decrypt
///
/// key must be 16 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_cfb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_128::aes_cfb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_cfb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes128;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Cfb};
type Aes128Cfb = Cfb<Aes128, NoPadding>;
// 参数验证
if key.len() != 16 {
return Err(format!(
"Invalid key length: expected 16 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
let cipher = Aes128Cfb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CFB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES CFB decryption failed: {}", e))
}
/// AES OFB Encrypt
///
/// key must be 16 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_ofb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_ofb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes128;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Ofb};
type Aes128Ofb = Ofb<Aes128, NoPadding>;
// 参数验证
if key.len() != 16 {
return Err(format!(
"Invalid key length: expected 16 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
let cipher = Aes128Ofb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create OFB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES OFB Decrypt
///
/// key must be 16 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_ofb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_128::aes_ofb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_ofb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes128;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Ofb};
type Aes128Ofb = Ofb<Aes128, NoPadding>;
// 参数验证
if key.len() != 16 {
return Err(format!(
"Invalid key length: expected 16 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
let cipher = Aes128Ofb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create OFB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES OFB decryption failed: {}", e))
}
/// AES IGE Encrypt
///
/// key must be 16 bytes
///
/// iv must be 32 bytes
///
/// data must be 16*n bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_ige_encrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_ige_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher};
use aes::Aes128;
// 修正:IGE需要32字节IV
if key.len() != 16 {
return Err("Key must be 16 bytes".to_string());
}
if iv.len() != 32 {
// ✅ 修正为32字节
return Err("IV must be 32 bytes".to_string());
}
if data.len() % 16 != 0 {
return Err("Data must be a multiple of 16 bytes".to_string());
}
let cipher = Aes128::new(GenericArray::from_slice(key));
let mut prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[..16]).to_owned();
let mut prev_prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[16..]).to_owned();
let mut ciphertext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block = GenericArray::clone_from_slice(chunk);
// IGE加密:先XOR,再加密,再XOR
for i in 0..16 {
block[i] ^= prev_block[i] ^ prev_prev_block[i];
}
cipher.encrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_block[i];
}
ciphertext.extend_from_slice(&block);
// 更新状态
prev_prev_block.copy_from_slice(&prev_block);
prev_block.copy_from_slice(&block);
}
Ok(ciphertext)
}
/// AES IGE Decrypt
///
/// key must be 16 bytes
///
/// iv must be 32 bytes
///
/// data must be 16*n bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_ige_encrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_128::aes_ige_decrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_ige_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt, NewBlockCipher};
use aes::Aes128;
// 修正:IGE需要32字节IV
if key.len() != 16 {
return Err("Key must be 16 bytes".to_string());
}
if iv.len() != 32 {
// ✅ 修正为32字节
return Err("IV must be 32 bytes".to_string());
}
if data.len() % 16 != 0 {
return Err("Data must be a multiple of 16 bytes".to_string());
}
let cipher = Aes128::new(GenericArray::from_slice(key));
let mut prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[..16]).to_owned();
let mut prev_prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[16..]).to_owned();
let mut plaintext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block = GenericArray::clone_from_slice(chunk);
let original_ciphertext = block.clone(); // ✅ 保存原始密文块
// IGE解密:先XOR,再解密,再XOR
for i in 0..16 {
block[i] ^= prev_block[i];
}
cipher.decrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_block[i] ^ prev_prev_block[i];
}
plaintext.extend_from_slice(&block);
// ✅ 修正:使用原始密文块更新状态
prev_prev_block.copy_from_slice(&prev_block);
prev_block.copy_from_slice(&original_ciphertext);
}
Ok(plaintext)
}
/// AES GCM Encrypt
///
/// key must be 16 bytes for AES-128
///
/// nonce must be 12 bytes (recommended), but other lengths are supported
///
/// data can be any length (no padding required)
///
/// The output ciphertext includes a 16-byte authentication tag appended at the end
///
///
/// ```ignore
/// let data = “this is data”.as_bytes();
/// let key = b"16_bytes_secret!!"; // 16 bytes for AES-128
/// let mut nonce = [0u8; 12]; // 12 bytes recommended
/// // fill nonce with random data
/// let enc_data = doe::crypto::aes::aes_128::aes_gcm_encrypt(key, &nonce, data, &[]).unwrap();
/// let dec_data = doe::crypto::aes::aes_128::aes_gcm_decrypt(key, &nonce, &enc_data, &[]).unwrap();
/// ```
pub fn aes_gcm_encrypt(
key: &[u8],
nonce: &[u8],
msg: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, String> {
use aes_gcm::{
aead::{Aead, KeyInit, Payload},
Aes128Gcm, Nonce,
};
// 只给出警告,不阻止使用
if nonce.len() != 12 {
eprintln!(
"Warning: Nonce length is {} bytes (recommended: 12 bytes)",
nonce.len()
);
}
let cipher =
Aes128Gcm::new_from_slice(key).map_err(|e| format!("Invalid key: {}", e))?;
let nonce = Nonce::from_slice(nonce);
cipher
.encrypt(nonce, Payload { msg, aad })
.map_err(|e| format!("Encryption error: {}", e))
}
/// AES GCM Decrypt
///
/// key must be 16 bytes for AES-128
///
/// nonce must be 12 bytes (recommended), but other lengths are supported
///
/// data can be any length (no padding required)
///
/// The output ciphertext includes a 16-byte authentication tag appended at the end
///
///
/// ```ignore
/// let data = “this is data”.as_bytes();
/// let key = b"16_bytes_secret!!"; // 16 bytes for AES-128
/// let mut nonce = [0u8; 12]; // 12 bytes recommended
/// // fill nonce with random data
/// let enc_data = doe::crypto::aes::aes_128::aes_gcm_encrypt(key, &nonce, data, &[]).unwrap();
/// let dec_data = doe::crypto::aes::aes_128::aes_gcm_decrypt(key, &nonce, &enc_data, &[]).unwrap();
/// ```
pub fn aes_gcm_decrypt(
key: &[u8],
nonce: &[u8],
msg: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, String> {
use aes_gcm::{
aead::{Aead, KeyInit, Payload},
Aes128Gcm, Nonce,
};
// 只给出警告,不阻止使用
if nonce.len() != 12 {
eprintln!(
"Warning: Nonce length is {} bytes (recommended: 12 bytes)",
nonce.len()
);
}
let cipher =
Aes128Gcm::new_from_slice(key).map_err(|e| format!("Invalid key: {}", e))?;
let nonce = Nonce::from_slice(nonce);
cipher
.decrypt(nonce, Payload { msg, aad })
.map_err(|e| format!("Encryption error: {}", e))
}
/// AES 256 CTR Encrypt
///
/// key must be 16 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_ctr_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_ctr_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::NewCipher;
use aes::cipher::StreamCipher;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt};
use aes::Aes128;
use ctr::Ctr128BE;
type Aes128Ctr = Ctr128BE<Aes128>;
if key.len() != 16 {
return Err("Key must be 16 bytes".to_string());
}
if iv.len() != 16 {
return Err("IV must be 16 bytes".to_string());
}
let mut cipher =
Aes128Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
let mut ciphertext = data.to_vec();
cipher.apply_keystream(&mut ciphertext);
Ok(ciphertext)
}
/// AES CTR Decrypt
///
/// key must be 16 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_128::aes_ctr_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_128::aes_ctr_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_ctr_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::NewCipher;
use aes::cipher::StreamCipher;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt};
use aes::Aes128;
use ctr::Ctr128BE;
type Aes128Ctr = Ctr128BE<Aes128>;
if key.len() != 16 {
return Err("Key must be 16 bytes".to_string());
}
if iv.len() != 16 {
return Err("IV must be 16 bytes".to_string());
}
let mut cipher =
Aes128Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
let mut ciphertext = data.to_vec();
cipher.apply_keystream(&mut ciphertext);
Ok(ciphertext)
}
}
pub mod aes_192 {
/// AES XTS Encrypt (AES-192)
///
/// key: 必须是 48 字节 (两个 24 字节的 AES-192 密钥拼接)
/// tweak: 16 字节 (通常代表磁盘扇区号)
/// data: 必须大于等于 16 字节
pub fn aes_xts_encrypt(
key: &[u8],
tweak: &[u8],
data: &[u8],
) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::{U16, U24};
use aes::cipher::generic_array::GenericArray;
use aes::Aes192;
use aes::NewBlockCipher;
use xts_mode::Xts128;
if key.len() != 48 {
return Err(format!(
"XTS AES-192 requires a 48-byte key, got {}",
key.len()
));
}
if tweak.len() != 16 {
return Err(format!("Tweak must be 16 bytes, got {}", tweak.len()));
}
if data.len() < 16 {
return Err(format!(
"Data must be at least 16 bytes for XTS, got {}",
data.len()
));
}
// 分别初始化两个密钥,每个24字节
let cipher_1 = Aes192::new(GenericArray::<u8, U24>::from_slice(&key[..24]));
let cipher_2 = Aes192::new(GenericArray::<u8, U24>::from_slice(&key[24..]));
// 组合成 XTS 模式
let xts = Xts128::<Aes192>::new(cipher_1, cipher_2);
let mut buffer = data.to_vec();
let mut tweak_arr: [u8; 16] = [0u8; 16];
tweak_arr.copy_from_slice(tweak);
xts.encrypt_sector(&mut buffer, tweak_arr);
Ok(buffer)
}
/// AES XTS Decrypt (AES-192)
///
/// key: 必须是 48 字节 (两个 24 字节的 AES-192 密钥拼接)
/// tweak: 16 字节 (通常代表磁盘扇区号)
/// data: 必须大于等于 16 字节
pub fn aes_xts_decrypt(
key: &[u8],
tweak: &[u8],
data: &[u8],
) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::{U16, U24};
use aes::cipher::generic_array::GenericArray;
use aes::Aes192;
use aes::NewBlockCipher;
use xts_mode::Xts128;
if key.len() != 48 {
return Err(format!(
"XTS AES-192 requires a 48-byte key, got {}",
key.len()
));
}
if tweak.len() != 16 {
return Err(format!("Tweak must be 16 bytes, got {}", tweak.len()));
}
if data.len() < 16 {
return Err(format!(
"Data must be at least 16 bytes for XTS, got {}",
data.len()
));
}
// 分别初始化两个密钥,每个24字节
let cipher_1 = Aes192::new(GenericArray::<u8, U24>::from_slice(&key[..24]));
let cipher_2 = Aes192::new(GenericArray::<u8, U24>::from_slice(&key[24..]));
// 组合成 XTS 模式
let xts = Xts128::<Aes192>::new(cipher_1, cipher_2);
let mut buffer = data.to_vec();
let mut tweak_arr: [u8; 16] = [0u8; 16];
tweak_arr.copy_from_slice(tweak);
xts.decrypt_sector(&mut buffer, tweak_arr);
Ok(buffer)
}
/// AES PCBC Encrypt (AES-192)
/// key: 24 bytes, iv: 16 bytes
pub fn aes_pcbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::generic_array::typenum::U24;
use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
use aes::Aes192;
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid iv length: expected 16 bytes, got {}",
iv.len()
));
}
if data.is_empty() {
return Err("Data cannot be empty".to_string());
}
use aes::NewBlockCipher;
let cipher = Aes192::new(GenericArray::<u8, U24>::from_slice(key));
let mut padded_data = data.to_vec();
// 手动添加 PKCS7 填充
let pad_len = 16 - (padded_data.len() % 16);
padded_data.extend(vec![pad_len as u8; pad_len]);
let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
let mut ciphertext = Vec::with_capacity(padded_data.len());
for chunk in padded_data.chunks(16) {
let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
// PCBC 核心逻辑: 异或前一个密文块 AND 前一个明文块
for i in 0..16 {
block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
}
cipher.encrypt_block(&mut block);
prev_plaintext.copy_from_slice(chunk);
prev_ciphertext.copy_from_slice(&block);
ciphertext.extend_from_slice(&block);
}
Ok(ciphertext)
}
/// AES PCBC Decrypt (AES-192)
/// key: 24 bytes, iv: 16 bytes
pub fn aes_pcbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::generic_array::typenum::U24;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt};
use aes::Aes192;
use aes::NewBlockCipher;
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid iv length: expected 16 bytes, got {}",
iv.len()
));
}
if data.len() % 16 != 0 {
return Err(format!(
"Invalid data length: must be multiple of 16 bytes, got {}",
data.len()
));
}
if data.is_empty() {
return Err("Data cannot be empty".to_string());
}
let cipher = Aes192::new(GenericArray::<u8, U24>::from_slice(key));
let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
let mut plaintext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
cipher.decrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
}
prev_plaintext.copy_from_slice(&block);
prev_ciphertext.copy_from_slice(chunk);
plaintext.extend_from_slice(&block);
}
// 手动移除 PKCS7 填充
if let Some(&pad_byte) = plaintext.last() {
if pad_byte >= 1 && pad_byte <= 16 {
let pad_len = pad_byte as usize;
if plaintext.len() >= pad_len {
let padding = &plaintext[plaintext.len() - pad_len..];
if padding.iter().all(|&b| b == pad_byte) {
plaintext.truncate(plaintext.len() - pad_len);
return Ok(plaintext);
}
}
}
}
Err("Invalid PKCS7 padding".to_string())
}
/// AES ECB Encrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 0 bytes (ECB does not use an IV)
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_ecb_encrypt(key, b"", data).unwrap();
/// ```
pub fn aes_ecb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes192;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Ecb};
// Validate key length for AES-192 (24 bytes)
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
// ECB does not use an IV; require empty slice to avoid confusion
if !iv.is_empty() {
return Err("ECB mode does not use an IV; expected empty slice".to_string());
}
type Aes192Ecb = Ecb<Aes192, Pkcs7>;
// Pass an empty IV slice explicitly
let cipher = Aes192Ecb::new_from_slices(key, Default::default())
.map_err(|e| format!("Failed to create ECB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES ECB Decrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 0 bytes (ECB does not use an IV)
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_ecb_encrypt(key, b"", data).unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_ecb_decrypt(key, b"", &enc_data).unwrap();
/// ```
pub fn aes_ecb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes192;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Ecb};
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if !iv.is_empty() {
return Err("ECB mode does not use an IV; expected empty slice".to_string());
}
type Aes192Ecb = Ecb<Aes192, Pkcs7>;
let cipher = Aes192Ecb::new_from_slices(key, Default::default())
.map_err(|e| format!("Failed to create ECB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES ECB decryption failed: {}", e))
}
/// AES CBC Encrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 16 bytes
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"1234567812345678"; // 16 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_cbc_encrypt(key, iv, data).unwrap();
/// ```
pub fn aes_cbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes192;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
type Aes192Cbc = Cbc<Aes192, Pkcs7>;
let cipher = Aes192Cbc::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CBC cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES CBC Decrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 16 bytes
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"1234567812345678"; // 16 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_cbc_encrypt(key, iv, data).unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_cbc_decrypt(key, iv, &enc_data).unwrap();
/// ```
pub fn aes_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes192;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
type Aes192Cbc = Cbc<Aes192, Pkcs7>;
let cipher = Aes192Cbc::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CBC cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES CBC decryption failed: {}", e))
}
/// AES CFB Encrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 16 bytes
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"1234567812345678"; // 16 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_cfb_encrypt(key, iv, data).unwrap();
/// ```
pub fn aes_cfb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes192;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Cfb};
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
type Aes192Cfb = Cfb<Aes192, NoPadding>;
let cipher = Aes192Cfb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CFB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES CFB Decrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 16 bytes
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"1234567812345678"; // 16 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_cfb_encrypt(key, iv, data).unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_cfb_decrypt(key, iv, &enc_data).unwrap();
/// ```
pub fn aes_cfb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes192;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Cfb};
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
type Aes192Cfb = Cfb<Aes192, NoPadding>;
let cipher = Aes192Cfb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CFB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES CFB decryption failed: {}", e))
}
/// AES OFB Encrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 16 bytes
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"1234567812345678"; // 16 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_ofb_encrypt(key, iv, data).unwrap();
/// ```
pub fn aes_ofb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes192;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Ofb};
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
type Aes192Ofb = Ofb<Aes192, NoPadding>;
let cipher = Aes192Ofb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create OFB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES OFB Decrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 16 bytes
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"1234567812345678"; // 16 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_ofb_encrypt(key, iv, data).unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_ofb_decrypt(key, iv, &enc_data).unwrap();
/// ```
pub fn aes_ofb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes192;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Ofb};
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
type Aes192Ofb = Ofb<Aes192, NoPadding>;
let cipher = Aes192Ofb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create OFB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES OFB decryption failed: {}", e))
}
/// AES IGE Encrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 32 bytes (two AES blocks: one for previous ciphertext, one for previous plaintext)
///
/// data length must be a multiple of 16 bytes (no padding is performed)
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"12345678123456781234567812345678"; // 32 bytes
/// let data = b"this is data!!!"; // exactly 16 bytes
/// let enc_data = doe::crypto::aes::aes_192::aes_ige_encrypt(key, iv, data).unwrap();
/// ```
pub fn aes_ige_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher};
use aes::Aes192;
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 32 {
return Err(format!(
"Invalid IV length: expected 32 bytes, got {}",
iv.len()
));
}
if data.len() % 16 != 0 {
return Err("Data length must be a multiple of 16 bytes".to_string());
}
let cipher = Aes192::new(GenericArray::from_slice(key));
let mut prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[..16]).to_owned();
let mut prev_prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[16..]).to_owned();
let mut ciphertext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block = GenericArray::clone_from_slice(chunk);
// IGE encryption: XOR with prev and prev_prev, then encrypt, then XOR with prev
for i in 0..16 {
block[i] ^= prev_block[i] ^ prev_prev_block[i];
}
cipher.encrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_block[i];
}
ciphertext.extend_from_slice(&block);
// Update state: shift previous blocks
prev_prev_block.copy_from_slice(&prev_block);
prev_block.copy_from_slice(&block);
}
Ok(ciphertext)
}
/// AES IGE Decrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 32 bytes
///
/// data length must be a multiple of 16 bytes
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"12345678123456781234567812345678"; // 32 bytes
/// let data = b"this is data!!!"; // exactly 16 bytes
/// let enc_data = doe::crypto::aes::aes_192::aes_ige_encrypt(key, iv, data).unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_ige_decrypt(key, iv, &enc_data).unwrap();
/// ```
pub fn aes_ige_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt, NewBlockCipher};
use aes::Aes192;
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 32 {
return Err(format!(
"Invalid IV length: expected 32 bytes, got {}",
iv.len()
));
}
if data.len() % 16 != 0 {
return Err("Data length must be a multiple of 16 bytes".to_string());
}
let cipher = Aes192::new(GenericArray::from_slice(key));
let mut prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[..16]).to_owned();
let mut prev_prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[16..]).to_owned();
let mut plaintext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block = GenericArray::clone_from_slice(chunk);
let original_ciphertext = block.clone(); // save for state update
// IGE decryption: XOR with prev, then decrypt, then XOR with prev and prev_prev
for i in 0..16 {
block[i] ^= prev_block[i];
}
cipher.decrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_block[i] ^ prev_prev_block[i];
}
plaintext.extend_from_slice(&block);
// Update state using the original ciphertext block
prev_prev_block.copy_from_slice(&prev_block);
prev_block.copy_from_slice(&original_ciphertext);
}
Ok(plaintext)
}
/// AES GCM Encrypt (AES-192)
///
/// key must be 24 bytes
///
/// nonce should be 12 bytes (recommended), other lengths are supported but may reduce security
///
/// aad (additional authenticated data) can be empty
///
/// Output includes a 16‑byte authentication tag appended to the ciphertext
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let nonce = b"123456781234"; // 12 bytes recommended
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_gcm_encrypt(key, nonce, data, b"").unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_gcm_decrypt(key, nonce, &enc_data, b"").unwrap();
/// ```
///
/// AES GCM Encrypt (AES-192)
///
/// key must be 24 bytes
///
/// nonce should be 12 bytes (recommended), other lengths are supported but may reduce security
///
/// aad (additional authenticated data) can be empty
///
/// Output includes a 16‑byte authentication tag appended to the ciphertext
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let nonce = b"123456781234"; // 12 bytes recommended
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_gcm_encrypt(key, nonce, data, b"").unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_gcm_decrypt(key, nonce, &enc_data, b"").unwrap();
/// let dec_data_str = String::from_utf8_lossy(&dec_data);
/// println!("Decrypted data: {}", dec_data_str);
/// ```
///
pub fn aes_gcm_encrypt(
key: &[u8],
nonce: &[u8],
msg: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, String> {
use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
use aes::Aes192;
// GF(2^128) 不可约多项式
const R: u128 = 0xE1000000000000000000000000000000;
/// GF(2^128) 乘法
fn gf_mul(mut x: u128, mut y: u128) -> u128 {
let mut z = 0u128;
for _ in 0..128 {
if y & 1 == 1 {
z ^= x;
}
let carry = x & 1;
x >>= 1;
if carry != 0 {
x ^= R;
}
y >>= 1;
}
z
}
/// 将 16 字节按大端序转换为 u128
fn bytes_to_u128_be(bytes: &[u8]) -> u128 {
let mut arr = [0u8; 16];
let len = bytes.len().min(16);
arr[..len].copy_from_slice(&bytes[..len]);
u128::from_be_bytes(arr)
}
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes for AES-192, got {}",
key.len()
));
}
use aes::NewBlockCipher;
let cipher = Aes192::new(GenericArray::from_slice(key));
// 1. 计算 H = E_K(0^128)
let mut h_block = [0u8; 16];
cipher.encrypt_block(GenericArray::from_mut_slice(&mut h_block));
let h = bytes_to_u128_be(&h_block);
// 2. 计算初始计数器 J0
let j0: u128 = if nonce.len() == 12 {
// J0 = nonce || 0x00000001
let mut nonce_padded = [0u8; 16];
nonce_padded[..12].copy_from_slice(nonce);
bytes_to_u128_be(&nonce_padded) | 1
} else {
// 对于非12字节nonce,使用GHASH计算
// J0 = GHASH(H, nonce || 0^(s+64) || [len(nonce)]_64)
let s = (16 - (nonce.len() % 16)) % 16;
let padded_len = nonce.len() + s + 8;
let mut padded = vec![0u8; padded_len];
padded[..nonce.len()].copy_from_slice(nonce);
// 最后8字节是nonce的位长度(大端序)
padded[padded_len - 8..]
.copy_from_slice(&(nonce.len() as u64 * 8).to_be_bytes());
let mut state: u128 = 0;
let mut remaining = &padded[..];
while remaining.len() >= 16 {
state ^= bytes_to_u128_be(&remaining[..16]);
state = gf_mul(state, h);
remaining = &remaining[16..];
}
state
};
// 3. 计算标签掩码 E(K, J0)
let mut j0_bytes = j0.to_be_bytes();
cipher.encrypt_block(GenericArray::from_mut_slice(&mut j0_bytes));
let mask = u128::from_be_bytes(j0_bytes);
// 4. GHASH 处理函数
fn ghash_update(mut state: u128, h: u128, data: &[u8]) -> u128 {
let mut remaining = data;
while remaining.len() >= 16 {
state ^= bytes_to_u128_be(&remaining[..16]);
state = gf_mul(state, h);
remaining = &remaining[16..];
}
// 处理最后一个不完整的块(用0填充)
if !remaining.is_empty() {
state ^= bytes_to_u128_be(remaining);
state = gf_mul(state, h);
}
state
}
// 5. GHASH 处理 AAD
let mut ghash_state = ghash_update(0, h, aad);
// 6. CTR 模式加密(从 J0 + 1 开始)
let mut ciphertext = msg.to_vec();
let mut counter = j0.wrapping_add(1);
let mut offset = 0;
while offset < ciphertext.len() {
let mut counter_bytes = counter.to_be_bytes();
cipher.encrypt_block(GenericArray::from_mut_slice(&mut counter_bytes));
let end = (offset + 16).min(ciphertext.len());
for i in offset..end {
ciphertext[i] ^= counter_bytes[i - offset];
}
counter = counter.wrapping_add(1);
offset = end;
}
// 7. GHASH 处理密文
ghash_state = ghash_update(ghash_state, h, &ciphertext);
// 8. 最终 GHASH:加入长度块
// 长度块 = [len(AAD) in bits]_64 || [len(C) in bits]_64
let len_block = ((aad.len() as u128) << 64) | ((ciphertext.len() as u128) << 3);
ghash_state ^= len_block;
ghash_state = gf_mul(ghash_state, h);
// 9. 计算认证标签
let tag = ghash_state ^ mask;
// 10. 拼接密文和标签
ciphertext.extend_from_slice(&tag.to_be_bytes());
Ok(ciphertext)
}
/// AES GCM Decrypt (AES-192)
///
/// key must be 24 bytes
///
/// nonce should be 12 bytes (recommended), other lengths are supported but may reduce security
///
/// aad (additional authenticated data) can be empty
///
/// Input must include the 16‑byte authentication tag appended to the ciphertext
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let nonce = b"123456781234"; // 12 bytes recommended
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_gcm_encrypt(key, nonce, data, b"").unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_gcm_decrypt(key, nonce, &enc_data, b"").unwrap();
/// let dec_data_str = String::from_utf8_lossy(&dec_data);
/// println!("Decrypted data: {}", dec_data_str);
/// ```
///
pub fn aes_gcm_decrypt(
key: &[u8],
nonce: &[u8],
ciphertext_with_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, String> {
use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
use aes::Aes192;
use aes::NewBlockCipher;
// GF(2^128) 不可约多项式
const R: u128 = 0xE1000000000000000000000000000000;
/// GF(2^128) 乘法
fn gf_mul(mut x: u128, mut y: u128) -> u128 {
let mut z = 0u128;
for _ in 0..128 {
if y & 1 == 1 {
z ^= x;
}
let carry = x & 1;
x >>= 1;
if carry != 0 {
x ^= R;
}
y >>= 1;
}
z
}
/// 将 16 字节按大端序转换为 u128
fn bytes_to_u128_be(bytes: &[u8]) -> u128 {
let mut arr = [0u8; 16];
let len = bytes.len().min(16);
arr[..len].copy_from_slice(&bytes[..len]);
u128::from_be_bytes(arr)
}
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes for AES-192, got {}",
key.len()
));
}
// 密文必须至少包含 16 字节的 Tag
if ciphertext_with_tag.len() < 16 {
return Err(
"Invalid input: ciphertext too short, missing authentication tag"
.to_string(),
);
}
// 1. 分离密文和标签
let ciphertext_len = ciphertext_with_tag.len() - 16;
let ciphertext = &ciphertext_with_tag[..ciphertext_len];
let received_tag_bytes = &ciphertext_with_tag[ciphertext_len..];
let received_tag = u128::from_be_bytes(received_tag_bytes.try_into().unwrap());
let cipher = Aes192::new(GenericArray::from_slice(key));
// 2. 计算 H = E_K(0^128)
let mut h_block = [0u8; 16];
cipher.encrypt_block(GenericArray::from_mut_slice(&mut h_block));
let h = bytes_to_u128_be(&h_block);
// 3. 计算初始计数器 J0 (与加密完全一致)
let j0: u128 = if nonce.len() == 12 {
let mut nonce_padded = [0u8; 16];
nonce_padded[..12].copy_from_slice(nonce);
bytes_to_u128_be(&nonce_padded) | 1
} else {
let s = (16 - (nonce.len() % 16)) % 16;
let padded_len = nonce.len() + s + 8;
let mut padded = vec![0u8; padded_len];
padded[..nonce.len()].copy_from_slice(nonce);
padded[padded_len - 8..]
.copy_from_slice(&(nonce.len() as u64 * 8).to_be_bytes());
let mut state: u128 = 0;
let mut remaining = &padded[..];
while remaining.len() >= 16 {
state ^= bytes_to_u128_be(&remaining[..16]);
state = gf_mul(state, h);
remaining = &remaining[16..];
}
state
};
// 4. 计算标签掩码 E(K, J0)
let mut j0_bytes = j0.to_be_bytes();
cipher.encrypt_block(GenericArray::from_mut_slice(&mut j0_bytes));
let mask = u128::from_be_bytes(j0_bytes);
// 5. GHASH 处理函数 (与加密完全一致)
fn ghash_update(mut state: u128, h: u128, data: &[u8]) -> u128 {
let mut remaining = data;
while remaining.len() >= 16 {
state ^= bytes_to_u128_be(&remaining[..16]);
state = gf_mul(state, h);
remaining = &remaining[16..];
}
if !remaining.is_empty() {
state ^= bytes_to_u128_be(remaining);
state = gf_mul(state, h);
}
state
}
// 6. 计算期望的 GHASH 状态
let mut ghash_state = ghash_update(0, h, aad);
ghash_state = ghash_update(ghash_state, h, ciphertext);
// 7. 最终 GHASH:加入长度块
let len_block = ((aad.len() as u128) << 64) | ((ciphertext.len() as u128) << 3);
ghash_state ^= len_block;
ghash_state = gf_mul(ghash_state, h);
// 8. 计算期望的认证标签
let expected_tag = ghash_state ^ mask;
// 9. 常量时间验证标签 (防止时序攻击)
// 不要直接使用 expected_tag == received_tag,因为那会引入分支和时序泄露
let expected_bytes = expected_tag.to_be_bytes();
let mut diff = 0u8;
for i in 0..16 {
diff |= expected_bytes[i] ^ received_tag_bytes[i];
}
if diff != 0 {
return Err("Authentication failed: invalid tag".to_string());
}
// 10. 验证通过,执行 CTR 模式解密(从 J0 + 1 开始)
// 注意:CTR 的解密和加密操作完全相同,都是与密钥流异或
let mut plaintext = ciphertext.to_vec();
let mut counter = j0.wrapping_add(1);
let mut offset = 0;
while offset < plaintext.len() {
let mut counter_bytes = counter.to_be_bytes();
cipher.encrypt_block(GenericArray::from_mut_slice(&mut counter_bytes));
let end = (offset + 16).min(plaintext.len());
for i in offset..end {
plaintext[i] ^= counter_bytes[i - offset];
}
counter = counter.wrapping_add(1);
offset = end;
}
Ok(plaintext)
}
/// AES CTR Encrypt / Decrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 16 bytes
///
/// CTR mode is a stream cipher: encryption and decryption are identical.
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"1234567812345678"; // 16 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_ctr_encrypt(key, iv, data).unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_ctr_decrypt(key, iv, &enc_data).unwrap();
/// assert_eq!(data.to_vec(), dec_data);
/// ```
pub fn aes_ctr_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt};
use aes::cipher::{NewCipher, StreamCipher};
use aes::Aes192;
use ctr::Ctr128BE;
type Aes192Ctr = Ctr128BE<Aes192>;
if key.len() != 24 {
return Err(format!(
"Invalid key length: expected 24 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid IV length: expected 16 bytes, got {}",
iv.len()
));
}
let mut cipher =
Aes192Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
let mut ciphertext = data.to_vec();
cipher.apply_keystream(&mut ciphertext);
Ok(ciphertext)
}
/// AES CTR Decrypt (AES-192)
///
/// key must be 24 bytes
///
/// iv must be 16 bytes
///
/// CTR mode decryption is identical to encryption.
/// ```ignore
/// let key = b"123456781234567812345678"; // 24 bytes
/// let iv = b"1234567812345678"; // 16 bytes
/// let data = b"this is data";
/// let enc_data = doe::crypto::aes::aes_192::aes_ctr_encrypt(key, iv, data).unwrap();
/// let dec_data = doe::crypto::aes::aes_192::aes_ctr_decrypt(key, iv, &enc_data).unwrap();
/// assert_eq!(data.to_vec(), dec_data);
/// ```
pub fn aes_ctr_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
// Decryption in CTR mode is the same as encryption
aes_ctr_encrypt(key, iv, data)
}
}
pub mod aes_256 {
/// AES SIV Encrypt (AES-256)
/// key: 必须是 64 字节
/// nonce: 16 字节 (必需参数)
/// aad: 关联数据
/// data: 明文
pub fn aes_siv_encrypt(
key: &[u8],
nonce: &[u8],
aad: &[u8],
data: &[u8],
) -> Result<Vec<u8>, String> {
use aes_siv::aead::generic_array::GenericArray;
use aes_siv::aead::{Aead, KeyInit, Payload};
use aes_siv::Aes256SivAead;
if key.len() != 64 {
return Err("SIV AES-256 requires a 64-byte key".to_string());
}
if nonce.len() != 16 {
return Err(format!(
"SIV AES-256 requires a 16-byte nonce, got {}",
nonce.len()
));
}
let cipher = Aes256SivAead::new_from_slice(key)
.map_err(|e| format!("Failed to create SIV cipher: {}", e))?;
// 构造nonce的GenericArray
let nonce_array = GenericArray::from_slice(nonce);
// 构造标准 AEAD 负载
let payload = Payload {
msg: data, // 只有这部分会被加密
aad: aad, // 这部分只参与认证,不加密
};
// 输出 = 16字节SIV标签 + 密文
cipher
.encrypt(nonce_array, payload)
.map_err(|e| format!("SIV encryption failed: {}", e))
}
/// AES SIV Decrypt (AES-256)
pub fn aes_siv_decrypt(
key: &[u8],
nonce: &[u8],
aad: &[u8],
ciphertext_with_siv: &[u8],
) -> Result<Vec<u8>, String> {
use aes_siv::aead::generic_array::GenericArray;
use aes_siv::aead::{Aead, KeyInit, Payload};
use aes_siv::Aes256SivAead;
if key.len() != 64 {
return Err("SIV AES-256 requires a 64-byte key".to_string());
}
if nonce.len() != 16 {
return Err(format!(
"SIV AES-256 requires a 16-byte nonce, got {}",
nonce.len()
));
}
let cipher = Aes256SivAead::new_from_slice(key)
.map_err(|e| format!("Failed to create SIV cipher: {}", e))?;
// 构造nonce的GenericArray
let nonce_array = GenericArray::from_slice(nonce);
let payload = Payload {
msg: ciphertext_with_siv, // 传入包含 tag 的密文
aad: aad,
};
// decrypt 会自动剥离 16 字节的 tag,验证它,并返回真实的明文
cipher
.decrypt(nonce_array, payload)
.map_err(|_| "SIV authentication failed".to_string())
}
/// AES XTS Encrypt (AES-256)
///
/// key: 必须是 64 字节 (两个 32 字节的 AES-256 密钥拼接)
/// tweak: 16 字节 (通常代表磁盘扇区号)
/// data: 必须大于等于 16 字节
pub fn aes_xts_encrypt(
key: &[u8],
tweak: &[u8],
data: &[u8],
) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::GenericArray;
use aes::Aes256;
// 使用你环境中已经验证可用的 NewBlockCipher,避免 KeyInit 版本冲突
use aes::NewBlockCipher;
use xts_mode::Xts128;
if key.len() != 64 {
return Err("XTS AES-256 requires a 64-byte key".to_string());
}
if tweak.len() != 16 {
return Err("Tweak must be 16 bytes".to_string());
}
if data.len() < 16 {
return Err("Data must be at least 16 bytes for XTS".to_string());
}
// 分别初始化两个密钥
let cipher_1 = Aes256::new(GenericArray::from_slice(&key[..32]));
let cipher_2 = Aes256::new(GenericArray::from_slice(&key[32..]));
// 组合成 XTS 模式
let xts = Xts128::<Aes256>::new(cipher_1, cipher_2);
let mut buffer = data.to_vec();
let mut tweak_arr = [0u8; 16];
tweak_arr.copy_from_slice(tweak);
xts.encrypt_sector(&mut buffer, tweak_arr);
Ok(buffer)
}
/// AES XTS Decrypt (AES-256)
///
/// key: 必须是 64 字节 (两个 32 字节的 AES-256 密钥拼接)
/// tweak: 16 字节 (通常代表磁盘扇区号)
/// data: 必须大于等于 16 字节
pub fn aes_xts_decrypt(
key: &[u8],
tweak: &[u8],
data: &[u8],
) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::GenericArray;
use aes::Aes256;
// 使用你环境中已经验证可用的 NewBlockCipher,避免 KeyInit 版本冲突
use aes::NewBlockCipher;
use xts_mode::Xts128;
if key.len() != 64 {
return Err("XTS AES-256 requires a 64-byte key".to_string());
}
if tweak.len() != 16 {
return Err("Tweak must be 16 bytes".to_string());
}
if data.len() < 16 {
return Err("Data must be at least 16 bytes for XTS".to_string());
}
let cipher_1 = Aes256::new(GenericArray::from_slice(&key[..32]));
let cipher_2 = Aes256::new(GenericArray::from_slice(&key[32..]));
let xts = Xts128::<Aes256>::new(cipher_1, cipher_2);
let mut buffer = data.to_vec();
let mut tweak_arr = [0u8; 16];
tweak_arr.copy_from_slice(tweak);
xts.decrypt_sector(&mut buffer, tweak_arr);
Ok(buffer)
}
/// AES PCBC Encrypt (AES-256)
/// key: 32 bytes, iv: 16 bytes
pub fn aes_pcbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::generic_array::typenum::U32;
use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
use aes::Aes256;
if key.len() != 32 {
return Err(format!(
"Invalid key length: expected 32 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid iv length: expected 16 bytes, got {}",
iv.len()
));
}
if data.is_empty() {
return Err("Data cannot be empty".to_string());
}
use aes::NewBlockCipher;
let cipher = Aes256::new(GenericArray::<u8, U32>::from_slice(key));
let mut padded_data = data.to_vec();
// 手动添加 PKCS7 填充
let pad_len = 16 - (padded_data.len() % 16);
padded_data.extend(vec![pad_len as u8; pad_len]);
let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
let mut ciphertext = Vec::with_capacity(padded_data.len());
for chunk in padded_data.chunks(16) {
let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
// PCBC 核心逻辑: 异或前一个密文块 AND 前一个明文块
for i in 0..16 {
block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
}
cipher.encrypt_block(&mut block);
prev_plaintext.copy_from_slice(chunk);
prev_ciphertext.copy_from_slice(&block);
ciphertext.extend_from_slice(&block);
}
Ok(ciphertext)
}
/// AES PCBC Decrypt (AES-256)
pub fn aes_pcbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::generic_array::typenum::U32;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt};
use aes::Aes256;
use aes::NewBlockCipher;
if key.len() != 32 {
return Err(format!(
"Invalid key length: expected 32 bytes, got {}",
key.len()
));
}
if iv.len() != 16 {
return Err(format!(
"Invalid iv length: expected 16 bytes, got {}",
iv.len()
));
}
if data.len() % 16 != 0 {
return Err(format!(
"Invalid data length: must be multiple of 16 bytes, got {}",
data.len()
));
}
if data.is_empty() {
return Err("Data cannot be empty".to_string());
}
let cipher = Aes256::new(GenericArray::<u8, U32>::from_slice(key));
let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
let mut plaintext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
cipher.decrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
}
prev_plaintext.copy_from_slice(&block);
prev_ciphertext.copy_from_slice(chunk);
plaintext.extend_from_slice(&block);
}
// 手动移除 PKCS7 填充
if let Some(&pad_byte) = plaintext.last() {
if pad_byte >= 1 && pad_byte <= 16 {
let pad_len = pad_byte as usize;
if plaintext.len() >= pad_len {
let padding = &plaintext[plaintext.len() - pad_len..];
if padding.iter().all(|&b| b == pad_byte) {
plaintext.truncate(plaintext.len() - pad_len);
return Ok(plaintext);
}
}
}
}
Err("Invalid PKCS7 padding".to_string())
}
/// AES ECB Encrypt
///
/// key must be 32 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(), data).unwrap();
/// ```
pub fn aes_ecb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::GenericArray;
use aes::Aes256;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Ecb};
type Aes256Ecb = Ecb<Aes256, Pkcs7>;
// ECB mode does not use an IV
let cipher = Aes256Ecb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create ECB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES ECB Decrypt
///
/// key must be 32 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(), data).unwrap();
///let dec_data = doe::crypto::aes::aes_256::aes_ecb_decrypt("12345678123456781234567812345678".as_bytes(), &enc_data).unwrap();
/// ```
pub fn aes_ecb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::GenericArray;
use aes::Aes256;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Ecb};
type Aes256Ecb = Ecb<Aes256, Pkcs7>;
let cipher = Aes256Ecb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create ECB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES ECB decryption failed: {}", e))
}
/// AES CBC Encrypt
///
/// key must be 32 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_cbc_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_cbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes256;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
type Aes256Cbc = Cbc<Aes256, Pkcs7>;
let cipher = Aes256Cbc::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CBC cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES CBC Decrypt
///
/// key must be 32 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_cbc_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_256::aes_cbc_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes256;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
type Aes256Cbc = Cbc<Aes256, Pkcs7>;
let cipher = Aes256Cbc::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CBC cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES CBC decryption failed: {}", e))
}
/// AES CFB Encrypt
///
/// key must be 32 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_cfb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_cfb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes256;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Cfb};
// CFB is a stream cipher mode and does NOT use padding
type Aes256Cfb = Cfb<Aes256, NoPadding>;
let cipher = Aes256Cfb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CFB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES CFB Decrypt
///
/// key must be 32 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_cfb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_256::aes_cfb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_cfb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes256;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Cfb};
type Aes256Cfb = Cfb<Aes256, NoPadding>;
let cipher = Aes256Cfb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create CFB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES CFB decryption failed: {}", e))
}
/// AES OFB Encrypt
///
/// key must be 32 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_ofb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_ofb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes256;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Ofb};
// OFB is a stream cipher mode and does NOT use padding
type Aes256Ofb = Ofb<Aes256, NoPadding>;
let cipher = Aes256Ofb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create OFB cipher: {}", e))?;
Ok(cipher.encrypt_vec(data))
}
/// AES OFB Decrypt
///
/// key must be 32 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_ofb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_256::aes_ofb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_ofb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::Aes256;
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Ofb};
type Aes256Ofb = Ofb<Aes256, NoPadding>;
let cipher = Aes256Ofb::new_from_slices(key, iv)
.map_err(|e| format!("Failed to create OFB cipher: {}", e))?;
cipher
.decrypt_vec(data)
.map_err(|e| format!("AES OFB decryption failed: {}", e))
}
/// AES IGE Encrypt
///
/// key must be 32 bytes
///
/// iv must be 32 bytes
///
/// data must be 16*n bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_ige_encrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_ige_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
use aes::Aes256;
if key.len() != 32 {
return Err("Key must be 32 bytes".to_string());
}
if iv.len() != 32 {
return Err("IV must be 32 bytes".to_string());
}
if data.len() % 16 != 0 {
return Err("Data must be a multiple of 16 bytes".to_string());
}
use aes::NewBlockCipher;
let cipher = Aes256::new(GenericArray::from_slice(key));
let mut prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[..16]).to_owned();
let mut prev_prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[16..]).to_owned();
let mut ciphertext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block = GenericArray::clone_from_slice(chunk);
for i in 0..16 {
block[i] ^= prev_block[i] ^ prev_prev_block[i];
}
cipher.encrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_block[i];
}
ciphertext.extend_from_slice(&block);
prev_prev_block.copy_from_slice(&prev_block);
prev_block.copy_from_slice(&block);
}
Ok(ciphertext)
}
/// AES IGE Decrypt
///
/// key must be 32 bytes
///
/// iv must be 32 bytes
///
/// data must be 16*n bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_ige_encrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_256::aes_ige_decrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_ige_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::typenum::U16;
use aes::cipher::{generic_array::GenericArray, BlockDecrypt};
use aes::Aes256;
if key.len() != 32 {
return Err("Key must be 32 bytes".to_string());
}
if iv.len() != 32 {
return Err("IV must be 32 bytes".to_string());
}
if data.len() % 16 != 0 {
return Err("Data must be a multiple of 16 bytes".to_string());
}
use aes::NewBlockCipher;
let cipher = Aes256::new(GenericArray::from_slice(key));
let mut prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[..16]).to_owned();
let mut prev_prev_block: GenericArray<u8, U16> =
GenericArray::from_slice(&iv[16..]).to_owned();
let mut plaintext = Vec::with_capacity(data.len());
for chunk in data.chunks(16) {
let mut block = GenericArray::clone_from_slice(chunk);
for i in 0..16 {
block[i] ^= prev_block[i];
}
cipher.decrypt_block(&mut block);
for i in 0..16 {
block[i] ^= prev_block[i] ^ prev_prev_block[i];
}
plaintext.extend_from_slice(&block);
prev_prev_block.copy_from_slice(&prev_block);
prev_block.copy_from_slice(chunk);
}
Ok(plaintext)
}
/// AES 256 CTR Encrypt
///
/// key must be 32 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_ctr_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
/// ```
pub fn aes_ctr_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::GenericArray;
use aes::cipher::{NewCipher, StreamCipher};
use aes::Aes256;
use ctr::Ctr128BE;
type Aes256Ctr = Ctr128BE<Aes256>;
if key.len() != 32 {
return Err("Key must be 32 bytes".to_string());
}
if iv.len() != 16 {
return Err("IV must be 16 bytes".to_string());
}
let mut cipher =
Aes256Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
let mut ciphertext = data.to_vec();
cipher.apply_keystream(&mut ciphertext);
Ok(ciphertext)
}
/// AES CTR Decrypt
///
/// key must be 32 bytes
///
/// iv must be 16 bytes
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_256::aes_ctr_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_256::aes_ctr_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
/// ```
pub fn aes_ctr_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
use aes::cipher::generic_array::GenericArray;
use aes::cipher::{NewCipher, StreamCipher};
use aes::Aes256;
use ctr::Ctr128BE;
type Aes256Ctr = Ctr128BE<Aes256>;
if key.len() != 32 {
return Err("Key must be 32 bytes".to_string());
}
if iv.len() != 16 {
return Err("IV must be 16 bytes".to_string());
}
let mut cipher =
Aes256Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
let mut plaintext = data.to_vec();
cipher.apply_keystream(&mut plaintext);
Ok(plaintext)
}
}
}
///RSA example
///```ignore
///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
///let data = b"hello world";
///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
///assert_eq!(data, dec_data.as_slice());
/// ```
///
pub mod rsa {
use rsa::pkcs8::DecodePrivateKey;
pub use rsa::*;
///RSA example
///```ignore
///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
///let data = b"hello world";
///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
///assert_eq!(data, dec_data.as_slice());
/// ```
///
pub fn gen_priv_key(bits: usize) -> std::result::Result<RsaPrivateKey, String> {
let mut rng = rand::thread_rng();
RsaPrivateKey::new(&mut rng, bits)
.map_err(|e| format!("Failed to generate RSA private key: {}", e))
}
///RSA example
///```ignore
///let pem = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----";
///let priv_key = doe::crypto::rsa::gen_priv_key_from_pkcs8_pem(pem).unwrap();
///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
///let data = b"hello world";
///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
///assert_eq!(data, dec_data.as_slice());
/// ```
pub fn gen_priv_key_from_pkcs8_pem(s: &str) -> std::result::Result<RsaPrivateKey, String> {
RsaPrivateKey::from_pkcs8_pem(s)
.map_err(|e| format!("Failed to parse RSA private key from PEM: {}", e))
}
///RSA example
///```ignore
///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
///let data = b"hello world";
///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
///assert_eq!(data, dec_data.as_slice());
/// ```
///
pub fn gen_pub_key(priv_key: &RsaPrivateKey) -> RsaPublicKey {
RsaPublicKey::from(priv_key)
}
///RSA example
///```ignore
///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
///let data = b"hello world";
///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
///assert_eq!(data, dec_data.as_slice());
/// ```
///
pub fn encrypt(
pub_key: &RsaPublicKey,
data: &[u8],
) -> std::result::Result<Vec<u8>, String> {
let mut rng = rand::thread_rng();
pub_key
.encrypt(&mut rng, Pkcs1v15Encrypt, data)
.map_err(|e| format!("RSA encryption failed: {}", e))
}
///RSA example
///```ignore
///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
///let data = b"hello world";
///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
///assert_eq!(data, dec_data.as_slice());
/// ```
///
pub fn decrypt(
priv_key: &RsaPrivateKey,
enc_data: &[u8],
) -> std::result::Result<Vec<u8>, String> {
priv_key
.decrypt(Pkcs1v15Encrypt, enc_data)
.map_err(|e| format!("RSA decryption failed: {}", e))
}
}
pub mod sha1 {
pub use sha1::*;
/// not secure
/// ```ignore
/// let hash = doe::crypto::sha1::sha1(b"hello world");
/// println!("SHA1 hash: {}", hash);
/// ```
pub fn sha1(data: &[u8]) -> String {
use sha1::{Digest, Sha1};
let mut hasher = Sha1::new();
hasher.update(data);
let result = hasher.finalize();
hex::encode(result)
}
}
pub mod sha2 {
pub use sha2::*;
/// ```ignore
/// let hash = doe::crypto::sha2::sha_224(b"hello world");
/// println!("SHA224 hash: {}", hash);
/// ```
pub fn sha_224(data: &[u8]) -> String {
use sha2::{Digest, Sha224};
let mut hasher = Sha224::new();
hasher.update(data);
let result = hasher.finalize();
hex::encode(result)
}
/// ```ignore
/// let hash = doe::crypto::sha2::sha_256(b"hello world");
/// println!("SHA256 hash: {}", hash);
/// ```
fn sha_256(data: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(data);
let result = hasher.finalize();
hex::encode(result)
}
/// ```ignore
/// let hash = doe::crypto::sha2::sha_512_224(b"hello world");
/// println!("SHA512/224 hash: {}", hash);
/// ```
fn sha_512_224(data: &[u8]) -> String {
use sha2::{Digest, Sha512_224};
let mut hasher = Sha512_224::new();
hasher.update(data);
let result = hasher.finalize();
hex::encode(result)
}
/// ```ignore
/// let hash = doe::crypto::sha2::sha_512_256(b"hello world");
/// println!("SHA512/256 hash: {}", hash);
/// ```
fn sha_512_256(data: &[u8]) -> String {
use sha2::{Digest, Sha512_256};
let mut hasher = Sha512_256::new();
hasher.update(data);
let result = hasher.finalize();
hex::encode(result)
}
/// ```ignore
/// let hash = doe::crypto::sha2::sha_384(b"hello world");
/// println!("SHA384 hash: {}", hash);
/// ```
fn sha_384(data: &[u8]) -> String {
use sha2::{Digest, Sha384};
let mut hasher = Sha384::new();
hasher.update(data);
let result = hasher.finalize();
hex::encode(result)
}
/// ```ignore
/// let hash = doe::crypto::sha2::sha_512(b"hello world");
/// println!("SHA512 hash: {}", hash);
/// ```
pub fn sha_512(data: &[u8]) -> String {
use sha2::{Digest, Sha512};
let mut hasher = Sha512::new();
hasher.update(data);
let result = hasher.finalize().to_vec();
hex::encode_upper(result)
}
}
pub mod sha3 {
pub use sha3::*;
/// ```ignore
/// let hash = doe::crypto::sha3::sha_224(b"hello world");
/// println!("SHA3-224 hash: {}", hash);
/// ```
pub fn sha_224(data: &[u8]) -> String {
use sha3::{Digest, Sha3_224};
let mut hasher = Sha3_224::new();
hasher.update(data);
let result = hasher.finalize().to_vec();
hex::encode_upper(result)
}
/// ```ignore
/// let hash = doe::crypto::sha3::sha_256(b"hello world");
/// println!("SHA3-256 hash: {}", hash);
/// ```
pub fn sha_256(data: &[u8]) -> String {
use sha3::{Digest, Sha3_256};
let mut hasher = Sha3_256::new();
hasher.update(data);
let result = hasher.finalize().to_vec();
hex::encode_upper(result)
}
/// ```ignore
/// let hash = doe::crypto::sha3::sha_384(b"hello world");
/// println!("SHA3-384 hash: {}", hash);
/// ```
pub fn sha_384(data: &[u8]) -> String {
use sha3::{Digest, Sha3_384};
let mut hasher = Sha3_384::new();
hasher.update(data);
let result = hasher.finalize().to_vec();
hex::encode_upper(result)
}
/// ```ignore
/// let hash = doe::crypto::sha3::sha_512(b"hello world");
/// println!("SHA3-512 hash: {}", hash);
/// ```
pub fn sha_512(data: &[u8]) -> String {
use sha3::{Digest, Sha3_512};
let mut hasher = Sha3_512::new();
hasher.update(data);
let result = hasher.finalize().to_vec();
hex::encode_upper(result)
}
/// ```ignore
/// let hash = doe::crypto::sha3::shake_128(b"hello world");
/// println!("SHAKE128 hash: {}", hash);
/// ```
pub fn shake_128(data: &[u8]) -> String {
use sha3::{
digest::{ExtendableOutput, Update, XofReader},
Shake128,
};
let mut hasher = Shake128::default();
hasher.update(data);
let mut reader = hasher.finalize_xof();
// 128 bytes of output
let mut result = [0u8; 128];
reader.read(&mut result);
hex::encode_upper(result)
}
/// ```ignore
/// let hash = doe::crypto::sha3::shake_256(b"hello world");
/// println!("SHAKE256 hash: {}", hash);
/// ```
pub fn shake_256(data: &[u8]) -> String {
use sha3::{
digest::{ExtendableOutput, Update, XofReader},
Shake256,
};
let mut hasher = Shake256::default();
hasher.update(data);
let mut reader = hasher.finalize_xof();
// 256 bytes of output
let mut result = [0u8; 256];
reader.read(&mut result);
hex::encode_upper(result)
}
}
pub mod sm {
pub use sm_crypto::*;
/// SM3 哈希算法 (中国国密散列算法标准)
///
/// 返回小写 16 进制字符串
/// ```ignore
/// let hash = doe::crypto::sm::sm3_hash(b"abc");
/// assert_eq!(hash, "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0");
/// ```
pub fn sm3_hash(data: &[u8]) -> String {
sm_crypto::sm3::sm3_hash(data)
}
/// SM2 生成密钥对
///
/// 返回 (私钥, 公钥)。公钥为 16 进制字符串,不含 "04" 前缀。
/// ```ignore
/// let (sk, pk) = doe::crypto::sm::sm2_gen_keypair();
/// ```
pub fn sm2_gen_keypair() -> (String, String) {
sm_crypto::sm2::gen_keypair()
}
/// SM2 签名
///
/// sk: 私钥 (16进制字符串)
/// id: 是否使用默认 ID (默认为 "1234567812345678")
/// ```ignore
/// let (sk, _) = doe::crypto::sm::sm2_gen_keypair();
/// let sign = doe::crypto::sm::sm2_sign(&sk, b"abc", true);
/// ```
pub fn sm2_sign(sk: &str, data: &[u8], id: bool) -> String {
let sign_ctx = sm_crypto::sm2::Sign::new(sk);
use num_bigint::BigUint;
fn to_fixed_bytes(num: &BigUint, len: usize) -> Vec<u8> {
let bytes = num.to_bytes_be(); // 大端字节
if bytes.len() >= len {
// 如果字节数超过所需长度,取最后 len 个字节(通常不会发生,但安全起见)
bytes[bytes.len() - len..].to_vec()
} else {
// 前面补零
let mut padded = vec![0u8; len - bytes.len()];
padded.extend_from_slice(&bytes);
padded
}
}
let (r, s): (BigUint, BigUint) = sign_ctx.sign(data, id);
// 将 r 和 s 转为固定 32 字节的大端字节数组(不足补零)
let r_bytes = to_fixed_bytes(&r, 32);
let s_bytes = to_fixed_bytes(&s, 32);
// 拼接 r + s 得到完整签名(64 字节)
let mut signature = Vec::with_capacity(64);
signature.extend_from_slice(&r_bytes);
signature.extend_from_slice(&s_bytes);
// 转为 hex 字符串
let hex_sig = hex::encode(&signature);
hex_sig
}
/// SM2 验签
///
/// pk: 公钥 (16进制字符串,不带04前缀)
/// ```ignore
/// let (_, pk) = doe::crypto::sm::sm2_gen_keypair();
/// let verify = doe::crypto::sm::sm2_verify(&pk, b"abc", &sign, true);
/// ```
use num_bigint::BigUint;
use sm_crypto::sm2::Verify;
pub fn sm2_verify(pk: &str, data: &[u8], sign: &str, id: bool) -> bool {
// 1. 将签名hex字符串转换为 (BigUint, BigUint)
let sig_bytes = hex::decode(sign).expect("Invalid hex signature");
let (r, s) = (
BigUint::from_bytes_be(&sig_bytes[0..32]),
BigUint::from_bytes_be(&sig_bytes[32..64]),
);
// 2. 创建验签上下文并执行验签
let verify_ctx = sm_crypto::sm2::Verify::new(pk);
verify_ctx.verify(data, (r, s), id) // id 参数现在是 bool 类型
}
/// SM2 加密
///
/// pk: 公钥 (16进制字符串,不带04前缀)
/// ```ignore
/// let (_, pk) = doe::crypto::sm::sm2_gen_keypair();
/// let enc = doe::crypto::sm::sm2_encrypt(&pk, b"abc").unwrap();
/// ```
pub fn sm2_encrypt(pk: &str, data: &[u8]) -> Result<Vec<u8>, String> {
let enc_ctx = sm_crypto::sm2::Encrypt::new(pk);
Ok(enc_ctx.encrypt(data))
}
/// SM2 解密
///
/// sk: 私钥 (16进制字符串)
/// ```ignore
/// let (sk, _) = doe::crypto::sm::sm2_gen_keypair();
/// let dec = doe::crypto::sm::sm2_decrypt(&sk, &enc).unwrap();
/// ```
pub fn sm2_decrypt(sk: &str, data: &[u8]) -> Result<Vec<u8>, String> {
let dec_ctx = sm_crypto::sm2::Decrypt::new(sk);
// sm_crypto 的 decrypt 方法本身返回 Vec<u8>,内部如果失败可能会 panic
// 这里包一层 Result 以保持 API 风格统一
Ok(dec_ctx.decrypt(data))
}
/// SM4 ECB 模式加密
///
/// key 必须为 16 字节
/// 内部自动处理 PKCS7 填充
/// ```ignore
/// let key = b"1234567812345678";
/// let enc = doe::crypto::sm::sm4_ecb_encrypt(key, b"abc").unwrap();
/// ```
pub fn sm4_ecb_encrypt(key: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
if key.len() != 16 {
return Err("SM4 key must be 16 bytes".to_string());
}
let sm4_ecb = sm_crypto::sm4::CryptSM4ECB::new(key);
Ok(sm4_ecb.encrypt_ecb(data))
}
/// SM4 ECB 模式解密
///
/// key 必须为 16 字节
/// ```ignore
/// let key = b"1234567812345678";
/// let dec = doe::crypto::sm::sm4_ecb_decrypt(key, &enc).unwrap();
/// ```
pub fn sm4_ecb_decrypt(key: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
if key.len() != 16 {
return Err("SM4 key must be 16 bytes".to_string());
}
let sm4_ecb = sm_crypto::sm4::CryptSM4ECB::new(key);
Ok(sm4_ecb.decrypt_ecb(data))
}
/// SM4 CBC 模式加密
///
/// key 必须为 16 字节
/// iv 必须为 16 字节
/// 内部自动处理 PKCS7 填充
/// ```ignore
/// let key = b"1234567812345678";
/// let iv = b"0000000000000000";
/// let enc = doe::crypto::sm::sm4_cbc_encrypt(key, iv, b"abc").unwrap();
/// ```
pub fn sm4_cbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
if key.len() != 16 {
return Err("SM4 key must be 16 bytes".to_string());
}
if iv.len() != 16 {
return Err("SM4 IV must be 16 bytes".to_string());
}
let sm4_cbc = sm_crypto::sm4::CryptSM4CBC::new(key, iv);
Ok(sm4_cbc.encrypt_cbc(data))
}
/// SM4 CBC 模式解密
///
/// key 必须为 16 字节
/// iv 必须为 16 字节
/// ```ignore
/// let key = b"1234567812345678";
/// let iv = b"0000000000000000";
/// let dec = doe::crypto::sm::sm4_cbc_decrypt(key, iv, &enc).unwrap();
/// ```
pub fn sm4_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
if key.len() != 16 {
return Err("SM4 key must be 16 bytes".to_string());
}
if iv.len() != 16 {
return Err("SM4 IV must be 16 bytes".to_string());
}
let sm4_cbc = sm_crypto::sm4::CryptSM4CBC::new(key, iv);
Ok(sm4_cbc.decrypt_cbc(data))
}
}
/// ```ignore
/// let hash = doe::crypto::md5(b"hello world");
/// println!("MD5 hash: {}", hash);
/// ```
pub fn md5(data: &[u8]) -> String {
use md5::compute;
let result = compute(data);
result
.to_vec()
.iter()
.map(|x| format!("{:02x}", x))
.collect::<String>()
}
/// in defalut 32 bytes
/// ```ignore
/// let hash = doe::crypto::blake3(b"hello world");
/// println!("BLAKE3 hash: {}", hash);
/// ```
pub fn blake3(data: &[u8]) -> String {
let hasher = blake3::hash(data);
hex::encode_upper(hasher.as_bytes())
}
/// can set the output size
/// ```ignore
/// let hash = doe::crypto::blake3_xof(b"hello world", 64);
/// println!("BLAKE3 XOF hash: {}", hash);
/// ```
pub fn blake3_xof(data: &[u8], size: usize) -> String {
let hasher = blake3::Hasher::new();
let mut reader = hasher.finalize_xof();
let mut result = vec![0u8; size];
reader.fill(&mut result);
hex::encode_upper(result)
}
}
#[cfg(feature = "crypto")]
pub use crypto::*;