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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! This module contains types providing the cryptographic primitives necessary to implement
//! Blocktree.
//! 
//! The [openssl] create is used for all of these primitives,
//! none of them are directly implemented in this module.
//! Rather, the types here wrap the functionality provided by OpenSSL in a more convenient
//! interface, and they serve as an abstraction layer, so that the underlying crypto library can be
//! more easily replaced.
pub mod tpm;

pub mod merkle_stream;
pub mod x509;
pub use merkle_stream::MerkleStream;
pub mod secret_stream;
pub use secret_stream::SecretStream;
mod envelope;
pub mod file_cred_store;
pub use envelope::Envelope;
//mod sign_stream;
//pub use sign_stream::SignStream;

use crate::{
    btensure, bterr, fmt, io, BigArray, BlockError, BlockMeta, BlockPath, Deserialize, Epoch,
    Formatter, Hashable, Principal, Principaled, Result, Serialize, Writecap, WritecapBody,
};

use btserde::{self, from_vec, to_vec, write_to};
use foreign_types::ForeignType;
use log::error;
use openssl::{
    encrypt::{Decrypter as OsslDecrypter, Encrypter as OsslEncrypter},
    error::ErrorStack,
    hash::{hash, DigestBytes, Hasher, MessageDigest},
    nid::Nid,
    pkcs5::pbkdf2_hmac,
    pkey::{HasPrivate, HasPublic, PKey, PKeyRef},
    rand::rand_bytes,
    rsa::{Padding as OpensslPadding, Rsa as OsslRsa},
    sign::{Signer as OsslSigner, Verifier as OsslVerifier},
    symm::{decrypt as openssl_decrypt, encrypt as openssl_encrypt, Cipher, Crypter, Mode},
};
use serde::{
    de::{self, DeserializeOwned, Deserializer, SeqAccess, Visitor},
    ser::{Error as SerError, SerializeStruct, Serializer},
};
use std::{
    cell::RefCell,
    fmt::Display,
    io::{Read, Write},
    marker::PhantomData,
    ops::{Deref, DerefMut},
    sync::Arc,
};
use strum_macros::{Display, EnumDiscriminants, FromRepr};
use zeroize::{ZeroizeOnDrop, Zeroizing};

/// The encryption of some type `T`.
/// 
/// This type is just e wrapper around a [Vec] of [u8] which remembers the type it was serialized
/// and encrypted from.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
pub struct Ciphertext<T> {
    data: Vec<u8>,
    phantom: PhantomData<T>,
}

impl<T> Ciphertext<T> {
    fn new(data: Vec<u8>) -> Ciphertext<T> {
        Ciphertext {
            data,
            phantom: PhantomData,
        }
    }
}

/// A signature over the serialization of a type `T`.
/// 
/// This struct allows the signature over a serialization of `T` to be stored together with a
/// signature over  it.
pub struct Signed<T> {
    _data: Vec<u8>,
    sig: Signature,
    phantom: PhantomData<T>,
}

impl<T> Signed<T> {
    fn new(data: Vec<u8>, sig: Signature) -> Signed<T> {
        Signed {
            _data: data,
            sig,
            phantom: PhantomData,
        }
    }
}

/// Errors that can occur during cryptographic operations.
#[derive(Debug)]
pub enum Error {
    NoReadCap,
    NoKeyAvailable,
    MissingPrivateKey,
    KeyVariantUnsupported,
    BlockNotEncrypted,
    InvalidHashFormat,
    InvalidSignature,
    IncorrectSize {
        expected: usize,
        actual: usize,
    },
    TooSmall {
        required: usize,
        actual: usize,
    },
    IndexOutOfBounds {
        index: usize,
        limit: usize,
    },
    IndivisibleSize {
        divisor: usize,
        actual: usize,
    },
    InvalidOffset {
        actual: usize,
        limit: usize,
    },
    HashCmpFailure,
    RootHashNotVerified,
    SignatureMismatch(Box<SignatureMismatch>),
    /// This variant is used to convey errors that originated in an underlying library.
    Library(Box<dyn ::std::error::Error + Send + Sync + 'static>),
    /// Occurs when an attempt is made to finish an [Op] that is already finished.
    OpAlreadyFinished,
    /// Indicates that a writecap was not issued to a particular [Principal].
    NotIssuedTo,
    /// Indicates that no root credentials were present in a [CredStore].
    NoRootCreds,
    /// Indicates that the wrong root password was given when attempting to access the root
    /// credentials.
    WrongRootPassword,
}

impl Error {
    fn signature_mismatch(expected: Principal, actual: Principal) -> Error {
        Error::SignatureMismatch(Box::new(SignatureMismatch { expected, actual }))
    }

    fn library<E: std::error::Error + Send + Sync + 'static>(err: E) -> Error {
        Error::Library(Box::new(err))
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Error::NoReadCap => write!(f, "no readcap"),
            Error::NoKeyAvailable => write!(f, "no key available"),
            Error::MissingPrivateKey => write!(f, "private key was missing"),
            Error::KeyVariantUnsupported => write!(f, "unsupported key variant"),
            Error::BlockNotEncrypted => write!(f, "block was not encrypted"),
            Error::InvalidHashFormat => write!(f, "invalid format"),
            Error::InvalidSignature => write!(f, "invalid signature"),
            Error::IncorrectSize { expected, actual } => {
                write!(f, "expected size {expected} but got {actual}")
            }
            Error::TooSmall { required, actual } => {
                write!(f, "expected at least {required} but got {actual}")
            }
            Error::IndexOutOfBounds { index, limit } => write!(
                f,
                "index {index} is out of bounds, it must be strictly less than {limit}",
            ),
            Error::IndivisibleSize { divisor, actual } => write!(
                f,
                "expected a size which is divisible by {divisor} but got {actual}",
            ),
            Error::InvalidOffset { actual, limit } => write!(
                f,
                "offset {actual} is out of bounds, it must be strictly less than {limit}",
            ),
            Error::HashCmpFailure => write!(f, "hash data are not equal"),
            Error::RootHashNotVerified => write!(f, "root hash is not verified"),
            Error::SignatureMismatch(mismatch) => {
                let actual = &mismatch.actual;
                let expected = &mismatch.expected;
                write!(
                    f,
                    "expected a signature from {expected} but found one from {actual}"
                )
            }
            Error::Library(err) => err.fmt(f),
            Error::OpAlreadyFinished => write!(f, "operation is already finished"),
            Error::NotIssuedTo => write!(f, "writecap was not issued to the given principal"),
            Error::NoRootCreds => write!(f, "root creds are not present"),
            Error::WrongRootPassword => write!(f, "incorrect root password"),
        }
    }
}

impl std::error::Error for Error {}

impl From<ErrorStack> for Error {
    fn from(error: ErrorStack) -> Error {
        Error::library(error)
    }
}

/// Contains information about why a signature verification failed.
#[derive(Debug)]
pub struct SignatureMismatch {
    /// The principal whose signature was actually present.
    pub actual: Principal,
    /// The principal whose signature was expected.
    pub expected: Principal,
}

/// Returns an array of the given length filled with cryptographically strong random data.
pub fn rand_array<const LEN: usize>() -> Result<[u8; LEN]> {
    let mut array = [0; LEN];
    rand_bytes(&mut array)?;
    Ok(array)
}

/// Returns a vector of the given length with with cryptographically strong random data.
pub fn rand_vec(len: usize) -> Result<Vec<u8>> {
    let mut vec = vec![0; len];
    rand_bytes(&mut vec)?;
    Ok(vec)
}

/// An ongoing Init-Update-Finish operation.
pub trait Op {
    /// Update this operation using the given data.
    fn update(&mut self, data: &[u8]) -> Result<()>;

    /// Finish this operation and write the result into the given buffer. If the given buffer is not
    /// large enough the implementation must return Error::IncorrectSize.
    fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize>;
}

impl<T: ?Sized + Op, P: DerefMut<Target = T>> Op for P {
    fn update(&mut self, data: &[u8]) -> Result<()> {
        self.deref_mut().update(data)
    }

    fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
        self.deref_mut().finish_into(buf)
    }
}

/// An ongoing hash operation.
pub trait HashOp: Op {
    /// The specific hash type which is returned by the finish method.
    type Hash: Hash;

    /// Returns the kind of hash this operation is computing.
    fn kind(&self) -> HashKind;

    /// Finish this operation and return a hash type containing the result.
    fn finish(&mut self) -> Result<Self::Hash>;
}

/// A hash operation which uses OpenSSL.
pub struct OsslHashOp<H> {
    hasher: Hasher,
    phantom: PhantomData<H>,
    kind: HashKind,
}

impl<H> OsslHashOp<H> {
    fn new(arg: HashKind) -> Result<Self> {
        let hasher = Hasher::new(arg.into())?;
        let phantom = PhantomData;
        Ok(OsslHashOp {
            hasher,
            phantom,
            kind: arg,
        })
    }
}

impl<H> Op for OsslHashOp<H> {
    fn update(&mut self, data: &[u8]) -> Result<()> {
        Ok(self.hasher.update(data)?)
    }

    fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
        if buf.len() < self.kind.len() {
            return Err(bterr!(Error::IncorrectSize {
                expected: self.kind.len(),
                actual: buf.len(),
            }));
        }
        let digest = self.hasher.finish()?;
        let slice = digest.as_ref();
        buf.copy_from_slice(slice);
        Ok(slice.len())
    }
}

impl<H: Hash + From<DigestBytes>> HashOp for OsslHashOp<H> {
    type Hash = H;

    fn kind(&self) -> HashKind {
        self.kind
    }

    fn finish(&mut self) -> Result<Self::Hash> {
        let digest = self.hasher.finish()?;
        Ok(H::from(digest))
    }
}

/// A wrapper which updates a [HashOp] when data is read or written.
pub struct HashStream<T, Op: HashOp> {
    inner: T,
    op: Op,
    update_failed: bool,
}

impl<T, Op: HashOp> HashStream<T, Op> {
    /// Create a new `HashWrap`.
    pub fn new(inner: T, op: Op) -> HashStream<T, Op> {
        HashStream {
            inner,
            op,
            update_failed: false,
        }
    }

    /// Finish this hash operation and write the result into the given buffer. The number of bytes
    /// written is returned.
    pub fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
        if self.update_failed {
            return Err(bterr!(
                "HashStream::finish_into can't produce result due to HashOp update failure",
            ));
        }
        self.op.finish_into(buf)
    }

    /// Finish this hash operation and return the resulting hash.
    pub fn finish(&mut self) -> Result<Op::Hash> {
        if self.update_failed {
            return Err(bterr!(
                "HashStream::finish can't produce result due to HashOp update failure",
            ));
        }
        self.op.finish()
    }
}

impl<T: Read, Op: HashOp> Read for HashStream<T, Op> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.update_failed {
            return Err(bterr!(
                "HashStream::read can't continue due to previous HashOp update failure",
            )
            .into());
        }
        let read = self.inner.read(buf)?;
        if read > 0 {
            if let Err(err) = self.op.update(&buf[..read]) {
                self.update_failed = true;
                error!("HashWrap::read failed to update HashOp: {}", err);
            }
        }
        Ok(read)
    }
}

impl<T: Write, Op: HashOp> Write for HashStream<T, Op> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.op.update(buf)?;
        self.inner.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

/// A cryptographic hash.
pub trait Hash: AsRef<[u8]> + AsMut<[u8]> + Sized {
    /// The hash operation associated with this `Hash`.
    type Op: HashOp;
    /// The type of the argument required by `new`.
    type Arg;

    /// Returns a new `Hash` instance.
    fn new(arg: Self::Arg) -> Self;
    /// Returns the `HashKind` of self.
    fn kind(&self) -> HashKind;
    /// Starts a new hash operation.
    fn start_op(&self) -> Result<Self::Op>;
}

/// Trait for hash types which can be created with no arguments.
pub trait DefaultHash: Hash {
    fn default() -> Self;
}

impl<A: Default, T: Hash<Arg = A>> DefaultHash for T {
    fn default() -> Self {
        Self::new(A::default())
    }
}

/// Represents the SHA2-256 hash algorithm.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hashable, Clone)]
pub struct Sha2_256([u8; Self::LEN]);

impl Sha2_256 {
    pub const KIND: HashKind = HashKind::Sha2_256;
    pub const LEN: usize = Self::KIND.len();
}

impl AsRef<[u8]> for Sha2_256 {
    fn as_ref(&self) -> &[u8] {
        self.0.as_slice()
    }
}

impl AsMut<[u8]> for Sha2_256 {
    fn as_mut(&mut self) -> &mut [u8] {
        self.0.as_mut_slice()
    }
}

impl From<DigestBytes> for Sha2_256 {
    fn from(value: DigestBytes) -> Self {
        let mut hash = Sha2_256::new(());
        // TODO: It would be great if there was a way to avoid this copy.
        hash.as_mut().copy_from_slice(value.as_ref());
        hash
    }
}

impl From<[u8; Self::LEN]> for Sha2_256 {
    fn from(value: [u8; Self::LEN]) -> Self {
        Sha2_256(value)
    }
}

impl From<Sha2_256> for [u8; Sha2_256::LEN] {
    fn from(value: Sha2_256) -> Self {
        value.0
    }
}

impl Hash for Sha2_256 {
    type Op = OsslHashOp<Sha2_256>;
    type Arg = ();

    fn new(_: Self::Arg) -> Self {
        Sha2_256([0u8; Self::KIND.len()])
    }

    fn kind(&self) -> HashKind {
        Self::KIND
    }

    fn start_op(&self) -> Result<Self::Op> {
        OsslHashOp::new(Self::KIND)
    }
}

/// Represents the SHA2-512 hash algorithm.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hashable, Clone)]
pub struct Sha2_512(#[serde(with = "BigArray")] [u8; Self::LEN]);

impl Sha2_512 {
    pub const KIND: HashKind = HashKind::Sha2_512;
    pub const LEN: usize = Self::KIND.len();
}

impl AsRef<[u8]> for Sha2_512 {
    fn as_ref(&self) -> &[u8] {
        self.0.as_slice()
    }
}

impl AsMut<[u8]> for Sha2_512 {
    fn as_mut(&mut self) -> &mut [u8] {
        self.0.as_mut_slice()
    }
}

impl From<DigestBytes> for Sha2_512 {
    fn from(value: DigestBytes) -> Self {
        let mut hash = Sha2_512::new(());
        hash.as_mut().copy_from_slice(value.as_ref());
        hash
    }
}

impl From<[u8; Self::LEN]> for Sha2_512 {
    fn from(value: [u8; Self::LEN]) -> Self {
        Self(value)
    }
}

impl From<Sha2_512> for [u8; Sha2_512::LEN] {
    fn from(value: Sha2_512) -> Self {
        value.0
    }
}

impl Hash for Sha2_512 {
    type Op = OsslHashOp<Sha2_512>;
    type Arg = ();

    fn new(_: Self::Arg) -> Self {
        Sha2_512([0u8; Self::LEN])
    }

    fn kind(&self) -> HashKind {
        Self::KIND
    }

    fn start_op(&self) -> Result<Self::Op> {
        OsslHashOp::new(Self::KIND)
    }
}

/// One of several concrete hash types.
#[derive(
    Debug,
    PartialEq,
    Eq,
    Serialize,
    Deserialize,
    Hashable,
    Clone,
    EnumDiscriminants,
    PartialOrd,
    Ord,
)]
#[strum_discriminants(derive(FromRepr, Display, Serialize, Deserialize))]
#[strum_discriminants(name(HashKind))]
pub enum VarHash {
    Sha2_256(Sha2_256),
    Sha2_512(Sha2_512),
}

impl VarHash {
    /// The character that's used to separate a hash type from its value in its string
    /// representation.
    const HASH_SEP: char = '!';

    pub fn kind(&self) -> HashKind {
        self.into()
    }

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

    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        self.as_mut()
    }
}

impl From<HashKind> for VarHash {
    fn from(kind: HashKind) -> VarHash {
        match kind {
            HashKind::Sha2_256 => VarHash::Sha2_256(Sha2_256::default()),
            HashKind::Sha2_512 => VarHash::Sha2_512(Sha2_512::default()),
        }
    }
}

impl AsRef<[u8]> for VarHash {
    fn as_ref(&self) -> &[u8] {
        match self {
            VarHash::Sha2_256(arr) => arr.as_ref(),
            VarHash::Sha2_512(arr) => arr.as_ref(),
        }
    }
}

impl AsMut<[u8]> for VarHash {
    fn as_mut(&mut self) -> &mut [u8] {
        match self {
            VarHash::Sha2_256(arr) => arr.as_mut(),
            VarHash::Sha2_512(arr) => arr.as_mut(),
        }
    }
}

impl TryFrom<MessageDigest> for VarHash {
    type Error = crate::Error;

    fn try_from(value: MessageDigest) -> Result<Self> {
        let kind: HashKind = value.try_into()?;
        Ok(kind.into())
    }
}

impl Hash for VarHash {
    type Op = VarHashOp;
    type Arg = HashKind;

    fn new(arg: Self::Arg) -> Self {
        arg.into()
    }

    fn kind(&self) -> HashKind {
        self.kind()
    }

    fn start_op(&self) -> Result<Self::Op> {
        VarHashOp::new(self.kind())
    }
}

impl TryFrom<&str> for VarHash {
    type Error = crate::Error;

    fn try_from(string: &str) -> Result<VarHash> {
        let mut split: Vec<&str> = string.split(Self::HASH_SEP).collect();
        if split.len() != 2 {
            return Err(bterr!(Error::InvalidHashFormat));
        };
        let second = split.pop().ok_or(Error::InvalidHashFormat)?;
        let first = split
            .pop()
            .ok_or(Error::InvalidHashFormat)?
            .parse::<usize>()
            .map_err(|_| Error::InvalidHashFormat)?;
        let mut hash = VarHash::from(HashKind::from_repr(first).ok_or(Error::InvalidHashFormat)?);
        base64_url::decode_to_slice(second, hash.as_mut()).map_err(|_| Error::InvalidHashFormat)?;
        Ok(hash)
    }
}

impl Display for VarHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let hash_kind: HashKind = self.into();
        let hash_data = base64_url::encode(self.as_ref());
        write!(f, "{}{}{hash_data}", hash_kind as u32, VarHash::HASH_SEP)
    }
}

#[allow(clippy::derivable_impls)]
impl Default for HashKind {
    fn default() -> HashKind {
        HashKind::Sha2_256
    }
}

impl Default for VarHash {
    fn default() -> Self {
        HashKind::default().into()
    }
}

impl HashKind {
    #[allow(clippy::len_without_is_empty)]
    pub const fn len(self) -> usize {
        match self {
            HashKind::Sha2_256 => 32,
            HashKind::Sha2_512 => 64,
        }
    }

    pub fn digest<'a, I: Iterator<Item = &'a [u8]>>(self, dest: &mut [u8], parts: I) -> Result<()> {
        btensure!(
            dest.len() >= self.len(),
            Error::TooSmall {
                required: self.len(),
                actual: dest.len(),
            }
        );
        let mut hasher = Hasher::new(self.into())?;
        for part in parts {
            hasher.update(part)?;
        }
        let hash = hasher.finish()?;
        dest[..self.len()].copy_from_slice(&hash);
        Ok(())
    }
}

/// An implementation of [std::hash::Hasher] which allows cryptographic hash algorithms to be used.
pub struct BtHasher {
    hasher: RefCell<Hasher>,
}

impl BtHasher {
    pub fn new(kind: HashKind) -> Result<Self> {
        btensure!(
            kind.len() >= 8,
            bterr!("only digests which produce at least 8 bytes are supported")
        );
        let hasher = RefCell::new(Hasher::new(kind.into())?);
        Ok(Self { hasher })
    }
}

impl std::hash::Hasher for BtHasher {
    fn write(&mut self, bytes: &[u8]) {
        let hasher = self.hasher.get_mut();
        hasher.update(bytes).unwrap();
    }

    fn finish(&self) -> u64 {
        let mut hasher = self.hasher.borrow_mut();
        let hash = hasher.finish().unwrap();
        let mut buf = [0u8; 8];
        buf.copy_from_slice(&hash[..8]);
        u64::from_le_bytes(buf)
    }

    fn write_u8(&mut self, i: u8) {
        self.write(&[i])
    }

    fn write_u16(&mut self, i: u16) {
        self.write(&i.to_le_bytes())
    }

    fn write_u32(&mut self, i: u32) {
        self.write(&i.to_le_bytes())
    }

    fn write_u64(&mut self, i: u64) {
        self.write(&i.to_le_bytes())
    }

    fn write_u128(&mut self, i: u128) {
        self.write(&i.to_le_bytes())
    }

    fn write_usize(&mut self, i: usize) {
        self.write(&i.to_le_bytes())
    }

    fn write_i8(&mut self, i: i8) {
        self.write_u8(i as u8)
    }

    fn write_i16(&mut self, i: i16) {
        self.write_u16(i as u16)
    }

    fn write_i32(&mut self, i: i32) {
        self.write_u32(i as u32)
    }

    fn write_i64(&mut self, i: i64) {
        self.write_u64(i as u64)
    }

    fn write_i128(&mut self, i: i128) {
        self.write_u128(i as u128)
    }

    fn write_isize(&mut self, i: isize) {
        self.write_usize(i as usize)
    }
}

impl TryFrom<MessageDigest> for HashKind {
    type Error = crate::Error;

    fn try_from(value: MessageDigest) -> Result<Self> {
        let nid = value.type_();
        if Nid::SHA256 == nid {
            Ok(HashKind::Sha2_256)
        } else if Nid::SHA512 == nid {
            Ok(HashKind::Sha2_512)
        } else {
            Err(bterr!("Unsupported MessageDigest with NID: {:?}", nid))
        }
    }
}

impl From<HashKind> for MessageDigest {
    fn from(kind: HashKind) -> Self {
        match kind {
            HashKind::Sha2_256 => MessageDigest::sha256(),
            HashKind::Sha2_512 => MessageDigest::sha512(),
        }
    }
}

/// A [HashOp] which produces a [VarHash].
pub struct VarHashOp {
    kind: HashKind,
    hasher: Hasher,
}

impl VarHashOp {
    pub fn new(arg: HashKind) -> Result<Self> {
        let hasher = Hasher::new(arg.into())?;
        Ok(VarHashOp { kind: arg, hasher })
    }
}

impl Op for VarHashOp {
    fn update(&mut self, data: &[u8]) -> Result<()> {
        Ok(self.hasher.update(data)?)
    }

    fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
        btensure!(
            buf.len() >= self.kind.len(),
            bterr!(Error::IncorrectSize {
                expected: self.kind.len(),
                actual: buf.len(),
            })
        );
        let digest = self.hasher.finish()?;
        let slice = digest.as_ref();
        buf.copy_from_slice(slice);
        Ok(slice.len())
    }
}

impl HashOp for VarHashOp {
    type Hash = VarHash;

    fn kind(&self) -> HashKind {
        self.kind
    }

    fn finish(&mut self) -> Result<Self::Hash> {
        let digest = self.hasher.finish()?;
        let mut hash: VarHash = self.kind.into();
        hash.as_mut().copy_from_slice(digest.as_ref());
        Ok(hash)
    }
}

/// A cryptographic signature.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Default)]
pub struct Signature {
    kind: Sign,
    data: Vec<u8>,
}

impl Signature {
    pub fn new(kind: Sign, data: Vec<u8>) -> Self {
        Self { kind, data }
    }

    pub fn empty(kind: Sign) -> Signature {
        let data = vec![0; kind.key_len() as usize];
        Signature { kind, data }
    }

    pub fn copy_from(kind: Sign, from: &[u8]) -> Signature {
        let mut data = vec![0; kind.key_len() as usize];
        data.as_mut_slice().copy_from_slice(from);
        Signature { kind, data }
    }

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

    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        self.data.as_mut_slice()
    }

    pub fn scheme(&self) -> Sign {
        self.kind
    }

    pub fn take_data(self) -> Vec<u8> {
        self.data
    }
}

impl AsRef<[u8]> for Signature {
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl AsMut<[u8]> for Signature {
    fn as_mut(&mut self) -> &mut [u8] {
        self.as_mut_slice()
    }
}

#[derive(Serialize, Deserialize)]
pub struct TaggedCiphertext<T, U> {
    aad: U,
    ciphertext: Ciphertext<T>,
    tag: Vec<u8>,
}

#[derive(EnumDiscriminants, ZeroizeOnDrop, Serialize, Deserialize, PartialEq, Eq)]
#[strum_discriminants(name(AeadKeyKind))]
#[strum_discriminants(derive(Serialize, Deserialize))]
pub enum AeadKey {
    AesGcm256 {
        key: [u8; AeadKeyKind::AesGcm256.key_len()],
        iv: [u8; AeadKeyKind::AesGcm256.iv_len()],
    },
}

impl AeadKeyKind {
    const fn key_len(self) -> usize {
        match self {
            AeadKeyKind::AesGcm256 => 32,
        }
    }

    const fn iv_len(self) -> usize {
        match self {
            AeadKeyKind::AesGcm256 => 16,
        }
    }
}

#[derive(Serialize, Deserialize)]
/// Parameters used to derive cryptographic keys from passwords.
pub struct DerivationParams {
    iter: usize,
    hash: HashKind,
    kind: AeadKeyKind,
    salt: Vec<u8>,
    iv: Vec<u8>,
}

impl DerivationParams {
    const PBKDF2_ITER: usize = 1000000;
    const PBKDF2_HASH: HashKind = HashKind::Sha2_256;
    /// The [AeadKeyKind] of the key derived from this struct.
    pub const EXPORT_KEY_KIND: AeadKeyKind = AeadKeyKind::AesGcm256;

    /// Creates a new struct containing the default value of all parameters.
    pub fn new() -> Result<DerivationParams> {
        const_assert!(
            DerivationParams::PBKDF2_HASH.len() == DerivationParams::EXPORT_KEY_KIND.key_len()
        );
        Ok(DerivationParams {
            iter: Self::PBKDF2_ITER,
            hash: Self::PBKDF2_HASH,
            kind: Self::EXPORT_KEY_KIND,
            salt: rand_vec(Self::PBKDF2_HASH.len())?,
            iv: rand_vec(Self::EXPORT_KEY_KIND.iv_len())?,
        })
    }

    /// Returns an HMAC of the given password based on the parameters in this struct.
    pub fn hmac(&self, password: &str) -> Result<Zeroizing<[u8; Self::EXPORT_KEY_KIND.key_len()]>> {
        let mut key = Zeroizing::new([0u8; Self::EXPORT_KEY_KIND.key_len()]);
        pbkdf2_hmac(
            password.as_bytes(),
            self.salt.as_slice(),
            self.iter,
            self.hash.into(),
            key.as_mut_slice(),
        )?;
        Ok(key)
    }

    /// Derives an [AeadKey] from the given password using the parameters in this struct.
    fn derive_key(&self, password: &str) -> Result<AeadKey> {
        let key = self.hmac(password)?;
        AeadKey::copy_components(self.kind, key.as_slice(), &self.iv)
    }
}

fn array_from<const N: usize>(slice: &[u8]) -> Result<[u8; N]> {
    let slice_len = slice.len();
    btensure!(
        N == slice_len,
        Error::IncorrectSize {
            actual: slice_len,
            expected: N,
        }
    );
    let mut array = [0u8; N];
    array.copy_from_slice(slice);
    Ok(array)
}

impl AeadKey {
    pub fn new(kind: AeadKeyKind) -> Result<AeadKey> {
        match kind {
            AeadKeyKind::AesGcm256 => Ok(AeadKey::AesGcm256 {
                key: rand_array()?,
                iv: rand_array()?,
            }),
        }
    }

    fn copy_components(kind: AeadKeyKind, key_buf: &[u8], iv_buf: &[u8]) -> Result<AeadKey> {
        match kind {
            AeadKeyKind::AesGcm256 => Ok(AeadKey::AesGcm256 {
                key: array_from(key_buf)?,
                iv: array_from(iv_buf)?,
            }),
        }
    }

    fn encrypt<T: Serialize + DeserializeOwned, U: Serialize + DeserializeOwned>(
        &self,
        aad: U,
        plaintext: &T,
    ) -> Result<TaggedCiphertext<T, U>> {
        let (cipher, key, iv, mut tag) = match self {
            AeadKey::AesGcm256 { key, iv } => (
                Cipher::aes_256_gcm(),
                key.as_slice(),
                iv.as_slice(),
                vec![0u8; 16],
            ),
        };

        let aad_data = to_vec(&aad)?;
        let plaintext_buf = to_vec(&plaintext)?;
        let mut ciphertext = vec![0u8; plaintext_buf.len() + cipher.block_size()];
        let mut crypter = Crypter::new(cipher, Mode::Encrypt, key, Some(iv))?;
        crypter.aad_update(&aad_data)?;
        let mut count = crypter.update(&plaintext_buf, &mut ciphertext)?;
        count += crypter.finalize(&mut ciphertext[count..])?;
        ciphertext.truncate(count);
        crypter.get_tag(&mut tag)?;

        Ok(TaggedCiphertext {
            aad,
            ciphertext: Ciphertext::new(ciphertext),
            tag,
        })
    }

    fn decrypt<T: Serialize + DeserializeOwned, U: Serialize + DeserializeOwned>(
        &self,
        tagged: &TaggedCiphertext<T, U>,
    ) -> Result<T> {
        let ciphertext = &tagged.ciphertext.data;
        let (cipher, key, iv) = match self {
            AeadKey::AesGcm256 { key, iv } => {
                (Cipher::aes_256_gcm(), key.as_slice(), iv.as_slice())
            }
        };

        let mut plaintext = vec![0u8; ciphertext.len() + cipher.block_size()];
        let mut crypter = Crypter::new(cipher, Mode::Decrypt, key, Some(iv))?;
        crypter.set_tag(&tagged.tag)?;
        let aad_buf = to_vec(&tagged.aad)?;
        crypter.aad_update(&aad_buf)?;
        let mut count = crypter.update(ciphertext, &mut plaintext)?;
        count += crypter.finalize(&mut plaintext[count..])?;
        plaintext.truncate(count);

        Ok(from_vec(&plaintext)?)
    }
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, EnumDiscriminants, ZeroizeOnDrop)]
#[strum_discriminants(name(SymKeyKind))]
pub enum SymKey {
    /// A key for the AES 256 cipher in Cipher Block Chaining mode. Note that this includes the
    /// initialization vector, so that a value of this variant contains all the information needed
    /// to fully initialize a cipher context.
    Aes256Cbc { key: [u8; 32], iv: [u8; 16] },
    /// A key for the AES 256 cipher in counter mode.
    Aes256Ctr { key: [u8; 32], iv: [u8; 16] },
}

struct SymParams<'a> {
    cipher: Cipher,
    key: &'a [u8],
    iv: Option<&'a [u8]>,
}

impl SymKey {
    pub(crate) fn generate(kind: SymKeyKind) -> Result<SymKey> {
        match kind {
            SymKeyKind::Aes256Cbc => Ok(SymKey::Aes256Cbc {
                key: rand_array()?,
                iv: rand_array()?,
            }),
            SymKeyKind::Aes256Ctr => Ok(SymKey::Aes256Ctr {
                key: rand_array()?,
                iv: rand_array()?,
            }),
        }
    }

    fn params(&self) -> SymParams {
        let (cipher, key, iv) = match self {
            SymKey::Aes256Cbc { key, iv } => (Cipher::aes_256_cbc(), key, Some(iv.as_slice())),
            SymKey::Aes256Ctr { key, iv } => (Cipher::aes_256_ctr(), key, Some(iv.as_slice())),
        };
        SymParams { cipher, key, iv }
    }

    fn block_size(&self) -> usize {
        let SymParams { cipher, .. } = self.params();
        cipher.block_size()
    }

    // The number of bytes that the plaintext expands by when encrypted.
    fn expansion_sz(&self) -> usize {
        match self {
            SymKey::Aes256Cbc { .. } => 16,
            SymKey::Aes256Ctr { .. } => 0,
        }
    }

    pub fn key_slice(&self) -> &[u8] {
        let SymParams { key, .. } = self.params();
        key
    }

    pub fn iv_slice(&self) -> Option<&[u8]> {
        let SymParams { iv, .. } = self.params();
        iv
    }
}

impl Encrypter for SymKey {
    fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        let SymParams { cipher, key, iv } = self.params();
        Ok(openssl_encrypt(cipher, key, iv, slice)?)
    }
}

impl Decrypter for SymKey {
    fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        let SymParams { cipher, key, iv } = self.params();
        Ok(openssl_decrypt(cipher, key, iv, slice)?)
    }
}

#[allow(clippy::derivable_impls)]
impl Default for SymKeyKind {
    fn default() -> Self {
        SymKeyKind::Aes256Ctr
    }
}

#[repr(u32)]
#[derive(Debug, Display, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum BitLen {
    Bits128 = 16,
    Bits256 = 32,
    Bits512 = 64,
    Bits2048 = 256,
    Bits3072 = 384,
    Bits4096 = 512,
}

impl BitLen {
    const fn bits(self) -> u32 {
        8 * self as u32
    }

    fn try_from_u32(value: u32) -> Result<Self> {
        match value {
            16 => Ok(Self::Bits128),
            32 => Ok(Self::Bits256),
            64 => Ok(Self::Bits512),
            256 => Ok(Self::Bits2048),
            384 => Ok(Self::Bits3072),
            512 => Ok(Self::Bits4096),
            _ => Err(bterr!("invalid KeyLen value: {value}")),
        }
    }
}

impl TryFrom<u32> for BitLen {
    type Error = crate::Error;
    fn try_from(value: u32) -> std::result::Result<Self, Self::Error> {
        Self::try_from_u32(value)
    }
}

/// A Cryptographic Scheme. This is a common type for operations such as encrypting, decrypting,
/// signing and verifying.
pub trait Scheme:
    DeserializeOwned + Serialize + Copy + std::fmt::Debug + PartialEq + Into<Self::Kind>
{
    type Kind: Scheme;
    fn as_enum(self) -> SchemeKind;
    fn hash_kind(&self) -> HashKind;
    fn padding(&self) -> Option<OpensslPadding>;
    fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>>;
    fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>>;
    fn generate(self) -> Result<AsymKeyPair<Self::Kind>>;
    fn key_len(self) -> BitLen;

    fn message_digest(&self) -> MessageDigest {
        self.hash_kind().into()
    }
}

pub enum SchemeKind {
    Sign(Sign),
    Encrypt(Encrypt),
}

#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
pub enum Encrypt {
    RsaEsOaep(RsaEsOaep),
}

impl Scheme for Encrypt {
    type Kind = Encrypt;

    fn as_enum(self) -> SchemeKind {
        SchemeKind::Encrypt(self)
    }

    fn hash_kind(&self) -> HashKind {
        match self {
            Encrypt::RsaEsOaep(inner) => inner.hash_kind(),
        }
    }

    fn padding(&self) -> Option<OpensslPadding> {
        match self {
            Encrypt::RsaEsOaep(inner) => inner.padding(),
        }
    }

    fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
        match self {
            Encrypt::RsaEsOaep(inner) => inner.public_from_der(der),
        }
    }

    fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
        match self {
            Encrypt::RsaEsOaep(inner) => inner.private_from_der(der),
        }
    }

    fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
        match self {
            Encrypt::RsaEsOaep(inner) => inner.generate(),
        }
    }

    fn key_len(self) -> BitLen {
        match self {
            Encrypt::RsaEsOaep(inner) => inner.key_len(),
        }
    }
}

impl Encrypt {
    pub const RSA_OAEP_2048_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
        key_len: BitLen::Bits2048,
        hash_kind: HashKind::Sha2_256,
    });

    pub const RSA_OAEP_3072_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
        key_len: BitLen::Bits3072,
        hash_kind: HashKind::Sha2_256,
    });
}

#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
pub enum Sign {
    RsaSsaPss(RsaSsaPss),
}

impl Default for Sign {
    fn default() -> Self {
        Self::RSA_PSS_2048_SHA_256
    }
}

impl Scheme for Sign {
    type Kind = Sign;

    fn as_enum(self) -> SchemeKind {
        SchemeKind::Sign(self)
    }

    fn hash_kind(&self) -> HashKind {
        match self {
            Sign::RsaSsaPss(inner) => inner.hash_kind(),
        }
    }

    fn padding(&self) -> Option<OpensslPadding> {
        match self {
            Sign::RsaSsaPss(inner) => inner.padding(),
        }
    }

    fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
        match self {
            Sign::RsaSsaPss(inner) => inner.public_from_der(der),
        }
    }

    fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
        match self {
            Sign::RsaSsaPss(inner) => inner.private_from_der(der),
        }
    }

    fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
        match self {
            Sign::RsaSsaPss(inner) => inner.generate(),
        }
    }

    fn key_len(self) -> BitLen {
        self.key_len_const()
    }
}

impl Sign {
    pub const RSA_PSS_2048_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
        key_bits: BitLen::Bits2048,
        hash_kind: HashKind::Sha2_256,
    });

    pub const RSA_PSS_3072_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
        key_bits: BitLen::Bits3072,
        hash_kind: HashKind::Sha2_256,
    });

    const fn key_len_const(self) -> BitLen {
        match self {
            Sign::RsaSsaPss(inner) => inner.key_bits,
        }
    }
}

enum Rsa {}

impl Rsa {
    /// The default public exponent to use for generated RSA keys.
    const EXP: u32 = 65537; // 2**16 + 1

    fn generate<S: Scheme>(scheme: S) -> Result<AsymKeyPair<S>> {
        let key = OsslRsa::generate(scheme.key_len().bits())?;
        // TODO: Separating the keys this way seems inefficient. Investigate alternatives.
        let public_der = key.public_key_to_der()?;
        let private_der = key.private_key_to_der()?;
        let public = AsymKey::<Public, S>::new(scheme, &public_der)?;
        let private = AsymKey::<Private, S>::new(scheme, &private_der)?;
        Ok(AsymKeyPair { public, private })
    }
}

#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
pub struct RsaEsOaep {
    key_len: BitLen,
    hash_kind: HashKind,
}

impl Scheme for RsaEsOaep {
    type Kind = Encrypt;

    fn as_enum(self) -> SchemeKind {
        SchemeKind::Encrypt(self.into())
    }

    fn hash_kind(&self) -> HashKind {
        self.hash_kind
    }

    fn padding(&self) -> Option<OpensslPadding> {
        Some(OpensslPadding::PKCS1_OAEP)
    }

    fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
        Ok(PKey::public_key_from_der(der)?.conv_pub())
    }

    fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
        Ok(PKey::private_key_from_der(der)?.conv_priv())
    }

    fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
        Rsa::generate(self.into())
    }

    fn key_len(self) -> BitLen {
        self.key_len
    }
}

impl From<RsaEsOaep> for Encrypt {
    fn from(scheme: RsaEsOaep) -> Self {
        Encrypt::RsaEsOaep(scheme)
    }
}

#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
pub struct RsaSsaPss {
    key_bits: BitLen,
    hash_kind: HashKind,
}

impl Scheme for RsaSsaPss {
    type Kind = Sign;

    fn as_enum(self) -> SchemeKind {
        SchemeKind::Sign(self.into())
    }

    fn hash_kind(&self) -> HashKind {
        self.hash_kind
    }

    fn padding(&self) -> Option<OpensslPadding> {
        Some(OpensslPadding::PKCS1_PSS)
    }

    fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
        Ok(PKey::public_key_from_der(der)?.conv_pub())
    }

    fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
        Ok(PKey::private_key_from_der(der)?.conv_priv())
    }

    fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
        Rsa::generate(self.into())
    }

    fn key_len(self) -> BitLen {
        self.key_bits
    }
}

impl From<RsaSsaPss> for Sign {
    fn from(scheme: RsaSsaPss) -> Self {
        Sign::RsaSsaPss(scheme)
    }
}

/// Marker trait for the `Public` and `Private` key privacy types.
pub trait KeyPrivacy {}

/// Represents keys which can be shared freely.
#[derive(Clone, Debug)]
pub enum Public {}

impl KeyPrivacy for Public {}

unsafe impl HasPublic for Public {}

#[derive(Debug, Clone)]
/// Represents keys which must be kept confidential.
pub enum Private {}

impl KeyPrivacy for Private {}

unsafe impl HasPrivate for Private {}

trait PKeyExt<T> {
    /// Converts a PKey<T> to a PKey<U>. This hack allows for converting between openssl's
    /// Public and Private types and ours.
    fn conv_pkey<U>(self) -> PKey<U>;

    /// Convert from openssl's Public type to `crypto::Public`.
    fn conv_pub(self) -> PKey<Public>;

    /// Convert from openssl's Private type to `crypto::Private`.
    fn conv_priv(self) -> PKey<Private>;
}

impl<T> PKeyExt<T> for PKey<T> {
    fn conv_pkey<U>(self) -> PKey<U> {
        let ptr = self.as_ptr();
        let new_pkey = unsafe { PKey::from_ptr(ptr) };
        std::mem::forget(self);
        new_pkey
    }

    fn conv_pub(self) -> PKey<Public> {
        self.conv_pkey()
    }

    fn conv_priv(self) -> PKey<Private> {
        self.conv_pkey()
    }
}

/// Represents any kind of asymmetric key.
#[derive(Debug, Clone)]
pub struct AsymKey<P, S> {
    scheme: S,
    pkey: PKey<P>,
}

impl<P, S: Copy> AsymKey<P, S> {
    pub fn scheme(&self) -> S {
        self.scheme
    }
}

pub type AsymKeyPub<S> = AsymKey<Public, S>;

impl<S: Scheme> AsymKey<Public, S> {
    pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Public, S>> {
        let pkey = scheme.public_from_der(der)?;
        Ok(AsymKey { scheme, pkey })
    }
}

impl<S: Scheme> AsymKey<Private, S> {
    pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Private, S>> {
        let pkey = scheme.private_from_der(der)?;
        Ok(AsymKey { scheme, pkey })
    }

    pub fn to_der(&self) -> Result<Vec<u8>> {
        self.pkey.private_key_to_der().map_err(|err| err.into())
    }
}

macro_rules! impl_asym_key_serialize {
    ($privacy:ty, $ser_lambda:expr) => {
        impl<S: Scheme> Serialize for AsymKey<$privacy, S> {
            fn serialize<T: Serializer>(&self, s: T) -> std::result::Result<T::Ok, T::Error> {
                let mut struct_s = s.serialize_struct(stringify!(AsymKey), 2)?;
                struct_s.serialize_field("scheme", &self.scheme)?;
                let der = $ser_lambda(&self.pkey).map_err(T::Error::custom)?;
                struct_s.serialize_field("pkey", der.as_slice())?;
                struct_s.end()
            }
        }
    };
}

impl_asym_key_serialize!(Public, |pkey: &PKey<Public>| pkey.public_key_to_der());
impl_asym_key_serialize!(Private, |pkey: &PKey<Private>| pkey.private_key_to_der());

macro_rules! impl_asym_key_deserialize {
    ($privacy:ty) => {
        impl<'de, S: Scheme> Deserialize<'de> for AsymKey<$privacy, S> {
            fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
                const FIELDS: &[&str] = &["scheme", "pkey"];

                struct StructVisitor<S: Scheme>(PhantomData<S>);

                impl<'de, S: Scheme> Visitor<'de> for StructVisitor<S> {
                    type Value = AsymKey<$privacy, S>;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_fmt(format_args!("struct {}", stringify!(AsymKey)))
                    }

                    fn visit_seq<V: SeqAccess<'de>>(
                        self,
                        mut seq: V,
                    ) -> std::result::Result<Self::Value, V::Error> {
                        let scheme: S = seq
                            .next_element()?
                            .ok_or_else(|| de::Error::missing_field(FIELDS[0]))?;
                        let der: Vec<u8> = seq
                            .next_element()?
                            .ok_or_else(|| de::Error::missing_field(FIELDS[1]))?;
                        AsymKey::<$privacy, _>::new(scheme, der.as_slice())
                            .map_err(de::Error::custom)
                    }
                }

                d.deserialize_struct(stringify!(AsymKey), FIELDS, StructVisitor(PhantomData))
            }
        }
    };
}

impl_asym_key_deserialize!(Public);
impl_asym_key_deserialize!(Private);

impl<S: Scheme> PartialEq for AsymKey<Public, S> {
    fn eq(&self, other: &Self) -> bool {
        self.scheme == other.scheme && self.pkey.public_eq(&other.pkey)
    }
}

impl Principaled for AsymKey<Public, Sign> {
    fn principal_of_kind(&self, kind: HashKind) -> Principal {
        let der = self.pkey.public_key_to_der().unwrap();
        let bytes = hash(kind.into(), der.as_slice()).unwrap();
        let mut hash_buf = VarHash::from(kind);
        hash_buf.as_mut().copy_from_slice(&bytes);
        Principal(hash_buf)
    }
}

impl Encrypter for AsymKey<Public, Encrypt> {
    fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        let mut encrypter = OsslEncrypter::new(&self.pkey)?;
        if let Some(padding) = self.scheme.padding() {
            encrypter.set_rsa_padding(padding)?;
        }
        {
            let Encrypt::RsaEsOaep(inner) = self.scheme;
            encrypter.set_rsa_oaep_md(inner.message_digest())?;
        }
        let buffer_len = encrypter.encrypt_len(slice)?;
        let mut ciphertext = vec![0; buffer_len];
        let ciphertext_len = encrypter.encrypt(slice, &mut ciphertext)?;
        ciphertext.truncate(ciphertext_len);
        Ok(ciphertext)
    }
}

impl Decrypter for AsymKey<Private, Encrypt> {
    fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        let mut decrypter = OsslDecrypter::new(&self.pkey)?;
        if let Some(padding) = self.scheme.padding() {
            decrypter.set_rsa_padding(padding)?;
        }
        {
            let Encrypt::RsaEsOaep(inner) = self.scheme;
            decrypter.set_rsa_oaep_md(inner.message_digest())?;
        }
        let buffer_len = decrypter.decrypt_len(slice)?;
        let mut plaintext = vec![0; buffer_len];
        let plaintext_len = decrypter.decrypt(slice, &mut plaintext)?;
        plaintext.truncate(plaintext_len);
        Ok(plaintext)
    }
}

impl Signer for AsymKey<Private, Sign> {
    fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
        let op = OsslSignOp::new((self.scheme, self.pkey.as_ref()))?;
        Ok(Box::new(op))
    }

    fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
        let mut signer = OsslSigner::new(self.scheme.message_digest(), &self.pkey)?;
        if let Some(padding) = self.scheme.padding() {
            signer.set_rsa_padding(padding)?;
        }
        for part in parts {
            signer.update(part)?;
        }
        let mut signature = Signature::empty(self.scheme);
        signer.sign(signature.as_mut_slice())?;
        Ok(signature)
    }

    fn kind(&self) -> Sign {
        self.scheme
    }
}

impl Verifier for AsymKey<Public, Sign> {
    fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>> {
        let op = OsslVerifyOp::init(self.scheme, self.pkey.as_ref())?;
        Ok(Box::new(op))
    }

    fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
        let mut verifier = OsslVerifier::new(self.scheme.message_digest(), &self.pkey)?;
        if let Some(padding) = self.scheme.padding() {
            verifier.set_rsa_padding(padding)?;
        }
        for part in parts {
            verifier.update(part)?;
        }
        if verifier.verify(signature)? {
            Ok(())
        } else {
            Err(bterr!(Error::InvalidSignature))
        }
    }

    fn kind(&self) -> Sign {
        self.scheme
    }
}

#[derive(Clone, Serialize)]
pub struct AsymKeyPair<S: Scheme> {
    public: AsymKey<Public, S>,
    private: AsymKey<Private, S>,
}

impl<'de, S: Scheme> Deserialize<'de> for AsymKeyPair<S> {
    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        const FIELDS: &[&str] = &["public", "private"];

        struct StructVisitor<S: Scheme>(PhantomData<S>);

        impl<'de, S: Scheme> Visitor<'de> for StructVisitor<S> {
            type Value = AsymKeyPair<S>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_fmt(format_args!("struct {}", stringify!(AsymKeyPair)))
            }

            fn visit_seq<V: SeqAccess<'de>>(
                self,
                mut seq: V,
            ) -> std::result::Result<Self::Value, V::Error> {
                let public: AsymKey<Public, S> = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::missing_field(FIELDS[0]))?;
                let private: AsymKey<Private, S> = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::missing_field(FIELDS[1]))?;
                Ok(AsymKeyPair { public, private })
            }
        }

        d.deserialize_struct(stringify!(AsymKey), FIELDS, StructVisitor(PhantomData))
    }
}

impl<S: Scheme> AsymKeyPair<S> {
    pub fn new(scheme: S, public_der: &[u8], private_der: &[u8]) -> Result<AsymKeyPair<S>> {
        let public = AsymKey::<Public, _>::new(scheme, public_der)?;
        let private = AsymKey::<Private, _>::new(scheme, private_der)?;
        Ok(AsymKeyPair { public, private })
    }

    pub fn public(&self) -> &AsymKey<Public, S> {
        &self.public
    }

    pub fn private(&self) -> &AsymKey<Private, S> {
        &self.private
    }
}

// Note that only signing keys are associated with a Principal.
impl Principaled for AsymKeyPair<Sign> {
    fn principal_of_kind(&self, kind: HashKind) -> Principal {
        self.public.principal_of_kind(kind)
    }
}

impl Encrypter for AsymKeyPair<Encrypt> {
    fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        self.public.encrypt(slice)
    }
}

impl Decrypter for AsymKeyPair<Encrypt> {
    fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        self.private.decrypt(slice)
    }
}

impl Signer for AsymKeyPair<Sign> {
    fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
        self.private.init_sign()
    }
    fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
        self.private.sign(parts)
    }
    fn kind(&self) -> Sign {
        self.private.kind()
    }
}

impl Verifier for AsymKeyPair<Sign> {
    fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>> {
        self.public.init_verify()
    }

    fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
        self.public.verify(parts, signature)
    }

    fn kind(&self) -> Sign {
        self.public.kind()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConcretePub {
    pub sign: AsymKeyPub<Sign>,
    pub enc: AsymKeyPub<Encrypt>,
}

impl Principaled for ConcretePub {
    fn principal_of_kind(&self, kind: HashKind) -> Principal {
        self.sign.principal_of_kind(kind)
    }
}

impl Encrypter for ConcretePub {
    fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        self.enc.encrypt(slice)
    }
}

impl Verifier for ConcretePub {
    fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>> {
        self.sign.init_verify()
    }

    fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
        self.sign.verify(parts, signature)
    }

    fn kind(&self) -> Sign {
        self.sign.kind()
    }
}

impl CredsPub for ConcretePub {
    fn public_sign(&self) -> &AsymKey<Public, Sign> {
        &self.sign
    }

    fn concrete_pub(&self) -> ConcretePub {
        self.clone()
    }
}

impl PartialEq for ConcretePub {
    fn eq(&self, other: &Self) -> bool {
        self.principal() == other.principal()
    }
}

#[derive(Clone, Serialize, Deserialize)]
pub struct ConcreteCreds {
    sign: AsymKeyPair<Sign>,
    encrypt: AsymKeyPair<Encrypt>,
    writecap: Option<Writecap>,
}

impl ConcreteCreds {
    pub fn new(sign: AsymKeyPair<Sign>, encrypt: AsymKeyPair<Encrypt>) -> ConcreteCreds {
        ConcreteCreds {
            sign,
            encrypt,
            writecap: None,
        }
    }

    pub fn generate() -> Result<ConcreteCreds> {
        let encrypt = Encrypt::RSA_OAEP_3072_SHA_256.generate()?;
        let sign = Sign::RSA_PSS_3072_SHA_256.generate()?;
        Ok(ConcreteCreds {
            sign,
            encrypt,
            writecap: None,
        })
    }

    pub fn set_writecap(&mut self, writecap: Writecap) -> Result<()> {
        writecap.assert_issued_to(&self.principal())?;
        self.writecap = Some(writecap);
        Ok(())
    }

    pub fn sign_pair(&self) -> &AsymKeyPair<Sign> {
        &self.sign
    }

    pub fn encrypt_pair(&self) -> &AsymKeyPair<Encrypt> {
        &self.encrypt
    }
}

impl Verifier for ConcreteCreds {
    fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>> {
        self.sign.init_verify()
    }

    fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
        self.sign.verify(parts, signature)
    }

    fn kind(&self) -> Sign {
        Verifier::kind(&self.sign)
    }
}

impl Encrypter for ConcreteCreds {
    fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        self.encrypt.encrypt(slice)
    }
}

impl Principaled for ConcreteCreds {
    fn principal_of_kind(&self, kind: HashKind) -> Principal {
        self.sign.principal_of_kind(kind)
    }
}

impl CredsPub for ConcreteCreds {
    fn public_sign(&self) -> &AsymKey<Public, Sign> {
        &self.sign.public
    }

    fn concrete_pub(&self) -> ConcretePub {
        ConcretePub {
            sign: self.sign.public.clone(),
            enc: self.encrypt.public.clone(),
        }
    }
}

impl Signer for ConcreteCreds {
    fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
        self.sign.init_sign()
    }

    fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
        self.sign.sign(parts)
    }

    fn kind(&self) -> Sign {
        Signer::kind(&self.sign)
    }
}

impl Decrypter for ConcreteCreds {
    fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        self.encrypt.decrypt(slice)
    }
}

impl CredsPriv for ConcreteCreds {
    fn writecap(&self) -> Option<&Writecap> {
        self.writecap.as_ref()
    }
}

pub trait Encrypter {
    fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
}

impl<T: ?Sized + Encrypter, P: Deref<Target = T>> Encrypter for P {
    fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        self.deref().encrypt(slice)
    }
}

pub trait EncrypterExt: Encrypter {
    /// Serializes the given value into a new vector, then encrypts it and returns the resulting
    /// ciphertext.
    fn ser_encrypt<T: Serialize>(&self, value: &T) -> Result<Ciphertext<T>> {
        let data = to_vec(value)?;
        let data = self.encrypt(&data)?;
        Ok(Ciphertext::new(data))
    }
}

impl<T: Encrypter + ?Sized> EncrypterExt for T {}

pub trait Decrypter {
    fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
}

impl<T: ?Sized + Decrypter, P: Deref<Target = T>> Decrypter for P {
    fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
        self.deref().decrypt(slice)
    }
}

pub trait DecrypterExt: Decrypter {
    fn ser_decrypt<T: DeserializeOwned>(&self, ct: &Ciphertext<T>) -> Result<T> {
        let pt = self.decrypt(ct.data.as_slice())?;
        Ok(from_vec(&pt)?)
    }
}

impl<T: Decrypter + ?Sized> DecrypterExt for T {}

/// Represents an ongoing signing operation.
pub trait SignOp: Op {
    /// Returns the signature scheme that this operation is using.
    fn scheme(&self) -> Sign;

    /// Finishes this signature operation and returns a new signature containing the result.
    fn finish(&mut self) -> Result<Signature> {
        let scheme = self.scheme();
        let mut sig = Signature::empty(scheme);
        self.finish_into(sig.as_mut())?;
        Ok(sig)
    }
}

impl<T: ?Sized + SignOp, P: DerefMut<Target = T>> SignOp for P {
    fn scheme(&self) -> Sign {
        self.deref().scheme()
    }
}

pub struct OsslSignOp<'a> {
    signer: OsslSigner<'a>,
    scheme: Sign,
}

impl<'a> OsslSignOp<'a> {
    pub fn new(arg: (Sign, &'a PKeyRef<Private>)) -> Result<Self> {
        let scheme = arg.0;
        let mut signer = OsslSigner::new(arg.0.message_digest(), arg.1)?;
        if let Some(padding) = scheme.padding() {
            signer.set_rsa_padding(padding)?;
        }
        Ok(OsslSignOp { signer, scheme })
    }
}

impl<'a> Op for OsslSignOp<'a> {
    fn update(&mut self, data: &[u8]) -> Result<()> {
        Ok(self.signer.update(data)?)
    }

    fn finish_into(&mut self, buf: &mut [u8]) -> Result<usize> {
        Ok(self.signer.sign(buf)?)
    }
}

impl<'a> SignOp for OsslSignOp<'a> {
    fn scheme(&self) -> Sign {
        self.scheme
    }
}

/// A struct which computes a signature over data as it is written to it.
pub struct SignWrite<T, Op> {
    inner: T,
    op: Op,
}

impl<T, Op: SignOp> SignWrite<T, Op> {
    pub fn new(inner: T, op: Op) -> Self {
        SignWrite { inner, op }
    }

    pub fn finish_into(mut self, buf: &mut [u8]) -> Result<(usize, T)> {
        Ok((self.op.finish_into(buf)?, self.inner))
    }

    pub fn finish(mut self) -> Result<(Signature, T)> {
        Ok((self.op.finish()?, self.inner))
    }
}

impl<T: Write, Op: SignOp> Write for SignWrite<T, Op> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.op.update(buf)?;
        self.inner.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

pub trait Signer {
    /// Starts a new signing operation and returns the struct representing it.
    fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>>;

    /// Returns a signature over the given parts. It's critical that subsequent invocations
    /// of this method on the same instance return a [Signature] with `data` fields of the same
    /// length.
    fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature>;

    fn sign_writecap(&self, writecap: &mut Writecap) -> Result<()> {
        let signed = self.ser_sign(&writecap.body)?;
        writecap.signature = signed.sig;
        Ok(())
    }

    fn kind(&self) -> Sign;
}

impl<T: ?Sized + Signer> Signer for &T {
    fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
        (*self).init_sign()
    }

    fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
        (*self).sign(parts)
    }

    fn kind(&self) -> Sign {
        (*self).kind()
    }
}

impl<T: ?Sized + Signer> Signer for Arc<T> {
    fn init_sign(&self) -> Result<Box<dyn '_ + SignOp>> {
        self.deref().init_sign()
    }

    fn sign(&self, parts: &mut dyn Iterator<Item = &[u8]>) -> Result<Signature> {
        self.deref().sign(parts)
    }

    fn kind(&self) -> Sign {
        self.deref().kind()
    }
}

pub trait SignerExt: Signer {
    fn ser_sign<T: Serialize>(&self, value: &T) -> Result<Signed<T>> {
        let data = to_vec(value)?;
        let sig = self.sign(&mut std::iter::once(data.as_slice()))?;
        Ok(Signed::new(data, sig))
    }

    fn ser_sign_into<T: Serialize>(&self, value: &T, buf: &mut Vec<u8>) -> Result<Signature> {
        write_to(value, &mut *buf)?;
        self.sign(&mut std::iter::once(buf.as_slice()))
    }
}

impl<T: ?Sized + Signer> SignerExt for T {}

pub trait VerifyOp {
    fn update(&mut self, data: &[u8]) -> Result<()>;

    fn finish(&mut self, sig: &[u8]) -> Result<()>;

    fn scheme(&self) -> Sign;
}

impl<T: ?Sized + VerifyOp, P: DerefMut<Target = T>> VerifyOp for P {
    fn update(&mut self, data: &[u8]) -> Result<()> {
        self.deref_mut().update(data)
    }

    fn finish(&mut self, sig: &[u8]) -> Result<()> {
        self.deref_mut().finish(sig)
    }

    fn scheme(&self) -> Sign {
        self.deref().scheme()
    }
}

pub struct OsslVerifyOp<'a> {
    verifier: OsslVerifier<'a>,
    scheme: Sign,
}

impl<'a> OsslVerifyOp<'a> {
    pub fn init(scheme: Sign, pkey: &'a PKeyRef<Public>) -> Result<Self> {
        let mut verifier = OsslVerifier::new(scheme.message_digest(), pkey)?;
        if let Some(padding) = scheme.padding() {
            verifier.set_rsa_padding(padding)?;
        }
        Ok(OsslVerifyOp { verifier, scheme })
    }
}

impl<'a> VerifyOp for OsslVerifyOp<'a> {
    fn update(&mut self, data: &[u8]) -> Result<()> {
        Ok(self.verifier.update(data)?)
    }

    fn finish(&mut self, sig: &[u8]) -> Result<()> {
        match self.verifier.verify(sig) {
            Ok(true) => Ok(()),
            Ok(false) => Err(bterr!(Error::InvalidSignature)),
            Err(err) => Err(err.into()),
        }
    }

    fn scheme(&self) -> Sign {
        self.scheme
    }
}

pub struct VerifyRead<T, Op> {
    inner: T,
    op: Op,
    update_failed: bool,
}

impl<T: Read, Op: VerifyOp> VerifyRead<T, Op> {
    pub fn new(inner: T, op: Op) -> Self {
        VerifyRead {
            inner,
            op,
            update_failed: false,
        }
    }

    pub fn finish(mut self, sig: &[u8]) -> std::result::Result<T, (T, crate::Error)> {
        if self.update_failed {
            return Err((
                self.inner,
                bterr!("VerifyRead::finish: update_failed was true"),
            ));
        }
        match self.op.finish(sig) {
            Ok(_) => Ok(self.inner),
            Err(err) => Err((self.inner, err)),
        }
    }
}

impl<T: Read, Op: VerifyOp> Read for VerifyRead<T, Op> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.update_failed {
            return Err(bterr!("VerifyRead::read update previously failed").into());
        }
        let read = self.inner.read(buf)?;
        if read > 0 {
            if let Err(err) = self.op.update(&buf[..read]) {
                self.update_failed = true;
                error!("VerifyRead::read failed to update VerifyOp: {err}");
            }
        }
        Ok(read)
    }
}

pub trait Verifier {
    fn init_verify(&self) -> Result<Box<dyn '_ + VerifyOp>>;

    fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()>;

    fn kind(&self) -> Sign;
}

impl<V: ?Sized + Verifier> Verifier for &V {
    fn init_verify<'a>(&'a self) -> Result<Box<dyn 'a + VerifyOp>> {
        (*self).init_verify()
    }

    fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
        (*self).verify(parts, signature)
    }

    fn kind(&self) -> Sign {
        (*self).kind()
    }
}

impl<V: ?Sized + Verifier> Verifier for Arc<V> {
    fn init_verify<'a>(&'a self) -> Result<Box<dyn 'a + VerifyOp>> {
        self.deref().init_verify()
    }

    fn verify(&self, parts: &mut dyn Iterator<Item = &[u8]>, signature: &[u8]) -> Result<()> {
        self.deref().verify(parts, signature)
    }

    fn kind(&self) -> Sign {
        self.deref().kind()
    }
}

pub trait VerifierExt: Verifier {
    fn ser_verify<T: Serialize>(&self, value: &T, signature: &[u8]) -> Result<()>;
}

impl<V: ?Sized + Verifier> VerifierExt for V {
    fn ser_verify<T: Serialize>(&self, value: &T, signature: &[u8]) -> Result<()> {
        let data = to_vec(value)?;
        self.verify(&mut std::iter::once(data.as_slice()), signature)
    }
}

/// Trait for types which can be used as public credentials.
pub trait CredsPub: Verifier + Encrypter + Principaled {
    /// Returns a reference to the public signing key which can be used to verify signatures.
    fn public_sign(&self) -> &AsymKey<Public, Sign>;

    fn concrete_pub(&self) -> ConcretePub;

    fn sign_kind(&self) -> Sign {
        Verifier::kind(self)
    }
}

impl<T: ?Sized + CredsPub> CredsPub for &T {
    fn public_sign(&self) -> &AsymKey<Public, Sign> {
        (*self).public_sign()
    }

    fn concrete_pub(&self) -> ConcretePub {
        (*self).concrete_pub()
    }
}

impl<T: ?Sized + CredsPub> CredsPub for Arc<T> {
    fn public_sign(&self) -> &AsymKey<Public, Sign> {
        self.deref().public_sign()
    }

    fn concrete_pub(&self) -> ConcretePub {
        self.deref().concrete_pub()
    }
}

/// Trait for types which contain private credentials.
pub trait CredsPriv: Decrypter + Signer {
    /// Returns a reference to the writecap associated with these credentials, if one has been
    /// issued.
    fn writecap(&self) -> Option<&Writecap>;

    fn sign_kind(&self) -> Sign {
        Signer::kind(self)
    }

    /// Returns the path these credentials are authorized to bind to according,
    /// as specified by their [Writecap]. If these creds haven't been issued a [Writecap], then
    /// an `Err` variant containing [BlockError::MissingWritecap] is returned.
    fn bind_path(&self) -> Result<BlockPath> {
        Ok(self
            .writecap()
            .ok_or(BlockError::MissingWritecap)?
            .bind_path())
    }
}

impl<T: ?Sized + CredsPriv> CredsPriv for &T {
    fn writecap(&self) -> Option<&Writecap> {
        (*self).writecap()
    }
}

impl<T: ?Sized + CredsPriv> CredsPriv for Arc<T> {
    fn writecap(&self) -> Option<&Writecap> {
        self.deref().writecap()
    }
}

/// Trait for types which contain both public and private credentials.
pub trait Creds: CredsPriv + CredsPub + Send + Sync {
    fn issue_writecap(
        &self,
        issued_to: Principal,
        path_components: &mut dyn Iterator<Item = &str>,
        expires: Epoch,
    ) -> Result<Writecap> {
        // The root principal is given by the path in our writecap, or if we don't have a writecap,
        // then we assume we are the root principal.
        let root_principal = self
            .writecap()
            .map(|e| e.root_principal())
            .unwrap_or_else(|| self.principal());
        let path = BlockPath::from_components(root_principal, path_components);
        let body = WritecapBody {
            issued_to,
            path,
            expires,
            signing_key: self.public_sign().to_owned(),
        };
        let signed = self.ser_sign(&body)?;
        Ok(Writecap {
            body,
            signature: signed.sig,
            next: self.writecap().map(|e| Box::new(e.to_owned())),
        })
    }

    fn pub_sign_kind(&self) -> Sign {
        CredsPub::sign_kind(self)
    }

    fn priv_sign_kind(&self) -> Sign {
        CredsPriv::sign_kind(self)
    }
}

impl<C: ?Sized + CredsPriv + CredsPub + Send + Sync> Creds for C {}

/// A trait for types which store credentials.
pub trait CredStore {
    /// The type of the credential handle returned by this store.
    type CredHandle: 'static + Creds;
    /// The type of the exported credentials returned by this store.
    type ExportedCreds: 'static + Serialize + DeserializeOwned;

    /// Returns the node credentials. If credentials haven't been generated, they are generated
    /// stored and returned.
    fn node_creds(&self) -> Result<Self::CredHandle>;
    /// Returns the root credentials. If no root credentials have been generated, or the provided
    /// password is incorrect, then an error is returned.
    fn root_creds(&self, password: &str) -> Result<Self::CredHandle>;
    /// Returns a public key which can be used to encrypt data intended only to be accessed by this
    /// node. The returned key can be given as the `new_parent` parameter to the
    /// [CredStore::export_root_creds] method.
    fn storage_key(&self) -> Result<AsymKeyPub<Encrypt>>;
    /// Exports the root credentials. These can be serialized and persisted external to the
    /// application and later loaded and deserialized and passed to the
    /// [CredStoreMut::import_root_creds] method.
    /// The `password` argument must match the value provided when the [CredStore::root_creds]
    /// method was called. The `new_parent` argument is the public key of the node that is to import
    /// the root key, which can be obtained using the [CredStoreMut::gen_root_creds] method on the
    /// importing node.
    fn export_root_creds(
        &self,
        root_creds: &Self::CredHandle,
        password: &str,
        new_parent: &AsymKeyPub<Encrypt>,
    ) -> Result<Self::ExportedCreds>;
}

impl<T: ?Sized + CredStore, P: Deref<Target = T>> CredStore for P {
    type CredHandle = T::CredHandle;
    type ExportedCreds = T::ExportedCreds;

    fn node_creds(&self) -> Result<Self::CredHandle> {
        self.deref().node_creds()
    }

    fn root_creds(&self, password: &str) -> Result<Self::CredHandle> {
        self.deref().root_creds(password)
    }

    fn storage_key(&self) -> Result<AsymKeyPub<Encrypt>> {
        self.deref().storage_key()
    }

    fn export_root_creds(
        &self,
        root_creds: &Self::CredHandle,
        password: &str,
        new_parent: &AsymKeyPub<Encrypt>,
    ) -> Result<Self::ExportedCreds> {
        self.deref()
            .export_root_creds(root_creds, password, new_parent)
    }
}

/// An extension of [CredStore] which exposes additional methods for mutating the credential store.
pub trait CredStoreMut: CredStore {
    /// Generates the root credentials and protects them using the given password. If the root
    /// credentials have already been generated then an error is returned.
    fn gen_root_creds(&self, password: &str) -> Result<Self::CredHandle>;
    /// Imports root credentials that were previously created with [CredStore::export_root_creds].
    /// The provided password must match the value that was given to that method.
    fn import_root_creds(
        &self,
        password: &str,
        exported: Self::ExportedCreds,
    ) -> Result<Self::CredHandle>;
    /// Assigns the given [Writecap] to the node credentials referred to by the given handle.
    ///  This method is responsible for committing the given [Writecap] to durable storage.
    fn assign_node_writecap(&self, handle: &mut Self::CredHandle, writecap: Writecap)
        -> Result<()>;
    /// Assigns `writecap` to the root credentials referred to by `handle`. This method
    /// is responsible for committing the given [Writecap] to durable storage.
    fn assign_root_writecap(&self, handle: &mut Self::CredHandle, writecap: Writecap)
        -> Result<()>;

    /// Generates new root credentials protected by `password` and issues them a self-signed
    /// [Writecap] which expires after `valid_for`. The newly generated root credentials are
    /// returned.
    fn provision_root(&self, password: &str, expires: Epoch) -> Result<Self::CredHandle> {
        let mut root_creds = self.gen_root_creds(password)?;
        let writecap =
            root_creds.issue_writecap(root_creds.principal(), &mut std::iter::empty(), expires)?;
        self.assign_root_writecap(&mut root_creds, writecap)?;
        Ok(root_creds)
    }
    /// Begin the provisioning process for a node by generating a new set of node credentials. The
    /// [Principal] of the newly generated credentials is returned. This [Principal] may then be
    /// transmitted to a root node which can use it to issue a [Writecap] to this node.
    fn provision_node_start(&self) -> Result<Principal> {
        let node_creds = self.node_creds()?;
        Ok(node_creds.principal())
    }
    /// Assigns the given [Writecap] to the node credentials and commits it to durable storage.
    /// A handle to the node credentials is returned.
    fn provision_node_finish(&self, writecap: Writecap) -> Result<Self::CredHandle> {
        let mut node_creds = self.node_creds()?;
        self.assign_node_writecap(&mut node_creds, writecap)?;
        Ok(node_creds)
    }
}

impl<T: ?Sized + CredStoreMut, P: Deref<Target = T>> CredStoreMut for P {
    fn gen_root_creds(&self, password: &str) -> Result<T::CredHandle> {
        self.deref().gen_root_creds(password)
    }

    fn import_root_creds(
        &self,
        password: &str,
        exported: Self::ExportedCreds,
    ) -> Result<Self::CredHandle> {
        self.deref().import_root_creds(password, exported)
    }

    fn assign_node_writecap(
        &self,
        handle: &mut Self::CredHandle,
        writecap: Writecap,
    ) -> Result<()> {
        self.deref().assign_node_writecap(handle, writecap)
    }

    fn assign_root_writecap(
        &self,
        handle: &mut Self::CredHandle,
        writecap: Writecap,
    ) -> Result<()> {
        self.deref().assign_root_writecap(handle, writecap)
    }
}

impl BlockMeta {
    /// Validates that this metadata struct contains a valid writecap, that this writecap is
    /// permitted to write to the path of this block and that the signature in this metadata struct
    /// is valid and matches the key the writecap was issued to.
    pub fn assert_valid(&self, path: &BlockPath) -> Result<()> {
        let body = &self.body;
        let writecap = body
            .writecap
            .as_ref()
            .ok_or(crate::BlockError::MissingWritecap)?;
        writecap.assert_valid_for(path)?;
        let signed_by = body.signing_key.principal();
        if writecap.body.issued_to != signed_by {
            return Err(bterr!(Error::signature_mismatch(
                writecap.body.issued_to.clone(),
                signed_by,
            )));
        }
        body.signing_key.ser_verify(&body, self.sig.as_slice())
    }
}

/// The types of errors which can occur when verifying a writecap chain is authorized to write to
/// a given path.
#[derive(Debug, PartialEq, Eq, Display)]
pub enum WritecapAuthzErr {
    /// The chain is not valid for use on the given path.
    UnauthorizedPath,
    /// At least one writecap in the chain is expired.
    Expired,
    /// The given writecaps do not actually form a chain.
    NotChained,
    /// The principal the root writecap was issued to does not own the given path.
    RootDoesNotOwnPath,
    /// An error occurred while serializing a writecap.
    Serde(String),
    /// The write cap chain was too long to be validated. The value contained in this error is
    /// the maximum allowed length.
    ChainTooLong(usize),
}

impl Writecap {
    /// Verifies that the given [Writecap] actually grants permission to write to the given
    /// [BlockPath].
    pub fn assert_valid_for(&self, path: &BlockPath) -> Result<()> {
        let mut writecap = self;
        const CHAIN_LEN_LIMIT: usize = 256;
        let mut prev: Option<&Writecap> = None;
        let mut sig_input_buf = Vec::new();
        let now = Epoch::now();
        for _ in 0..CHAIN_LEN_LIMIT {
            if !writecap.body.path.contains(path) {
                return Err(bterr!(WritecapAuthzErr::UnauthorizedPath));
            }
            if writecap.body.expires <= now {
                return Err(bterr!(WritecapAuthzErr::Expired));
            }
            if let Some(prev) = &prev {
                if prev
                    .body
                    .signing_key
                    .principal_of_kind(writecap.body.issued_to.kind())
                    != writecap.body.issued_to
                {
                    return Err(bterr!(WritecapAuthzErr::NotChained));
                }
            }
            sig_input_buf.clear();
            write_to(&writecap.body, &mut sig_input_buf)
                .map_err(|e| bterr!(WritecapAuthzErr::Serde(e.to_string())))?;
            writecap.body.signing_key.verify(
                &mut std::iter::once(sig_input_buf.as_slice()),
                writecap.signature.as_slice(),
            )?;
            match &writecap.next {
                Some(next) => {
                    prev = Some(writecap);
                    writecap = next;
                }
                None => {
                    // We're at the root key. As long as the signer of this writecap is the owner of
                    // the path, then the writecap is valid.
                    if writecap
                        .body
                        .signing_key
                        .principal_of_kind(path.root().kind())
                        == *path.root()
                    {
                        return Ok(());
                    } else {
                        return Err(bterr!(WritecapAuthzErr::RootDoesNotOwnPath));
                    }
                }
            }
        }
        Err(bterr!(WritecapAuthzErr::ChainTooLong(CHAIN_LEN_LIMIT)))
    }
}

#[cfg(test)]
mod tests {
    use std::{
        io::{Seek, SeekFrom},
        time::Duration,
    };

    use super::*;
    use crate::{
        crypto::secret_stream::SecretStream,
        test_helpers::{self, *},
        Sectored, TryCompose,
    };

    #[test]
    fn encrypt_decrypt_block() {
        const SECT_SZ: usize = 16;
        const SECT_CT: usize = 8;
        let mut block = make_block_with();
        write_fill(&mut block, SECT_SZ, SECT_CT);
        block.rewind().expect("rewind failed");
        read_check(block, SECT_SZ, SECT_CT);
    }

    #[test]
    fn rsa_sign_and_verify() -> Result<()> {
        let key = make_key_pair();
        let header = b"About: lyrics".as_slice();
        let message = b"Everything that feels so good is bad bad bad.".as_slice();
        let signature = key.sign(&mut [header, message].into_iter())?;
        key.verify(&mut [header, message].into_iter(), signature.as_slice())
    }

    #[test]
    fn hash_to_string() {
        let hash = make_principal().0;
        let string = hash.to_string();
        assert_eq!("0!dSip4J0kurN5VhVo_aTipM-ywOOWrqJuRRVQ7aa-bew", string)
    }

    #[test]
    fn hash_to_string_round_trip() -> Result<()> {
        let expected = make_principal().0;
        let string = expected.to_string();
        let actual = VarHash::try_from(string.as_str())?;
        assert_eq!(expected, actual);
        Ok(())
    }

    #[test]
    fn verify_writecap_valid() {
        let writecap = make_writecap(["apps", "verse"].into_iter());
        writecap
            .assert_valid_for(&writecap.body.path)
            .expect("failed to verify writecap");
    }

    #[test]
    fn verify_writecap_invalid_signature() -> Result<()> {
        let mut writecap = make_writecap(["apps", "verse"].into_iter());
        writecap.signature = Signature::empty(Sign::RSA_PSS_3072_SHA_256);
        let result = writecap.assert_valid_for(&writecap.body.path);
        if let Err(ref err) = result {
            if let Some(err) = err.downcast_ref::<Error>() {
                if let Error::InvalidSignature = err {
                    return Ok(());
                }
            }
        }
        Err(bterr!("unexpected result {:?}", result))
    }

    fn assert_authz_err<T: std::fmt::Debug>(
        expected: WritecapAuthzErr,
        result: Result<T>,
    ) -> Result<()> {
        if let Some(err) = result.as_ref().err() {
            if let Some(actual) = err.downcast_ref::<WritecapAuthzErr>() {
                if *actual == expected {
                    return Ok(());
                }
            }
        }
        Err(bterr!("unexpected result: {:?}", result))
    }

    #[test]
    fn verify_writecap_invalid_path_not_contained() -> Result<()> {
        let writecap = make_writecap(["apps", "verse"].into_iter());
        let mut path = writecap.body.path.clone();
        path.pop_component();
        // `path` is now a superpath of `writecap.path`, thus the writecap is not authorized to
        // write to it.
        let result = writecap.assert_valid_for(&path);
        assert_authz_err(WritecapAuthzErr::UnauthorizedPath, result)
    }

    #[test]
    fn verify_writecap_invalid_expired() -> Result<()> {
        let mut writecap = make_writecap(["apps", "verse"].into_iter());
        writecap.body.expires = Epoch::now() - Duration::from_secs(1);
        let result = writecap.assert_valid_for(&writecap.body.path);
        assert_authz_err(WritecapAuthzErr::Expired, result)
    }

    #[test]
    fn verify_writecap_invalid_not_chained() -> Result<()> {
        let (mut root_writecap, root_key) = make_self_signed_writecap();
        root_writecap.body.issued_to = Principal(VarHash::from(HashKind::Sha2_256));
        root_key.sign_writecap(&mut root_writecap)?;
        let node_principal = NODE_CREDS.principal();
        let writecap = make_writecap_trusted_by(
            root_writecap,
            &root_key,
            node_principal,
            ["apps", "contacts"].into_iter(),
        );
        let result = writecap.assert_valid_for(&writecap.body.path);
        assert_authz_err(WritecapAuthzErr::NotChained, result)
    }

    #[test]
    fn verify_writecap_invalid_root_doesnt_own_path() -> Result<()> {
        let (mut root_writecap, root_key) = make_self_signed_writecap();
        let owner = Principal(VarHash::from(HashKind::Sha2_256));
        root_writecap.body.path = make_path_with_root(owner, std::iter::empty());
        root_key.sign_writecap(&mut root_writecap)?;
        let node_principal = NODE_CREDS.principal();
        let writecap = make_writecap_trusted_by(
            root_writecap,
            &root_key,
            node_principal,
            ["apps", "contacts"].into_iter(),
        );
        let result = writecap.assert_valid_for(&writecap.body.path);
        assert_authz_err(WritecapAuthzErr::RootDoesNotOwnPath, result)
    }

    #[test]
    fn aeadkey_encrypt_decrypt_aes256gcm() {
        let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
        let aad = [1u8; 16];
        let expected = [2u8; 32];
        let tagged = key.encrypt(aad, &expected).expect("encrypt failed");
        let actual = key.decrypt(&tagged).expect("decrypt failed");
        assert_eq!(expected, actual.as_slice());
    }

    #[test]
    fn aeadkey_decrypt_fails_when_ct_modified() {
        let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
        let aad = [1u8; 16];
        let expected = [2u8; 32];
        let mut tagged = key.encrypt(aad, &expected).expect("encrypt failed");
        tagged.ciphertext.data[0] = tagged.ciphertext.data[0].wrapping_add(1);
        let result = key.decrypt(&tagged);
        assert!(result.is_err())
    }

    #[test]
    fn aeadkey_decrypt_fails_when_aad_modified() {
        let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
        let aad = [1u8; 16];
        let expected = [2u8; 32];
        let mut tagged = key.encrypt(aad, &expected).expect("encrypt failed");
        tagged.aad[0] = tagged.aad[0].wrapping_add(1);
        let result = key.decrypt(&tagged);
        assert!(result.is_err())
    }

    #[test]
    fn compose_merkle_and_secret_streams() {
        use merkle_stream::tests::make_merkle_stream_filled_with_zeros;
        const SECT_SZ: usize = 4096;
        const SECT_CT: usize = 16;
        let merkle = make_merkle_stream_filled_with_zeros(SECT_SZ, SECT_CT);
        let key = SymKey::generate(SymKeyKind::Aes256Cbc).expect("key generation failed");
        let mut secret = SecretStream::new(key)
            .try_compose(merkle)
            .expect("compose for secret failed");
        let secret_sect_sz = secret.sector_sz();
        write_fill(&mut secret, secret_sect_sz, SECT_CT);
        secret.rewind().expect("rewind failed");
        read_check(secret, secret_sect_sz, SECT_CT);
    }

    fn ossl_hash_op_same_as_digest_test_case<H: Hash + From<DigestBytes>>(kind: HashKind) {
        let parts = (0u8..32).map(|k| vec![k; kind.len()]).collect::<Vec<_>>();
        let expected = {
            let mut expected = vec![0u8; kind.len()];
            kind.digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
                .unwrap();
            expected
        };
        let mut op = OsslHashOp::<H>::new(kind).unwrap();

        for part in parts.iter() {
            op.update(part.as_slice()).unwrap();
        }
        let actual = op.finish().unwrap();

        assert_eq!(expected.as_slice(), actual.as_ref());
    }

    /// Tests that the hash computed using an `OsslHashOp` is the same as the one returned by the
    /// `HashKind::digest` method.
    #[test]
    fn ossl_hash_op_same_as_digest() {
        ossl_hash_op_same_as_digest_test_case::<Sha2_256>(Sha2_256::KIND);
        ossl_hash_op_same_as_digest_test_case::<Sha2_512>(Sha2_512::KIND);
    }

    /// Tests that a `HashWrap` instance calculates the same hash as a call to the `digest` method.
    #[test]
    fn hash_stream_agrees_with_digest_method() {
        let cursor = BtCursor::new([0u8; 3 * 32]);
        let parts = (1u8..4).map(|k| [k; Sha2_512::LEN]).collect::<Vec<_>>();
        let expected = {
            let mut expected = Sha2_512::default();
            HashKind::Sha2_512
                .digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
                .unwrap();
            expected
        };
        let op = OsslHashOp::<Sha2_512>::new(Sha2_512::KIND).unwrap();
        let mut wrap = HashStream::new(cursor, op);

        for part in parts.iter() {
            wrap.write(part.as_slice()).unwrap();
        }
        let actual = wrap.finish().unwrap();

        assert_eq!(expected, actual);
    }

    /// Tests that the `VarHash` computed by `VarHashOp` is the same as the one returned by the
    /// `digest` method.
    #[test]
    fn var_hash_op_agress_with_digest_method() {
        let parts = (32..64u8).map(|k| [k; Sha2_512::LEN]).collect::<Vec<_>>();
        let expected = {
            let mut expected = VarHash::from(HashKind::Sha2_512);
            HashKind::Sha2_512
                .digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
                .unwrap();
            expected
        };
        let mut op = VarHashOp::new(HashKind::Sha2_512).unwrap();

        for part in parts.iter() {
            op.update(part.as_slice()).unwrap();
        }
        let actual = op.finish().unwrap();

        assert_eq!(expected, actual);
    }

    /// Tests that the signature produced by `OsslSignOp` can be verified.
    #[test]
    fn ossl_sign_op_sig_can_be_verified() {
        let keys = &test_helpers::NODE_CREDS;
        let part_values = (1..9u8).map(|k| [k; 32]).collect::<Vec<_>>();
        let get_parts = || part_values.iter().map(|a| a.as_slice());
        let mut sign_op = keys.init_sign().expect("init_sign failed");

        for part in get_parts() {
            sign_op.update(part).expect("update failed");
        }
        let sig = sign_op.finish().expect("finish failed");

        keys.verify(&mut get_parts(), sig.as_ref())
            .expect("verify failed");
    }

    /// Tests that the signature produced by a `SignWrite` can be verified.
    #[test]
    fn sign_write_sig_can_be_verified() {
        use crate::Decompose;
        const LEN: usize = 512;

        let cursor = BtCursor::new([0u8; LEN]);
        let keys = &test_helpers::NODE_CREDS;
        let sign_op = keys.sign.private.init_sign().expect("init_sign failed");
        let mut sign_write = SignWrite::new(cursor, sign_op);

        for part in (1..9u8).map(|k| [k; LEN / 8]) {
            sign_write.write(part.as_slice()).expect("write failed");
        }
        let (sig, cursor) = sign_write.finish().expect("finish failed");
        let array = cursor.into_inner();

        keys.verify(&mut std::iter::once(array.as_slice()), sig.as_ref())
            .expect("verify failed");
    }

    /// Tests that data signed using a `SignWrite` can later be verified using a `VerifyRead`.
    #[test]
    fn sign_write_then_verify_read() {
        const LEN: usize = 512;
        let cursor = BtCursor::new([0u8; LEN]);
        let keys = &test_helpers::NODE_CREDS;
        let sign_op = keys.sign.private.init_sign().expect("init_sign failed");
        let mut sign_write = SignWrite::new(cursor, sign_op);

        for part in (1..9u8).map(|k| [k; LEN / 8]) {
            sign_write.write(part.as_slice()).expect("write failed");
        }
        let (sig, mut cursor) = sign_write.finish().expect("finish failed");
        cursor.seek(SeekFrom::Start(0)).expect("seek failed");

        let verify_op = keys.sign.public.init_verify().expect("init_verify failed");
        let mut verify_read = VerifyRead::new(cursor, verify_op);
        let mut buf = Vec::with_capacity(LEN);
        verify_read
            .read_to_end(&mut buf)
            .expect("read_to_end failed");

        verify_read
            .finish(sig.as_ref())
            .expect("failed to verify signature");
    }

    /// Tests that validate the dependencies of this module.
    mod dependency_tests {
        use super::*;
        use openssl::{
            ec::{EcGroup, EcKey},
            nid::Nid,
        };

        /// This test validates that data encrypted with AES 256 CBC can later be decrypted.
        #[test]
        fn aes_256_cbc_roundtrip() {
            use super::*;
            let expected = b"We attack at the crack of noon!";
            let cipher = Cipher::aes_256_cbc();

            let key = BLOCK_KEY.key_slice();
            let iv = BLOCK_KEY.iv_slice();
            let ciphertext = openssl_encrypt(cipher, key, iv, expected).unwrap();
            let actual = openssl_decrypt(cipher, key, iv, ciphertext.as_slice()).unwrap();

            assert_eq!(expected, actual.as_slice());
        }

        /// Tests that the keys for the SECP256K1 curve are the expected sizes.
        #[test]
        fn secp256k1_key_lengths() {
            let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
            let key = EcKey::generate(&group).unwrap();
            let public = key.public_key_to_der().unwrap();
            let private = key.private_key_to_der().unwrap();
            let public_len = public.len();
            let private_len = private.len();
            assert_eq!(88, public_len);
            assert_eq!(118, private_len);
        }

        #[test]
        fn ed25519_key_lengths() {
            let key = PKey::generate_x25519().unwrap();
            let public = key.public_key_to_der().unwrap();
            let private = key.private_key_to_der().unwrap();
            let public_len = public.len();
            let private_len = private.len();
            assert_eq!(44, public_len);
            assert_eq!(48, private_len);
        }
    }

    mod obj_safety {
        use super::*;

        #[test]
        fn op_obj_safe() {
            assert_obj_safe!(Op);
        }

        #[test]
        fn sign_op_obj_safe() {
            assert_obj_safe!(SignOp);
        }

        #[test]
        fn verify_op_obj_safe() {
            assert_obj_safe!(VerifyOp);
        }

        #[test]
        fn encrypter_obj_safe() {
            assert_obj_safe!(Encrypter);
        }

        #[test]
        fn decrypter_obj_safe() {
            assert_obj_safe!(Decrypter);
        }

        #[test]
        fn verifier_obj_safe() {
            assert_obj_safe!(Verifier);
        }

        #[test]
        fn signer_obj_safe() {
            assert_obj_safe!(Signer);
        }

        #[test]
        fn creds_pub_obj_safe() {
            assert_obj_safe!(CredsPub);
        }

        #[test]
        fn creds_priv_obj_safe() {
            assert_obj_safe!(CredsPriv);
        }

        #[test]
        fn creds_obj_safe() {
            assert_obj_safe!(Creds);
        }
    }
}