Carbon.Cryptography.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
# Copyright Aaron Jensen and WebMD Health Services
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

#Requires -Version 5.1
Set-StrictMode -Version 'Latest'

Add-Type -AssemblyName 'System.Security'

# Functions should use $moduleRoot as the relative root from which to find
# things. A published module has its function appended to this file, while a
# module in development has its functions in the Functions directory.
$moduleRoot = $PSScriptRoot
$moduleBinRoot = Join-Path -Path $moduleRoot -ChildPath 'bin'
$moduleBinRoot | Out-Null # To make the PSScriptAnalyzer squiggle go away.
$privateModulesRoot = Join-Path -Path $moduleRoot -ChildPath 'PSModules'

Import-Module -Name (Join-Path -Path $privateModulesRoot -ChildPath 'Carbon.Core') `
              -Function @('Invoke-CPowerShell', 'Test-COperatingSystem')

# Store each of your module's functions in its own file in the Functions
# directory. On the build server, your module's functions will be appended to
# this file, so only dot-source files that exist on the file system. This allows
# developers to work on a module without having to build it first. Grab all the
# functions that are in their own files.
$functionsPath = Join-Path -Path $moduleRoot -ChildPath 'Functions\*.ps1'
if( (Test-Path -Path $functionsPath) )
{
    foreach( $functionPath in (Get-Item $functionsPath) )
    {
        . $functionPath.FullName
    }
}



function Convert-CSecureStringToByte
{
    <#
    .SYNOPSIS
    Converts a secure string to an array of bytes.
 
    .DESCRIPTION
    The `Convert-CSecureStringToByte` converts a `[securestring]` to an array of bytes that represents the original
    decrypted string. The secure string is never left in memory as a string, but is kept as an array of bytes during
    the conversion, and all arrays used during the conversion are cleared.
 
    The decrypted secure string is returned as an array of bytes. You are resonsible for clearing the array when
    you're done, otherwise you risk exposing your secret in memory or on the file system.
 
    .EXAMPLE
    Convert-CSecureStringToByte -SecureString $credential.Password
 
    Demonstrates how to convert a secure string into an array of bytes representing the original password.
    #>

    [CmdletBinding()]
    [OutputType([Byte[]])]
    param(
        [Parameter(Mandatory)]
        [securestring]$SecureString
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

    $ptrDecryptedString = [Runtime.Interopservices.Marshal]::SecureStringToGlobalAllocUnicode($SecureString);
    try
    {
        [byte[]]$bytes = [byte[]]::New($SecureString.Length * 2)
        for( $idx = 0; $idx -lt $bytes.Length; ++$idx )
        {
            $bytes[$idx] = [Runtime.InteropServices.Marshal]::ReadByte($ptrDecryptedString, $idx)
        }
        return $bytes
    }
    finally
    {
        [Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($ptrDecryptedString)
    }
}


function Convert-CSecureStringToString
{
    <#
    .SYNOPSIS
    Converts a secure string into a plain text string.
 
    .DESCRIPTION
    The `Convert-CSecureStringToString` function converts a secure string to a plaintexxt string. Try really, really,
    really hard not to do this. Once you do, the plaintext string will be *all over memory* and, perhaps, the file
    system.
     
    The function creates a new `[pscredential]` with the password and uses it to convert the password to plaintext
    (i.e. it calls `$credential.GetNetworkCredential().Password`).
 
    .OUTPUTS
    System.String.
 
    .EXAMPLE
    Convert-CSecureStringToString -SecureString $mySuperSecretPasswordIAmAboutToExposeToEveryone
 
    Returns the plain text/decrypted value of the secure string.
 
    .EXAMPLE
    $ISureHopeIKnowWhatIAmDoing | Convert-CSecureStringToString
 
    Demonstrates that you can pipe a secure string to `Convert-CSecureStringToString`.
    #>

    [CmdletBinding()]
    [OutputType([String])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        # The secure string to convert.
        [securestring]$SecureString
    )
    
    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        $bytes = Convert-CSecureStringToByte -SecureString $SecureString
        try
        {
            return [Text.Encoding]::Unicode.GetString($bytes)
        }
        finally
        {
            $bytes.Clear()
        }
    }
}




function ConvertTo-AesKey
{
    [CmdletBinding()]
    [OutputType([byte[]])]
    param(
        [Parameter(Mandatory)]
        [String]$From,

        [Parameter(Mandatory)]
        [Object]$InputObject
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState    

    $Key = $InputObject

    $bytesKey = $true
    if( $InputObject -isnot [byte[]] )
    {
        $bytesKey = $false
        if( $InputObject -is [SecureString] )
        {
            $unicodeKey = Convert-CSecureStringToByte -SecureString $InputObject
            try
            {
                # SecureString is two bytes per char. We need an encoding that is typically one byte per char, otherwise
                # the key will be twice as big as it should be. In the end, the user is responsible for ensuring the
                # key is the property size (in bytes).
                $Key = [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, $unicodeKey)
            }
            finally
            {
                $unicodeKey.Clear() # Keep it out of memory!
            }
        }
        else
        {
            $msg = "An encryption key must be a [securestring] or an array of bytes, but $($From) got passed a " +
                   """$($InputObject.GetType().FullName)"". If you are passing an array of bytes, make sure you " +
                   "explicitly cast it as a ``byte[]`, e.g. `([byte[]])@( ... )` when passing to $($From)."
            Write-Error -Message $msg
            return
        }
    }

    if( $Key.Length -ne 128/8 -and $Key.Length -ne 192/8 -and $Key.Length -ne 256/8 )
    {
        $commonMsg = "Key is the wrong length. The $($From) function is using AES, which requires a 128-bit, " +
                     '192-bit, or 256-bit key (16, 24, or 32 bytes, respectively). '
        # Did we receive an array of bytes for a key or a secure string?
        if( $bytesKey )
        {
            $msg = "$($commonMsg) Make sure your byte array key is 16, 24, or 32 bytes long."
        }
        # Got a secure string.
        else
        {
            $msg = "$($commonMsg) Make sure that when the secure string key is UTF-8 encoded and converted to a byte " +
                   "array, that array is 16, 32, or 64 bytes long. $($From) received a secure string key that is " +
                   "$($Key.Length) bytes long."
        }
        Write-Error -Message $msg
        return
    }

    return $Key
}



function Find-CCertificate
{
    <#
    .SYNOPSIS
    Searches certificate stores for certificates.
 
    .DESCRIPTION
    The `Find-CCertificate` function searches through the My/Personal certificate store for the local machine and
    current user accounts for certificates that match search criteria. Use the following parameters to search:
 
    * `Subject`: return certificates with the given subject. Wildcards accepted.
    * `LiteralSubject`: return certificates whose subjects exactly match the given subject.
    * `Active`: return certificates that are active and not expired.
    * `HasPrivateKey`: return certificates that have a private key.
    * `HostName`: return certificates that authenticate the given hostname. Wildcards supported. Matches against the
      subject's common name and the certificate's subject alternate names.
    * `LiteralHostName`: return certificates that authenticate the given hostname. Matches against the subject's common
      name and the certificate's subject alternate names.
    * `KeyUsageName`: return certificates that have the given enhanced key usage, searching each usage's friendly name.
    * `KeyUsageOId`: return certificates that have the given enhanced key usage, searching each usage's object ID.
    * `Trusted`: return certificates that are trusted/verified.
 
    You can search in the local machine or current user accounts (not both) by passing the account to the
    `StoreLocation` parameter. You can search in different stores by passing the store name to the `StoreName`
    parameter.
 
    .EXAMPLE
    Find-CCertificate -Active -HostName 'dev.example.com' -KeyUsageName 'Server Authentication' -Trusted -HasPrivateKey
 
    Demonstrates how to search for a certificate using multiple criteria. In this example, we're looking for a TLS
    certificate that can be used with the `dev.example.com` hostname.
    #>

    [CmdletBinding()]
    param(
        [String] $Subject,

        [String] $LiteralSubject,

        [switch] $Active,

        [switch] $HasPrivateKey,

        [String] $HostName,

        [String] $LiteralHostName,

        [String] $KeyUsageName,

        [String] $KeyUsageOid,

        [switch] $Trusted,

        [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,

        [Security.Cryptography.X509Certificates.StoreName] $StoreName =
            [Security.Cryptography.X509Certificates.StoreName]::My
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    Write-Verbose 'Find-CCertificate search criteria:'
    if( $Subject )
    {
        Write-Verbose (" Subject like $($Subject)")
    }
    if( $LiteralSubject )
    {
        Write-Verbose (" Subject eq $($LiteralSubject)")
    }
    if( $Active )
    {
        Write-Verbose (' Active True')
    }
    if( $HasPrivateKey )
    {
        Write-Verbose (' HasPrivateKey True')
    }
    if( $HostName )
    {
        Write-Verbose (" HostName like $($HostName)")
    }
    if( $LiteralHostName )
    {
        Write-Verbose (" HostName eq $($LiteralHostName)")
    }
    if( $KeyUsageName )
    {
        Write-Verbose (" Key Usage $($KeyUsageName)")
    }
    if( $KeyUsageOid )
    {
        Write-Verbose (" Key Usage OID $($KeyUsageOid)")
    }
    if( $Trusted )
    {
        Write-Verbose (" Trusted True")
    }
    if( $StoreLocation )
    {
        Write-Verbose (" StoreLocation $($StoreLocation)")
    }
    if( $StoreName )
    {
        Write-Verbose (" StoreName $($StoreName)")
    }
    Write-Verbose ''

    function Test-Object 
    {
        [CmdletBinding()]
        param(
            [Parameter(Mandatory, ValueFromPipeline)]
            [AllowEmptyString()]
            [AllowNull()]
            [Object] $InputObject,

            [Parameter(Mandatory, ParameterSetName='Equals')]
            [AllowEmptyString()]
            [AllowNull()]
            [switch] $Equals,

            [Parameter(Mandatory, ParameterSetName='LessThan')]
            [switch] $LessThan,

            [Parameter(Mandatory, ParameterSetName='GreaterThan')]
            [switch] $GreaterThan,

            [Parameter(Mandatory, ParameterSetName='Contains')]
            [switch] $Contains,

            [Parameter(Mandatory, ParameterSetName='ContainsLike')]
            [switch] $ContainsLike,

            [Parameter(Mandatory, ParameterSetName='Matches')]
            [switch] $Match,

            [Parameter(Mandatory, ParameterSetName='Like')]
            [switch] $Like,

            [Parameter(Mandatory, Position=0)]
            [Object] $Value,

            [Parameter(Mandatory)]
            [String] $Name,

            [String] $DisplayValue
        )

        process
        {
            $success = $false

            if( $Equals )
            {
                if( $null -eq $InputObject )
                {
                    if( $null -eq $Value )
                    {
                        $success = $true
                    }
                }
                elseif( $InputObject -eq $Value )
                {
                    $success = $true
                }
            }
            elseif( $LessThan )
            {
                $success = $InputObject -lt $Value
            }
            elseif( $GreaterThan )
            {
                $success = $InputObject -gt $Value
            }
            elseif( $Contains )
            {
                $success = $InputObject -contains $Value
            }
            elseif( $ContainsLike )
            {
                $success = $null -ne ($InputObject | Where-Object { $_ -like $Value })
            }
            elseif( $Match )
            {
                $success = $InputObject -match $Value
            }
            elseif( $Like )
            {
                $success = $InputObject -like $Value
            }

            $flag = '!'
            if( $success )
            {
                $flag = ' '
            }

            if( -not $DisplayValue )
            {
                $displayValues =
                    $InputObject |
                    ForEach-Object { $_ } |
                    ForEach-Object {
                        if( $_ -is [DateTime] )
                        {
                            return $_.ToString('yyyy-MM-dd HH:mm:ss')
                        }
                        return $_.ToString()
                    }
                $DisplayValue = $displayValues -join ', '
            }

            $name = '{0,-22}' -f $Name
            $msg = " $($flag) $($Name) $($DisplayValue)"
            if( $longestLineLength -lt $msg.Length )
            {
                $script:longestLineLength = $msg.Length
            }
            Write-Verbose -Message $msg
            return $success
        }
    }

    $getCertArgs = @{}

    if( $StoreLocation )
    {
        $getCertArgs['StoreLocation'] = $StoreLocation
    }

    $certs = Get-CCertificate @getCertArgs -StoreName $StoreName
    $isFirstCert = $true
    foreach( $certificate in $certs )
    {
        if( $isFirstCert )
        {
            $isFirstCert = $false
        }
        else
        {
            Write-Verbose ('')
        }

        Write-Verbose -Message ("$($certificate.Subject)")
        Write-Verbose -Message ("$($certificate.Thumbprint)")

        $script:longestLineLength = $certificate.Subject.Length
        if( $script:longestLineLength -lt $certificate.Thumbprint.Length )
        {
            $script:longestLineLength = $certificate.Thumbprint.Length
        }

        if( $Subject )
        {
            if( -not ($certificate.Subject | Test-Object -Like $Subject -Name 'subject') )
            {
                continue
            }
        }

        if( $LiteralSubject )
        {
            if( -not ($certificate.Subject | Test-Object -Equals $LiteralSubject -Name 'subject') )
            {
                continue
            }
        }

        if( $HasPrivateKey.IsPresent )
        {
            if( -not ($certificate.HasPrivateKey | Test-Object -Equals $HasPrivateKey -Name 'private key') )
            {
                continue
            }
        }

        if( $Active )
        {
            if( -not ($certificate.NotBefore | Test-Object -LessThan (Get-Date) -Name 'start date') )
            {
                continue
            }

            if( -not ($certificate.NotAfter | Test-Object -GreaterThan (Get-Date) -Name 'expiration date') )
            {
                continue
            }
        }

        $subjectHostName = ''
        if( $certificate.Subject -match '^CN=([^,]+),?.*$' )
        {
            $subjectHostName = $Matches[1]
        }

        if( $HostName )
        {
            $inSubject = $subjectHostName | Test-Object -Like $HostName -Name 'subject common name'
            if( -not $inSubject )
            {
                $found =
                    (,$certificate.DnsNameList | Test-Object -ContainsLike $HostName -Name 'subject alternate name')
                if( -not $found )
                {
                    continue
                }
            }
        }

        if( $LiteralHostName )
        {
            $inSubject = $subjectHostName | Test-Object -Equals $LiteralHostName -Name 'subject common name'
            if( -not $inSubject )
            {
                $found =
                    (,$certificate.DnsNameList | Test-Object -Contains $LiteralHostName -Name 'subject alternate name')
                if( -not $found )
                {
                    continue
                }
            }
        }

        if( $KeyUsageName -or $KeyUsageOid )
        {
            if( $certificate.EnhancedKeyUsageList.Count -eq 0 )
            {
                $certificate.EnhancedKeyUsageList.Count |
                    Test-Object -Equals 0 -Name 'key usage' -DisplayValue 'Any' |
                    Out-Null
            }
            else
            {
                if( $KeyUsageName )
                {
                    $names = $certificate.EnhancedKeyUsageList | Select-Object -ExpandProperty 'FriendlyName'
                    if( -not (,$names | Test-Object -Contains $KeyUsageName -Name 'key usage') )
                    {
                        continue
                    }
                }

                if( $KeyUsageOid )
                {
                    $oids = $certificate.EnhancedKeyUsageList | Select-Object -ExpandProperty 'ObjectId'
                    if( -not (,$oids | Test-Object -Contains $KeyUsageOid -Name 'key usage') )
                    {
                        continue
                    }
                }
            }
        }

        if( $Trusted )
        {
            if( -not $certificate.Verify() | Test-Object -Equals $true -Name 'trusted' )
            {
                continue
            }
        }
        
        Write-Verbose -Message "^$('-' * ($longestLineLength - 1))^"
        $certificate | Write-Output
    }
}


function Find-CTlsCertificate
{
    <#
    .SYNOPSIS
    Finds a TLS certificate that matches a hostname from the certificate stores.
 
    .DESCRIPTION
    The `Find-CTlsCertficate` function finds a TLS certificate for the current computer. It determines the computer's
    domain name/hostname using the `HostName` and `DomainName` properties from
    `[System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()`. To get a certificate for a custom
    hostname, pass that hostname to the `HostName` parameter.
 
    The `Find-CTlsCertificate` function returns the first certificate that:
 
    * has a private key.
    * hasn't expired and whose start date is in the past
    * contains the `HostName` in its subject or Subject Alternative Name list.
    * has 'Server Authentication' in its enhanced key usage list or has no enhanced key usage metadata.
 
    Additionally, you can use the `-Trusted` switch to only return trusted certificates, i.e. certificates whose
    issuing certificate authorities in its cert chain are installed in the local machine or current user's [trusted
    certificate stores](https://docs.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography#x509store).
    `Find-CTlsCertificate` calls the `Verify()` method on each `X509Certificate2` object to determine if that
    certificate is trusted.
 
    If multiple certificates are found, `Find-CTlsCertificate` will return the certificate that expires later. If no
    certificate is found, it writes an error and returns nothing.
 
    Use the `-Verbose` switch to see why a certificate is or isn't being found and selected by `Find-CTlsCertificate`.
    You'll see messages for each selection criteria and if a criterium isn't met, you'll see a `!` flag. For example,
    this verbose output from `Find-CTlsCertificate -HostName 'example.com' -Trusted -Verbose`
 
        VERBOSE: FCD157FCB753E2B388183C19021301B1739DF1E2
        VERBOSE: CN=sub.example.com
        VERBOSE: private key True
        VERBOSE: start date 2021-10-18 15:43:23
        VERBOSE: expiration date 2023-10-19 15:43:23
        VERBOSE: ! hostname ['sub.example.com']
        VERBOSE:
        VERBOSE: 7F660D4F7201B8EB8F7F6AC2A0906253C240584F
        VERBOSE: CN=example.com
        VERBOSE: private key True
        VERBOSE: start date 2021-10-18 15:43:23
        VERBOSE: expiration date 2022-10-19 15:43:23
        VERBOSE: hostname ['example.com']
        VERBOSE: key usage Any
        VERBOSE: trusted True
        VERBOSE: ^--------------------------------------^
 
    shows that certificate `FCD157FCB753E2B388183C19021301B1739DF1E2` wasn't selected because its hostname didn't match
    the `example.com` hostname, but that certificate `7F660D4F7201B8EB8F7F6AC2A0906253C240584F` was selected because
    it matched all six criteria.
 
    .OUTPUTS
    System.Security.Cryptography.x509Certificates.X509Certificate2 that was found or `$null` if no match was found.
 
    .EXAMPLE
    Find-CTlsCertificate
 
    Demonstrates how to find a TLS certificate for the current computer using the computer's hostname and domain name
    as determined by the `[System.Net.NetworkInformation.IPGlobalProperties]` object returned by the
    ``[System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()::GetIPGlobalProperties()` method.
 
    .EXAMPLE
    Find-CTlsCertificate -HostName 'example.com'
 
    Demonstrates how to find a valid TLS valid certificate for a hostname, in this example, `example.com`.
 
    .EXAMPLE
    Find-CTlsCertificate -HostName 'example.com' -Trusted
 
    Demonstrates how to find a valid *trusted* TLS certificate by using the `-Trusted` switch. Trusted certificates
    are issued by certificate authorities whose certificates (and all certificates in the certificate chain) are in the
    local machine or current user's [trusted certificate stores](https://docs.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography#x509store).
    #>

    [CmdletBinding()]
    [OutputType([Security.Cryptography.X509Certificates.X509Certificate2])]
    param(
        # The hostname whose TLS certificate to find.
        [String] $HostName,

        # In addition to all other search criteria, if set, causes `Find-CTLSCertificate` to only return trusted
        # certificates, i.e. certificates that are issued by a certificate authority installed in the local machine or
        # current user's [trusted certificate stores](https://docs.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography#x509store).
        # `Find-CTlsCertificate` calls the `Verify()` method on each certificate to determine if a certificate is
        # trusted.
        [switch] $Trusted
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState
    
    if( -not $HostName )
    {
        $ipProperties = [Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
        $HostName= "$($ipProperties.HostName).$($ipProperties.DomainName)"
    }

    $certificate =
        Find-CCertificate -HostName $HostName `
                         -Active `
                         -HasPrivateKey `
                         -KeyUsageName 'Server Authentication' `
                         -Trusted:$Trusted |
        Sort-Object -Property 'NotAfter' -Descending |
        Select-Object -First 1
    
    if( $certificate )
    {
        return $certificate
    }

    $isTrustedMsg = ''
    if( $Trusted )
    {
        $isTrustedMsg = '* is trusted.' + [Environment]::NewLine
    }
    $msg = "TLS certificate for $($HostName) does not exist. Make sure there is a certificate in the My certificate " +
           'store for the LocalMachine or CurrentUser that:' + [Environment]::NewLine +
           ' ' + [Environment]::NewLine +
           '* has a private key' + [Environment]::NewLine +
           '* hasn''t expired and whose "NotBefore"/"Valid From" date is in the past' + [Environment]::NewLine +
           "* has subject ""CN=$($HostName)""; or whose Server Alternative Name contains ""$($HostName)""" +
           [Environment]::NewLine +
           '* has an enhanced key usage of "Server Authentication" (or no enhanced key usage ' +
           'metadata) ' + [Environment]::NewLine +
           $isTrustedMsg +
           ' ' + [Environment]::NewLine + 
           'Use the -Verbose switch to see why each certificate was rejected.'

    Write-Error -Message $msg -ErrorAction $ErrorActionPreference
}


function Get-CCertificate
{
    <#
    .SYNOPSIS
    Gets a certificate from a file or the Windows certificate store.
 
    .DESCRIPTION
    The `Get-CCertificate` function gets an X509 certificate from a file or the Windows certificate store. When you
    want to get a certificate from a file, pass the path to the `Path` parameter (wildcards allowed). If the certificate
    is password-protected, pass its password, as a `[securestring]`, to the `Password` parameter. If you plan on
    installing the certificate in a Windows certificate store, and you want to customize the key storage flags, pass
    the flags to the `KeyStorageFlags` parameter.
 
    On Windows, the path can also be a path to a certificate in PowerShell's certificate drive (i.e. the path begins
    with `cert:\`). When getting a path in the `cert:` drive, the `Password` and `KeyStorageFlags` parameters are
    ignored. The certificate is returned. Wildcards allowed.
 
    When called with no parameters, `Get-CCertificate` returns all certificates in all certificate locations and stores
    (except stores with custom names). You can filter what certificates to return using any combination of these
    parameters. A certificate must match all filters to be returned.
 
    * `StoreLocation`: only return certificates in one of the store locations, `CurrentUser` or `LocalMachine`.
    * `StoreName`: only return certificates from this store. Can't be used with `CustomStoreName`.
    * `CustomStoreName`: only return certificates from this custom store name. Can't be used with `StoreName`.
    * `Subject`: only return certificates with this subject. Wildcards allowed.
    * `LiteralSubject`: only return certificates with this exact subject.
    * `Thumbprint`: only return certificates with this thumbprint. Wildcards allowed.
    * `FriendlyName`: only return certificates with this friendly name. Wildcards allowed. Friendly names are
      Windows-only. If you pass a friendly name on other platforms, you'll get no certificates back.
    * `LiteralFriendlyName`: only return certificates with this exact friendly name. Friendly names are Windows-only. If
      you pass a friendly name on other platforms, you'll get no certificates back.
 
    `Get-CCertificate` adds a `Path` property to the returned objects that is the file system path where the certificate
    was loaded from, or, if loaded from a Windows certificate store, the path to the certificate in the `cert:` drive.
 
    When loading certificates from a certificate store, `Get-CCertificate` adds `StoreLocation` and `StoreName`
    properties for the store where the certificate was found.
 
    .OUTPUTS
    System.Security.Cryptography.x509Certificates.X509Certificate2. The X509Certificate2 certificates that were found,
    or `$null`.
 
    .EXAMPLE
    Get-CCertificate -Path C:\Certificates\certificate.cer -Password MySuperSecurePassword
 
    Gets an X509Certificate2 object representing the certificate.cer file.
 
    .EXAMPLE
    Get-CCertificate -Thumbprint a909502dd82ae41433e6f83886b00d4277a32a7b -StoreName My -StoreLocation LocalMachine
 
    Gets an X509Certificate2 object for the certificate in the Personal store with a specific thumbprint under the Local
    Machine.
 
    .EXAMPLE
    Get-CCertificate
 
    Demonstrates how to get all certificates in all current user and local machine stores.
 
    .EXAMPLE
    Get-CCertificate -Thumbprint a909502dd82ae41433e6f83886b00d4277a32a7b
 
    Demonstrates how to find certificates with a given thumbprints.
 
    .EXAMPLE
    Get-CCertificate -StoreLocation CurrentUser
 
    Demonstrates how to get all certificates for a specific location.
 
    .EXAMPLE
    Get-CCertificate -StoreName My
 
    Demonstrates how to get all certificates from a specific store.
 
    .EXAMPLE
    Get-CCertificate -Subject 'CN=Carbon.Cryptography'
 
    Demonstrates how to find all certificates in all stores that have a specific subject.
 
    .EXAMPLE
    Get-CCertificate -LiteralSubject 'CN=*.example.com'
 
    Demonstrates how to find a certificate that has wildcards in its subject using the `LiteralSubject` parameter.
 
    .EXAMPLE
    Get-CCertificate -Thumbprint $thumbprint -CustomStoreName 'SharePoint' -StoreLocation LocalMachine
 
    Demonstrates how to get a certificate from a custom store, i.e. one that is not part of the standard `StoreName`
    enumeration.
 
    .EXAMPLE
    Get-CCertificate -FriendlyName 'My Friendly Name'
 
    Demonstrates how to get all certificates with a specific friendly name. Friendly names are Windows-only. No
    certificates will be returned when using this parameter on non-Windows platforms.
 
    .EXAMPLE
    Get-CCertificate -LiteralFriendlyName '*My Friendly Name'
 
    Demonstrates how to find a certificate that has wildcards in its subject using the `LiteralFriendlyName` parameter.
 
    .EXAMPLE
    Get-CCertificate -Path 'cert:\CurrentUser\a909502dd82ae41433e6f83886b00d4277a32a7b'
 
    Demonstrates how to get a certificate out of a Windows certificate store with its certificate path. Wildcards
    supported. The `cert:` drive only exists on Windows. If you use a `cert:` path on non-Windows platforms, you'll get
    an error.
    #>

    [CmdletBinding(DefaultParameterSetName='FromCertificateStore')]
    [OutputType([Security.Cryptography.X509Certificates.X509Certificate2])]
    param(
        # The path to the certificate. On Windows, this can also be a certificate path, e.g. `cert:\`. Wildcards
        # supported.
        [Parameter(Mandatory, ParameterSetName='ByPath', Position=0)]
        [String] $Path,

        # The password to the certificate. Must be a `[securestring]`.
        [Parameter(ParameterSetName='ByPath')]
        [securestring] $Password,

        # The storage flags to use when loading a certificate file. This controls where/how you can store the
        # certificate in the certificate stores later. Use the `-bor` operator to combine flags.
        [Parameter(ParameterSetName='ByPath')]
        [Security.Cryptography.X509Certificates.X509KeyStorageFlags] $KeyStorageFlags,

        # The certificate's thumbprint. Wildcards allowed.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $Thumbprint,

        # The subject of the certificate. Wildcards allowed.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $Subject,

        # The literal subject of the certificate.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $LiteralSubject,

        # The friendly name of the certificate. Wildcards allowed. Friendly name is Windows-only. If you search by
        # friendly name on other platforms, you'll never get any certificates back.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $FriendlyName,

        # The literal friendly name of the certificate. Friendly name is Windows-only. If you search by friendly name on
        # other platforms, you'll never get any certificates back.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $LiteralFriendlyName,

        # The location of the certificate's store.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Parameter(ParameterSetName='FromCertificateStoreCustomStore')]
        [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,

        # The name of the certificate's store.
        [Parameter(ParameterSetName='FromCertificateStore')]
        [Security.Cryptography.X509Certificates.StoreName] $StoreName,

        # The name of the non-standard, custom store.
        [Parameter(Mandatory, ParameterSetName='FromCertificateStoreCustomStore')]
        [String] $CustomStoreName
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    function Add-PathMember
    {
        param(
            [Parameter(Mandatory,VAlueFromPipeline=$true)]
            [Security.Cryptography.X509Certificates.X509Certificate2]
            $Certificate,

            [Parameter(Mandatory)]
            [string]
            $Path
        )

        process
        {
            $Certificate | Add-Member -MemberType NoteProperty -Name 'Path' -Value $Path -PassThru
        }
    }

    function Resolve-CertificateProviderFriendlyPath
    {
        param(
            [Parameter(Mandatory,ValueFromPipelineByPropertyName)]
            [string]
            $PSPath,

            [Parameter(Mandatory,ValueFromPipelineByPropertyName)]
            [Management.Automation.PSDriveInfo]
            $PSDrive
        )

        process
        {
            $qualifier = '{0}:' -f $PSDrive.Name
            $path = $PSPath | Split-Path -NoQualifier
            Join-Path -Path $qualifier -ChildPath $path
        }
    }

    if( $PSCmdlet.ParameterSetName -eq 'ByPath' )
    {
        if( -not (Test-Path -Path $Path -PathType Leaf) )
        {
            Write-Error -Message "Certificate ""$($Path)"" not found." -ErrorAction $ErrorActionPreference
            return
        }

        foreach( $item in (Get-Item -Path $Path) )
        {
            Write-Debug -Message $PSCmdlet.GetUnresolvedProviderPathFromPSPath($item.PSPath)
            if( $item -is [Security.Cryptography.X509Certificates.X509Certificate2] )
            {
                $certFriendlyPath = $item | Resolve-CertificateProviderFriendlyPath
                $item | Add-PathMember -Path $certFriendlyPath | Write-Output
            }
            elseif( $item -is [IO.FileInfo] )
            {
                try
                {
                    $ctorParams = @($item.FullName, $Password )
                    if( $PSBoundParameters.ContainsKey('KeyStorageFlags') )
                    {
                        # macOS doesn't allow ephemeral key storage, which is kind of weird but whatever.
                        if( (Test-COperatingSystem -MacOS) )
                        {
                            $KeyStorageFlags = 
                                $KeyStorageFlags -band -bnot [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet
                        }
                        $ctorParams += $KeyStorageFlags
                    }
                    New-Object 'Security.Cryptography.X509Certificates.X509Certificate2' -ArgumentList $ctorParams | 
                        Add-PathMember -Path $item.FullName |
                        Write-Output
                }
                catch
                {
                    $ex = $_.Exception
                    while( $ex.InnerException )
                    {
                        $ex = $ex.InnerException
                    }
                    $msg = "[$($ex.GetType().FullName)] exception creating X509Certificate2 object from file " +
                           """$($item.FullName)"": $($ex)"
                    Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                }
            }
        }
        return
    }

    $foundCerts = @{}
    Write-Debug -Message "[$($MyInvocation.MyCommand.Name)]"
    $locationWildcard = '*'
    if( $StoreLocation )
    {
        $locationWildcard = $StoreLocation.ToString()
    }

    $storeNameWildcard = '*'
    if( $StoreName )
    {
        $storeNameWildcard = $StoreName.ToString()
    }
    Write-Debug -Message " $($locationWildcard)\$($storeNameWildcard)"

    # If we're searching for a certificate, don't write an error if one isn't found. Only write an error if the user
    # is looking for a specific certificate in a specific location and store.
    $searching = [Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Thumbprint) -or `
                 [Management.Automation.WildcardPattern]::ContainsWildcardCharacters($FriendlyName) -or `
                 [Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Subject) -or `
                 $locationWildcard -eq '*' -or `
                 ($storeNameWildcard -eq '*' -and -not $CustomStoreName)
                 
    [Security.Cryptography.X509Certificates.StoreLocation] $currentUserLocation =
        [Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser
    [Security.Cryptography.X509Certificates.StoreLocation] $localMachineLocation =
        [Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine

    $result = @()
    @($currentUserLocation, $localMachineLocation) |
        Where-Object { $_.ToString() -like $locationWildcard } |
        ForEach-Object {
            $location = $_
            Write-Debug -Message " $($location)"

            if( $CustomStoreName )
            {
                try
                {
                    Write-Debug -Message " $($CustomStoreName)"
                    [Security.Cryptography.X509Certificates.X509Store]::New($CustomStoreName, $location) |
                        Write-Output
                }
                catch
                {
                    $msg = "Failed to open ""$($location)\$($CustomStoreName)"" custom store: $($_)"
                    Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                }
                return
            }

            Write-Debug -Message " $($storeNameWildcard)"

            [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreName]) |
                Where-Object { $_.ToString() -like $storeNameWildcard } |
                ForEach-Object {
                    $name = $_
                    try
                    {
                        [Security.Cryptography.X509Certificates.X509Store]::New($name, $location) |
                            Write-Output
                    }
                    catch
                    {
                        $ex = $_.Exception
                        while( $ex.InnerException )
                        {
                            $ex = $ex.InnerException
                        }
                        $msg = "Exception opening ""$($location)\$($name)"" store: " +
                               "[$($ex.GetType().FullName)]: $($ex)"
                        Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                    }
                }
        } |
        Foreach-Object {
            $openFlags = [Security.Cryptography.X509Certificates.OpenFlags]::OpenExistingOnly -bor `
                         [Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly

            [Security.Cryptography.X509Certificates.X509Store] $store = $_
            try
            {
                $store.Open($openFlags)
                $storeNamePropValue = $store.Name
                if( -not $CustomStoreName )
                {
                    if( $storeNamePropValue -eq 'CA' )
                    {
                        $storeNamePropValue = [Security.Cryptography.X509Certificates.StoreName]::CertificateAuthority
                    }
                    else
                    {
                        $storeNamePropValue = [Security.Cryptography.X509Certificates.StoreName]$storeNamePropValue
                    }
                }
                Write-Debug " $($store.Location) $($store.Name)"
                $store.Certificates |
                    Add-Member -MemberType NoteProperty -Name 'StoreLocation' -Value $store.Location -PassThru |
                    Add-Member -MemberType NoteProperty -Name 'StoreName' -Value $storeNamePropValue -PassThru |
                    Add-Member -MemberType ScriptProperty -Name 'Path' -Value {
                        if( -not (Test-Path -Path 'cert:') )
                        {
                            return
                        }

                        $storeNamePath = $this.StoreName
                        if( $storeNamePath.ToString() -eq 'CertificateAuthority' )
                        {
                            $storeNamePath = 'CA'
                        }

                        $path = Join-Path -Path 'cert:' -ChildPath $this.StoreLocation
                        $path = Join-Path -Path $path -ChildPath $storeNamePath
                        $path = Join-Path -Path $path -ChildPath $this.Thumbprint
                        return $path
                    } -PassThru
            }
            # Store doesn't exist.
            catch [Security.Cryptography.CryptographicException]
            {
                $Global:Error.RemoveAt(0)
            }
            catch
            {
                $ex = $_.Exception
                while( $ex.InnerException )
                {
                    $ex = $ex.InnerException
                }
                $msg = "[$($ex.GetType().FullName)] exception opening and iterating certificates in " +
                       """$($store.Location)\$($store.Name)"" store: $($ex)"
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
            }
            finally
            {
                $store.Dispose()
            }
        } |
        Where-Object {
            $key = "$($_.StoreLocation)\$($_.StoreName)\$($_.Thumbprint)"
            if( $foundCerts.ContainsKey($key) )
            {
                return $false
            }
            $foundCerts[$key] = $_
            return $true
        } |
        Where-Object {
            if( -not $Subject )
            {
                return $true
            }
            return $_.Subject -like $Subject
        } |
        Where-Object {
            if( -not $LiteralSubject )
            {
                return $true
            }

            return $_.Subject -eq $LiteralSubject
        } |
        Where-Object {
            if( -not $Thumbprint )
            {
                return $true
            }
            return $_.Thumbprint -like $Thumbprint
        } |
        Where-Object {
            if( -not $FriendlyName )
            {
                return $true
            }
            return $_.FriendlyName -like $FriendlyName
        } |
        Where-Object {
            if( -not $LiteralFriendlyName )
            {
                return $true
            }
            return $_.FriendlyName -eq $LiteralFriendlyName
        } |
        ForEach-Object { $_.pstypenames.Insert(0, 'Carbon.Cryptography.X509Certificate2') ; $_ } |
        Tee-Object -Variable 'result' |
        Write-Output

    if( -not $searching -and -not $result )
    {
        $fields = [Collections.ArrayList]::New()
        if( $Subject )
        {
            $field = "Subject like ""$($Subject)"""
            [void]$fields.Add($field)
        }

        if( $LiteralSubject )
        {
            $field = "Subject equal ""$($LiteralSubject)"""
            [void]$fields.Add($field)
        }

        if( $Thumbprint )
        {
            $field = "Thumbprint like ""$($Thumbprint)"""
            [void]$fields.Add($field)
        }

        if( $FriendlyName )
        {
            $field = "Friendly Name like ""$($FriendlyName)"""
            [void]$fields.Add($field)
        }

        if( $LiteralFriendlyName )
        {
            $field = "Friendly Name equal ""$($LiteralFriendlyName)"""
            [void]$fields.Add($field)
        }

        if( $StoreName )
        {
            $storeDisplayName = $StoreName.ToString()
        }
        elseif( $CustomStoreName )
        {
            $storeDisplayName = "$($CustomStoreName) custom"
        }

        $lastField = ''
        if( $fields.Count -gt 1 )
        {
            $lastField = ", and $($fields[-1])"
            $fields = $fields[0..($fields.Count - 2)]
        }

        $msg = "Certificate with $($fields -join ', ')$($lastField) does not exist in the $($StoreLocation)\" +
               "$($storeDisplayName) store."
        Write-Error -Message $msg -ErrorAction $ErrorActionPreference
    }
}




function Install-CCertificate
{
    <#
    .SYNOPSIS
    Installs an X509 certificate.
     
    .DESCRIPTION
    The `Install-CCertificate` function installs an X509 certificate. It uses the .NET X509 certificates API. The user
    performing the action must have permission to modify the store or the installation will fail. You can install from
    a file (pass the path to the file to the `-Path` parameter), or from an `X509Certificate2` object (pass it to the
    `-Certificate` parameter). Pass the store location (LocalMachine or CurrentUser) to the `-StoreLocation` parameter.
    Pass the store name (e.g. My, Root) to the `-StoreName` parameter. If the certificate has a private key and you want
    the private key exportable, use the `-Exportable` switch.
 
    If the certificate already exists in the store, nothing happens. If you want to re-install the certificate over any
    existing certificates, use the `-Force` switch.
 
    If installing a certificate from a file, and the file is password-protected, use the `-Password` parameter to pass
    the certificate's password. The password must be a `[securestring]`.
 
    This function only works on Windows.
 
    To install a certificate on a remote computer, create a remoting session with the `New-PSSession` cmdlet, and pass
    the session object to this function's `Session` parameter. When installing to a remote computer, the certificate's
    binary data is converted to a base64 encoded string and sent to the remote computer, where it is converted back
    into a certificate. If installing a certificate from a file, the file's bytes are converted to base64, sent to the
    remote computer, saved as a temporary file, installed, and the temporary file is removed.
 
    .OUTPUTS
    System.Security.Cryptography.X509Certificates.X509Certificate2. An X509Certificate2 object representing the newly installed certificate.
     
    .EXAMPLE
    Install-CCertificate -Path 'C:\Users\me\certificate.cer' -StoreLocation LocalMachine -StoreName My -Exportable -Password $securePassword
     
    Demonstrates how to install a password-protected certificate from a file and to allow its private key to be
    exportable.
     
    .EXAMPLE
    Install-CCertificate -Path C:\Users\me\certificate.cer -StoreLocation LocalMachine -StoreName My -Session $session
     
    Demonstrates how to install a certificate from a file on the local computer into the local machine's personal store
    on a remote cmoputer. You can pass multiple sessions to the `Session` parameter.
    #>

    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName='FromFileInWindowsStore')]
    [OutputType([Security.Cryptography.X509Certificates.X509Certificate2])]
    param(
        # The path to the certificate file.
        [Parameter(Mandatory, Position=0, ParameterSetName='FromFileInWindowsStore')]
        [Parameter(Mandatory, Position=0, ParameterSetName='FromFileInCustomStore')]
        [String] $Path,
        
        # The certificate to install.
        [Parameter(Mandatory, Position=0, ParameterSetName='FromCertificateInWindowsStore')]
        [Parameter(Mandatory, Position=0, ParameterSetName='FromCertificateInCustomStore')]
        [Security.Cryptography.X509Certificates.X509Certificate2] $Certificate,
        
        # The location of the certificate's store. To see a list of acceptable values, run:
        #
        # > [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreLocation])
        [Parameter(Mandatory)]
        [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,
        
        # The name of the certificate's store. To see a list of acceptable values run:
        #
        # > [Enum]::GetValues([Security.Cryptography.X509Certificates.StoreName])
        [Parameter(Mandatory, ParameterSetName='FromFileInWindowsStore')]
        [Parameter(Mandatory, ParameterSetName='FromCertificateInWindowsStore')]
        [Security.Cryptography.X509Certificates.StoreName] $StoreName,

        # The name of the non-standard, custom store where the certificate should be installed.
        [Parameter(Mandatory, ParameterSetName='FromFileInCustomStore')]
        [Parameter(Mandatory, ParameterSetName='FromCertificateInCustomStore')]
        [String] $CustomStoreName,

        # Mark the private key as exportable. Only valid if loading the certificate from a file.
        [Parameter(ParameterSetName='FromFileInWindowsStore')]
        [Parameter(ParameterSetName='FromFileInCustomStore')]
        [switch] $Exportable,
        
        # The password for the certificate. Should be a `System.Security.SecureString`.
        [Parameter(ParameterSetName='FromFileInWindowsStore')]
        [Parameter(ParameterSetName='FromFileInCustomStore')]
        [securestring] $Password,

        # Use the `Session` parameter to install a certificate on remote computer(s) using PowerShell remoting. Use
        # `New-PSSession` to create a session.
        [Management.Automation.Runspaces.PSSession[]] $Session,

        # Re-install the certificate, even if it is already installed. Calls the `Add()` method for store even if the
        # certificate is in the store. This function assumes that the `Add()` method replaces existing certificates.
        [switch] $Force,

        # Return the installed certificate.
        [switch] $PassThru
    )
    
    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    $ephemeralKeyFlag = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet
    $defaultKeyFlag = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet

    if( $PSCmdlet.ParameterSetName -like 'FromFile*' )
    {   
        $resolvedPath = Resolve-Path -Path $Path
        if( -not $resolvedPath )
        {
            return
        }

        $Path = $resolvedPath.ProviderPath
        
        $fileBytes = [IO.File]::ReadAllBytes($Path)
        $encodedCert = [Convert]::ToBase64String($fileBytes)
        $keyFlags = $ephemeralKeyFlag
        if( (Test-COperatingSystem -MacOS) )
        {
            $keyFlags = $defaultKeyFlag
        }

        # We need the certificate thumbprint so we can check if the certificate exists or not.
        $Certificate = [Security.Cryptography.X509Certificates.X509Certificate]::New($Path, $Password, $keyFlags)
        try
        {
            $thumbprint = $Certificate.Thumbprint
        }
        finally
        {
            $Certificate.Reset()
        }
        $Certificate = $null
    }
    else
    {
        $thumbprint = $Certificate.Thumbprint
        $encodedCert = [Convert]::ToBase64String( $Certificate.RawData )
    }

    $keyFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet
    if( $StoreLocation -eq [Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser )
    {
        $keyFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::UserKeySet
    }

    $keyFlags = $keyFlags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet

    if( $Exportable )
    {
        $keyFlags = $keyFlags -bor [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
    }

    $invokeCommandArgs = @{ }
    if( $Session )
    {
        $invokeCommandArgs['Session'] = $Session
    }

    Invoke-Command @invokeCommandArgs -ScriptBlock {
        [CmdletBinding()]
        param(
            # The base64 encoded certificate to install.
            [Parameter(Mandatory)]
            [String] $EncodedCertificate,

            # The password for the certificate.
            [securestring] $Password,

            [Parameter(Mandatory)]
            [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,
        
            $StoreName,

            [string] $CustomStoreName,

            [Security.Cryptography.X509Certificates.X509KeyStorageFlags] $KeyStorageFlags,

            [bool] $Force,

            [bool] $WhatIf,

            [Management.Automation.ActionPreference] $Verbosity,
            
            [String] $Thumbprint
        )

        Set-StrictMode -Version 'Latest'

        $WhatIfPreference = $WhatIf
        $VerbosePreference = $Verbosity

        $certFilePath = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([IO.Path]::GetRandomFileName())

        [Security.Cryptography.X509Certificates.X509Certificate2] $cert = $null
        [Security.Cryptography.X509Certificates.X509Store] $store = $null
        if( $CustomStoreName )
        {
            $storeNameDisplay = $CustomStoreName
            $store = [Security.Cryptography.X509Certificates.X509Store]::New($CustomStoreName, $StoreLocation)
        }
        else
        {
            $StoreName = [Security.Cryptography.X509Certificates.StoreName]$StoreName
            $storeNameDisplay = $StoreName.ToString()
            $store = [Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation)
        }

        if( -not $Force )
        {
            try
            {
                $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly) )
                if( $store.Certificates | Where-Object 'Thumbprint' -eq $Thumbprint )
                {
                    return
                }
            }
            catch
            {
                $msg = "Exception reading certificates from $($StoreLocation)\$($storeNameDisplay) store: $($_)"
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }
            finally
            {
                $store.Close()
            }
        }

        $certBytes = [Convert]::FromBase64String( $EncodedCertificate )
        [IO.File]::WriteAllBytes( $certFilePath, $certBytes )

        # Make sure the key isn't persisted if we're not going to store it.
        if( $WhatIf )
        {
            # We don't use EphemeralKeySet because it isn't supported on macOS.
            $KeyStorageFlags = [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet
        }

        try
        {
            $cert = 
                [Security.Cryptography.X509Certificates.X509Certificate2]::New($certFilePath, $Password, $KeyStorageFlags)
        }
        catch
        {
            $msg = "Exception reading certificate from file: $($_)"
            Write-Error -Message $msg -ErrorAction $ErrorActionPreference
            return
        }
        
        $description = $cert.FriendlyName
        if( -not $description )
        {
            $description = $cert.Subject
        }

        try
        {
            $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) )

            $action = "install into $($StoreLocation)\$($storeNameDisplay) store"
            $target = "$($description) ($($cert.Thumbprint))"
            if( $PSCmdlet.ShouldProcess($target, $action) )
            {
                $msg = "Installing certificate ""$($description)"" ($($cert.Thumbprint)) into $($StoreLocation)\" +
                    "$($storeNameDisplay) store."
                Write-Verbose -Message $msg 
                $store.Add( $cert )
            }
        }
        catch
        {
            if( (Test-COperatingSystem -MacOS) -and ($cert.HasPrivateKey -and -not $Exportable) )
            {
                $msg = "Exception installing certificate ""$($description)"" ($($cert.Thumbprint)) into " +
                       "$($StoreLocation)\$($storeNameDisplay): $($_). On macOS, certificates with private keys " +
                       "must be exportable. Update $($MyInvocation.MyCommand.Name) with the ""-Exportable"" switch."
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }

            $msg = "Exception installing certificate in $($StoreLocation)\$($storeNameDisplay) store: $($_)"
            Write-Error -Message $msg -ErrorAction $ErrorActionPreference
            return
        }
        finally
        {
            Remove-Item -Path $certFilePath -ErrorAction Ignore -WhatIf:$false -Force

            if( $cert )
            {
                $cert.Reset()
            }

            if( $store )
            {
                $store.Close()
            }
        }
    } -ArgumentList $encodedCert,
                    $Password,
                    $StoreLocation,
                    $StoreName,
                    $CustomStoreName,
                    $keyFlags,
                    $Force,
                    $WhatIfPreference,
                    $VerbosePreference,
                    $thumbprint

    if( $PassThru )
    {
        # Don't return a certificate object created by this function. It may have been loaded from a file and stored
        # in a temp file on disk. If that certificate object isn't properly disposed, the temp file can stick around
        # slowly filling up disks.
        $storeParam = @{ StoreName = $StoreName }
        if( $CustomStoreName )
        {
            $storeParam = @{ CustomStoreName = $CustomStoreName }
        }
        return Get-CCertificate -Thumbprint $thumbprint -StoreLocation $StoreLocation @storeParam
    }
}




function New-CRsaKeyPair
{
    <#
    .SYNOPSIS
    Generates a public/private RSA key pair.
 
    .DESCRIPTION
    The `New-CRsaKeyPair` function uses the `certreq.exe` program to generate an RSA public/private key pair suitable
    for use in encrypting/decrypting CMS messages, credentials in DSC resources, etc.
 
    Pass the subject to the `Subject` parameter (it must begin with `CN=`) and the paths where you want the public and
    private keys saved to the `PublicKeyPath` and `PrivateKeyPath` parameters, respectively. `New-CRsaKeyPair` creates
    a temporary .inf file and passes it to the `certreq.exe` program. You will be prompted for a password, unless you
    pass a password to the `Password` parameter.
     
    By default, a key pair with no key usages or enhanced key usages is generated that is 4096 bits in length, uses
    `SHA512` as the signature/hash algorithm, and is valid until December 31st, 9999. An object with
    `[IO.FileInfo] PublicKeyFile` and `[IO.FileInfo] PrivateKeyFile` properties is returned.
 
    You can change the key's length, algorithm, and expiration data with the `Length`, `Algorithm`, and `ValidTo`
    parameters. You can set the key pair's usages with the `KeyUsage` parameter. Valid usages this function supports
    are `ClientAuthentication`, `CodeSigning`, `DocumentEncryption`, `DocumentSigning`, and `ServerAuthentication`.
 
    If the destination files already exist, you'll get an error and no keys will be generated. Use the `Force` switch to
    overwrite any existing files.
 
    The `certreq.exe` command stores the private key in the current user's `My` certificate store. This function exports
    that private key to a file and removes it from the current user's `My` store. The private key is protected with the
    password provided via the `-Password` parameter. If you don't provide a password, you will be prompted for one. To
    not protect the private key with a password, pass `$null` as the value of the `-Password` parameter.
 
    The public key is saved as an X509Certificate. The private key is saved as a PFX file. Both can be loaded by .NET's
    `X509Certificate` class. Returns `System.IO.FileInfo` objects for the public and private key, in that order.
 
    .LINK
    Get-CCertificate
 
    .LINK
    Install-CCertificate
 
    .EXAMPLE
    New-CRsaKeyPair -Subject 'CN=MyName' -PublicKeyFile 'MyName.cer' -PrivateKeyFile 'MyName.pfx' -Password $secureString
 
    Demonstrates the minimal parameters needed to generate a key pair. The key will use a sha512 signing algorithm, have
    a length of 4096 bits, and expire on `12/31/9999`. The public key will be saved in the current directory as
    `MyName.cer`. The private key will be saved to the current directory as `MyName.pfx` and protected with password in
    `$secureString`. The key pair will have no usages, so you won't be able to do much with it.
 
    .EXAMPLE
    New-CRsaKeyPair -Subject 'CN=MyName' -PublicKeyFile 'MyName.cer' -PrivateKeyFile 'MyName.pfx' -Password $null
 
    Demonstrates how to save the private key unprotected (i.e. without a password). You must set the password to
    `$null`. This functionality was introduced in Carbon 2.1.
 
    .EXAMPLE
    New-CRsaKeyPair -Subject 'CN=MyName' -PublicKeyFile 'MyName.cer' -PrivateKeyFile 'MyName.pfx' -Algorithm 'sha1' -ValidTo (Get-Date -Year 2015 -Month 12 -Day 31) -Length 1024 -Password $secureString -KeyUsage DocumentSigning, DocumentEncryption
 
    Demonstrates how to use all the parameters to create a truly customized key pair. The generated certificate will use
    the sha1 signing algorithm, expires 12/31/2015, is 1024 bits in length, and can be used to sign and encrypt.
    #>

    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingUserNameAndPassWordParams', '')]
    param(
        # The key's subject. Should be of the form `CN=Name,OU=Name,O=SuperMagicFunTime,ST=OR,C=US`. Only the `CN=Name`
        # part is required.
        [Parameter(Mandatory, Position=0)]
        [ValidatePattern('^CN=')]
        [string] $Subject,

        # The signature algorithm. Default is `sha512`.
        [ValidateSet('md5', 'sha1', 'sha256', 'sha384', 'sha512')]
        [string] $Algorithm = 'sha512',

        # The date/time the keys should expire. Default is `DateTime::MaxValue`.
        [DateTime] $ValidTo = ([DateTime]::MaxValue),

        # The length, in bits, of the generated key length. Default is `4096`.
        [int] $Length = 4096,

        # What extended key usages the certificate will have. By default, it will be for any purpose (OID 2.5.29.37.0).
        [ValidateSet('ClientAuthentication', 'CodeSigning', 'DocumentEncryption', 'DocumentSigning',
                     'ServerAuthentication')]
        [String[]] $KeyUsage,

        # The file where the public key should be stored. Saved as an X509 certificate.
        [Parameter(Mandatory, Position=1)]
        [string] $PublicKeyFile,

        # The file where the private key should be stored. The private key will be saved as an X509 certificate in PFX
        # format and will include the public key.
        [Parameter(Mandatory, Position=2)]
        [string] $PrivateKeyFile,

        # The password for the private key. If one is not provided, you will be prompted for one. Pass `$null` to not
        # protect your private key with a password.
        #
        # This parameter was introduced in Carbon 2.1.
        [securestring] $Password,

        # Overwrites `PublicKeyFile` and/or `PrivateKeyFile`, if they exist.
        [Switch] $Force
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    function Resolve-KeyPath
    {
        param(
            [Parameter(Mandatory)]
            [string] $Path
        )

        Set-StrictMode -Version 'Latest'

        $Path = [IO.Path]::GetFullPath($Path)

        if( (Test-Path -Path $Path -PathType Leaf) )
        {
            if( -not $Force )
            {
                Write-Error ('File ''{0}'' exists. Use the -Force switch to overwrite.' -f $Path)
                return
            }
        }
        else
        {
            $root = Split-Path -Parent -Path $Path
            if( -not (Test-Path -Path $root -PathType Container) )
            {
                New-Item -Path $root -ItemType 'Directory' -Force | Out-Null
            }
        }

        return $Path
    }

    $PublicKeyFile = Resolve-KeyPath -Path $PublicKeyFile
    if( -not $PublicKeyFile )
    {
        return
    }

    $PrivateKeyFile = Resolve-KeyPath -Path $PrivateKeyFile
    if( -not $PrivateKeyFile )
    {
        return
    }

    if( (Test-Path -Path $PrivateKeyFile -PathType Leaf) )
    {
        if( -not $Force )
        {
            Write-Error ('Private key file ''{0}'' exists. Use the -Force switch to overwrite.' -f $PrivateKeyFile)
            return
        }
    }

    $tempDir = '{0}-{1}' -f (Split-Path -Leaf -Path $PSCommandPath),([IO.Path]::GetRandomFileName())
    $tempDir = Join-Path -Path $env:TEMP -ChildPath $tempDir
    New-Item -Path $tempDir -ItemType 'Directory' | Out-Null
    $tempInfFile = Join-Path -Path $tempDir -ChildPath 'temp.inf'

    # Adapted from
    # * https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/certreq_1
    # * https://docs.microsoft.com/en-us/windows/win32/api/certenroll/ne-certenroll-x509keyusageflags
    # * https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509keyusageflags
    # * https://omvs.de/2019/11/13/key-usage-extensions-at-x-509-certificates/
    # CERT_DIGITAL_SIGNATURE_KEY_USAGE (0x80/128):
    # The key can be used as a digital signature. The key is used with a Digital Signature Algorithm (DSA) to support
    # services other than nonrepudiation, certificate signing, or revocation list signing.
    # CERT_NON_REPUDIATION_KEY_USAGE (0x40/64):
    # The key can be used for authentication. The key is used to verify a digital signature as part of a
    # nonrepudiation service that protects against false denial of action by a signing entity.
    # CERT_KEY_ENCIPHERMENT_KEY_USAGE (0x20/32):
    # The key can be used for key encryption. The key is used for key transport. That is, the key is used to manage a
    # key passed from its point of origination to another point of use.
    # CERT_DATA_ENCIPHERMENT_KEY_USAGE (0x10/16):
    # The key can be used for data encryption. The key is used to encrypt user data other than cryptographic keys.
    # CERT_KEY_AGREEMENT_KEY_USAGE (8):
    # The key can be used to determine key agreement, such as a key created using the Diffie-Hellman key agreement
    # algorithm. The key agreement or key exchange protocol enables two or more
    # parties to negotiate a key value without transferring the key and without previously establishing a shared
    # secret.
    # CERT_KEY_CERT_SIGN_KEY_USAGE (4):
    # The key can be used to sign certificates. The key is used to verify a certificate signature. This value can only
    # be used for certificates issued by certification authorities.
    # CERT_OFFLINE_CRL_SIGN_KEY_USAGE (2):
    # The key can be used to sign a certificate revocation list (CRL). The key is used to verify an offline
    # certificate revocation list (CRL) signature.
    # CERT_CRL_SIGN_KEY_USAGE (2):
    # The key can be used to sign a certificate revocation list (CRL). The key is used to verify a CRL signature.
    # CERT_ENCIPHER_ONLY_KEY_USAGE (1):
    # The key can be used for encryption only. The key is used to encrypt data while performing key agreement. When
    # this value is specified, the CERT_KEY_AGREEMENT_KEY_USAGE value must also be specified.
    # CERT_DECIPHER_ONLY_KEY_USAGE (0x8000/32768):
    # The key can be used for decryption only. The key is used to decrypt data while performing key agreement. When
    # this value is specified, the CERT_KEY_AGREEMENT_KEY_USAGE must also be specified.

    $usageMap = @{
        ClientAuthentication = @('CERT_DIGITAL_SIGNATURE_KEY_USAGE', 'CERT_KEY_ENCIPHERMENT_KEY_USAGE');
        CodeSigning = 'CERT_DIGITAL_SIGNATURE_KEY_USAGE';
        DocumentEncryption = @('CERT_KEY_ENCIPHERMENT_KEY_USAGE', 'CERT_DATA_ENCIPHERMENT_KEY_USAGE');
        DocumentSigning = 'CERT_DIGITAL_SIGNATURE_KEY_USAGE';
        ServerAuthentication = @('CERT_DIGITAL_SIGNATURE_KEY_USAGE', 'CERT_KEY_ENCIPHERMENT_KEY_USAGE');
    }

    try
    {
        $certReqPath = Get-Command -Name 'certreq.exe' -ErrorAction Ignore | Select-Object -ExpandProperty 'Path'
        if( -not $certReqPath )
        {
            'Command "certreq.exe" does not exist. This is a Windows-only command. If you''re on Windows, make sure ' +
            '"C:\Windows\System32" is part of your "Path" environment variable.' |
                Write-Error -ErrorAction $ErrorActionPreference
            return
        }

        # Taken from example 1 of the Protect-CmsMessage help topic.
        [int]$daysValid = [Math]::Floor(($ValidTo - (Get-Date)).TotalDays)
        [int]$MaxDaysValid = [Math]::Floor(([DateTime]::MaxValue - [DateTime]::UtcNow).TotalDays)
        Write-Debug -Message ('Days Valid: {0}' -f $daysValid)
        Write-Debug -Message ('Max Days Valid: {0}' -f $MaxDaysValid)
        if( $daysValid -gt $MaxDaysValid )
        {
            Write-Debug -Message ('Adjusted Days Valid: {0}' -f $daysValid)
            $daysValid = $MaxDaysValid
        }

        $keyUsages = & {
            foreach( $usage in $KeyUsage )
            {
                if( $usageMap.ContainsKey($usage) )
                {
                    $usageMap[$usage] | Write-Output
                }
            }
        } | Select-Object -Unique

        $extensions = & {
            if( -not $KeyUsage )
            {
                return
            }

            foreach( $usage in $KeyUsage )
            {
                switch( $usage )
                {
                    'ClientAuthentication' { 'szOID_CLIENT_AUTHENTICATION' }
                    'CodeSigning' { 'szOID_CODE_SIGNING' }
                    'DocumentEncryption' { 'szOID_DOCUMENT_ENCRYPTION' }
                    'DocumentSigning' { 'szOID_DOCUMENT_SIGNING' }
                    'ServerAuthentication' { 'szOID_SERVER_AUTHENTICATION' }
                }
            }
        }

        $keySpec = 'AT_NONE'
        if( $KeyUsage | Where-Object { $_ -like '*Signing' } )
        {
            $keySpec = 'AT_SIGNATURE'
        }
        if( $KeyUsage | Where-Object { $_ -notlike '*Signing' } )
        {
            $keySpec = 'AT_KEYEXCHANGE'
        }

        $keyUsageLine = ''
        if( $keyUsages )
        {
            $keyUsageLine = "KeyUsage = ""$($keyUsages -join ' | ')"""
        }

        $extensionsLine = ''
        if( $extensions )
        {
            $extensionsLine = $extensions -join "%,""$([Environment]::NewLine)_continue_ = ""%"
            $extensionsLine = "%szOID_ENHANCED_KEY_USAGE% = ""{text}%$($extensionsLine)%"""
        }
        
        @"
[Version]
Signature = "`$Windows NT`$"
 
[Strings]
szOID_ANY_PURPOSE = 2.5.29.37.0
szOID_CLIENT_AUTHENTICATION = 1.3.6.1.5.5.7.3.2
szOID_CODE_SIGNING = 1.3.6.1.5.5.7.3.3
szOID_DOCUMENT_ENCRYPTION = 1.3.6.1.4.1.311.80.1
szOID_DOCUMENT_SIGNING = 1.3.6.1.4.1.311.10.3.12
szOID_ENHANCED_KEY_USAGE = 2.5.29.37
szOID_SERVER_AUTHENTICATION = 1.3.6.1.5.5.7.3.1
 
[NewRequest]
Subject = "$($Subject)"
MachineKeySet = false
KeyLength = $($Length)
KeySpec = $($keySpec)
HashAlgorithm = $($Algorithm)
Exportable = true
RequestType = Cert
ValidityPeriod = Days
ValidityPeriodUnits = $($daysValid)
$($keyUsageLine)
 
[Extensions]
$($extensionsLine)
"@
 | Set-Content -Path $tempInfFile

        Get-Content -Raw -Path $tempInfFile | Write-Verbose

        $forceArg = ''
        if( $Force )
        {
            $forceArg = ' -f'
        }
        Write-Debug "& ""$($certReqPath)"" -q$($forceArg) -new ""$($tempInfFile)"" ""$($PublicKeyFile)"""
        $output = & $certReqPath -q ($forceArg.TrimStart()) -new $tempInfFile $PublicKeyFile 
        if( $LASTEXITCODE -or -not (Test-Path -Path $PublicKeyFile -PathType Leaf) )
        {
            Write-Error ('Failed to create public/private key pair:{0}{1}' -f ([Environment]::NewLine),($output -join ([Environment]::NewLine)))
            return
        }
        else
        {
            $output | Write-Debug
        }

        $publicKey = Get-CCertificate -Path $PublicKeyFile
        if( -not $publicKey )
        {
            Write-Error ('Failed to load public key ''{0}'':{1}{2}' -f $PublicKeyFile,([Environment]::NewLine),($output -join ([Environment]::NewLine)))
            return
        }

        $privateCertPath = Join-Path -Path 'cert:\CurrentUser\My' -ChildPath $publicKey.Thumbprint
        if( -not (Test-Path -Path $privateCertPath -PathType Leaf) )
        {
            Write-Error -Message ('Private key ''{0}'' not found. Did certreq.exe fail to install the private key there?' -f $privateCertPath)
            return
        }

        try
        {
            $privateCert = Get-Item -Path $privateCertPath
            if( -not $privateCert.HasPrivateKey )
            {
                Write-Error -Message ('Certificate ''{0}'' doesn''t have a private key.' -f $privateCertPath)
                return
            }

            if( -not $PSBoundParameters.ContainsKey('Password') )
            {
                $Password = Read-Host -Prompt 'Enter private key password' -AsSecureString
            }

            $privateCertBytes = $privateCert.Export( 'PFX', $Password )
            [IO.File]::WriteAllBytes( $PrivateKeyFile, $privateCertBytes )

            [pscustomobject]@{
                'PublicKeyFile' = (Get-Item $PublicKeyFile);
                'PrivateKeyFile' = (Get-Item $PrivateKeyFile);
            } | Write-Output
        }
        finally
        {
            Remove-Item -Path $privateCertPath
        }
    }
    finally
    {
        Remove-Item -Path $tempDir -Recurse
    }
}



function Protect-CString
{
    <#
    .SYNOPSIS
    Encrypts a string.
 
    .DESCRIPTION
    The `Protect-CString` function encrypts a string using the Windows Data Protection API (DPAPI), RSA, or AES. Pass
    a plaintext string or a secure string to the `String` parameter. When encrypting a `SecureString`, it is converted
    to an array of bytes, encrypted, then the array of bytes is cleared from memory (i.e. the plaintext version of the
    `SecureString` is only in memory long enough to encrypt it). All strings and secure string bytes are re-encoded
    from UTF-16/Unicode to UTF-8 before encrypting.
 
    ## Windows Data Protection API (DPAPI)
 
    The DPAPI hides the encryptiong/decryption keys. There is a unique key for each user and a machine key. Anything
    encrypted with a user's key, can only be decrypted by that user. Anything encrypted with the machine key can be
    decrypted by anyone on that machine. Use the `ForUser` switch to encrypt with the current user's key. Use the
    `ForComputer` switch to encrypt at the machine level.
 
    If you want to encrypt something as a different user, pass that user's credentials to the `Credential` parameter.
    `Protect-CString` will launch a PowerShell process as that user to do the encryption. Encrypting as another user
    doesn't work over PowerShell Remoting.
 
    ## RSA
 
    RSA is an assymetric encryption/decryption algorithm, which requires a public/private key pair. The secret is
    encrypted with the public key, and can only be decrypted with the corresponding private key. The secret being
    encrypted can't be larger than the RSA key pair's size/length, usually 1024, 2048, or 4096 bits (128, 256, and 512
    bytes, respectively). `Protect-CString` encrypts with .NET's `System.Security.Cryptography.RSACryptoServiceProvider`
    class.
 
    You can specify the public key in three ways:
 
     * by passing the `System.Security.Cryptography.X509Certificates.X509Certificate2` object to use to the
       `Certificate` parameter.
     * with a certificate in one of the Windows certificate stores. Pass its thumbprint to the `Thumbprint`
       parameter.
     * with an X509 certificate file. Pass the file's path to the `PublicKeyPath` parameter. You can also pass a
       certificate provider path to the `PublicKeyPath` parameter (e.g. `cert:`).
 
    You can generate an RSA public/private key pair with the `New-CRsaKeyPair` function.
 
    ## AES
 
    AES is a symmetric encryption/decryption algorithm. You supply a 16-, 24-, or 32-byte key/password/passphrase with
    the `Key` parameter, and that key is used to encrypt. There is no limit on the size of the data you want to encrypt.
    `Protect-CString` encrypts with the object returned by `[Security.Cryptography.Aes]::Create()`
 
    You can only pass a `[securestring]` or array of bytes as the key. The array of bytes must be 16, 24, or 32 bytes
    long. When passing a secure string, when UTF-8 encoded and converted to a byte array, it must also be 16, 24, or 32
    bytes long. You can use this code to check on the byte length of a plain text string (where $key is the plain text
    key):
 
        [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length
 
    Symmetric encryption requires a random, unique initialization vector (i.e. IV) everytime you encrypt something.
    `Protect-CString` generates one for you. This IV must be known to decrypt the secret, so it is pre-pendeded to the
    encrypted text.
 
    This code demonstrates how to generate a key:
 
        $key = [Security.Cryptography.AesManaged]::New().Key
 
    You can save this key as a string by encoding it as a base64 string:
 
        $base64EncodedKey = [Convert]::ToBase64String($key)
 
    If you base64 encode your key's bytes, they must be converted back to bytes before passing it to `Protect-CString`.
 
        Protect-CString -String 'the secret sauce' -Key ([Convert]::FromBase64String($base64EncodedKey))
 
    .LINK
    New-CRsaKeyPair
 
    .LINK
    Unprotect-CString
 
    .LINK
    http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx
 
    .EXAMPLE
    Protect-CString -String 'TheStringIWantToEncrypt' -ForUser | Out-File MySecret.txt
 
    Encrypts the given string and saves the encrypted string into MySecret.txt. Only the user who encrypts the string
    can unencrypt it.
 
    .EXAMPLE
    Protect-CString -String $credential.Password -ForUser | Out-File MySecret.txt
 
    Demonstrates that `Protect-CString` can encrypt a `SecureString`.
 
    .EXAMPLE
    Protect-CString -String "MySuperSecretIdentity" -ForComputer
 
    Demonstrates how to encrypt a value that can only be decrypted on the current computer.
 
    .EXAMPLE
    Protect-CString -String 's0000p33333r s33333cr33333t' -Credential (Get-Credential 'builduser')
 
    Demonstrates how to use `Protect-CString` to encrypt a secret as a specific user. This is useful for situation where
    a secret needs to be encrypted by a user other than the user running `Protect-CString`. Encrypting as a specific
    user won't work over PowerShell remoting.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Certificate $myCert
 
    Demonstrates how to encrypt a secret using RSA with a `System.Security.Cryptography.X509Certificates.X509Certificate2`
    object. You're responsible for creating/loading the certificate. The `New-CRsaKeyPair` function will create a key
    pair for you, if you've got a Windows SDK installed.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Thumbprint '44A7C27F3353BC53F82318C14490D7E2500B6D9E'
 
    Demonstrates how to encrypt a secret using RSA with a certificate in one of the Windows certificate stores. All
    local machine and user stores are searched for the certificate with the given thumbprint that has a private key.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -PublicKeyPath 'C:\Projects\Security\publickey.cer'
 
    Demonstrates how to encrypt a secret using RSA with a certificate file. The file must be loadable by the
    `System.Security.Cryptography.X509Certificates.X509Certificate` class.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -PublicKeyPath 'cert:\LocalMachine\My\44A7C27F3353BC53F82318C14490D7E2500B6D9E'
 
    Demonstrates how to encrypt a secret using RSA with a certificate in the Windows certificate store, giving its exact
    path.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Key 'gT4XPfvcJmHkQ5tYjY3fNgi7uwG4FB9j'
 
    Demonstrates how to encrypt a secret with a key, password, or passphrase. In this case, we are encrypting with a
    plaintext password.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Key (Read-Host -Prompt 'Enter password (must be 16, 24, or 32 characters long):' -AsSecureString)
 
    Demonstrates that you can use a `SecureString` as the key, password, or passphrase.
 
    .EXAMPLE
    Protect-CString -String 'the secret sauce' -Key ([byte[]]@(163,163,185,174,205,55,157,219,121,146,251,116,43,203,63,38,73,154,230,112,82,112,151,29,189,135,254,187,164,104,45,30))
 
    Demonstrates that you can use an array of bytes as the key, password, or passphrase.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position=0, ValueFromPipeline)]
        # The string to encrypt. Any non-string object you pass will be converted to a string before encrypting by
        # calling the object's `ToString` method.
        #
        # This can also be a `SecureString` object. The `SecureString` is converted to an array of bytes, the bytes are
        # encrypted, then the plaintext bytes are cleared from memory (i.e. the plaintext password is in memory for the
        # amount of time it takes to encrypt it). Passing a secure string is the most secure usage.
        #
        # The string and secure string bytes are re-encoded as UTF-8 before encrypting.
        [Object]$String,

        [Parameter(Mandatory, ParameterSetName='DPAPICurrentUser')]
        # Encrypts for the current user so that only they can decrypt.
        [switch]$ForUser,

        [Parameter(Mandatory, ParameterSetName='DPAPILocalMachine')]
        # Encrypts for the current computer so that any user logged into the computer can decrypt.
        [switch]$ForComputer,

        [Parameter(Mandatory, ParameterSetName='DPAPIForUser')]
        # Encrypts for a specific user.
        [pscredential]$Credential,

        [Parameter(Mandatory, ParameterSetName='RsaByCertificate')]
        # The public key to use for encrypting.
        [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,

        [Parameter(Mandatory, ParameterSetName='RsaByThumbprint')]
        # The thumbprint of the certificate, found in one of the Windows certificate stores, to use when encrypting. All
        # certificate stores are searched.
        [String]$Thumbprint,

        [Parameter(Mandatory, ParameterSetName='RsaByPath')]
        # The path to the public key to use for encrypting. Must be to an `X509Certificate2` object.
        [String]$PublicKeyPath,

        [Parameter(ParameterSetName='RsaByCertificate')]
        [Parameter(ParameterSetName='RsaByPath')]
        [Parameter(ParameterSetName='RsaByThumbprint')]
        # The padding mode to use when encrypting. When using an RSA public key, defaults to
        # [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1.
        [Security.Cryptography.RSAEncryptionPadding]$Padding,

        [Parameter(Mandatory, ParameterSetName='Symmetric')]
        # The key to use to encrypt the secret. Must be a `[securestring]` or an array of bytes. If passing a byte
        # array, # must be 16, 24, or 32 bytes long. If passing a secure string, when it is UTF-8 encoded and converted
        # to a byte # array, that array must also be 16, 24, or 32 bytes long. This code will tell you the length, in
        # bytes, of your plain text key (stored in the `$key`variable):
        #
        # [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length
        [Object]$Key
    )

    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        # We find and validate the certificate/key here so our try/catch block around actual encryption doesn't catch
        # these errors.
        [byte[]]$keyBytes = [byte[]]::New(0)
        if( $PSCmdlet.ParameterSetName -like 'Rsa*' )
        {
            if( $PSCmdlet.ParameterSetName -eq 'RsaByThumbprint' )
            {
                $Certificate = Get-Item -Path ('cert:\*\*\{0}' -f $Thumbprint) | Select-Object -First 1
                if( -not $Certificate )
                {
                    Write-Error "Certificate with thumbprint ""$($Thumbprint)"" not found."
                    return
                }
            }
            elseif( $PSCmdlet.ParameterSetName -eq 'RsaByPath' )
            {
                $Certificate = Get-CCertificate -Path $PublicKeyPath
                if( -not $Certificate )
                {
                    return
                }
            }

            $rsaKey = $Certificate.PublicKey.Key
            if( -not $rsaKey.GetType().IsSubclassOf([Security.Cryptography.RSA]) )
            {
                $msg = "Certificate ""$($Certificate.Subject)"" ($($Certificate.Thumbprint)) is not an RSA public " +
                    "key. Found a public key of type ""$($rsaKey.GetType().FullName)"", but expected type " +
                    """$([Security.Cryptography.RSACryptoServiceProvider].FullName)""."
                Write-Error $msg
                return
            }
        }
        elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' )
        {
            $keyBytes = ConvertTo-AesKey -InputObject $Key -From 'Protect-CString'
            if( -not $keyBytes )
            {
                return
            }
        }


        $stringBytes = [byte[]]::New(0)
        $unicodeBytes = [Text.Encoding]::Unicode.GetBytes( $String.ToString() )
        [byte[]]$encryptedBytes = [byte[]]::New(0)
        try
        {
            if( $String -is [securestring] )
            {
                $unicodeBytes = Convert-CSecureStringToByte -SecureString $String
            }
            # Unicode takes up two bytes, so the max length of strings we can encrypt is cut from about 472 characters
            # to 236. Let's re-encode in UTF-8, which only uses one byte per character. This also maintains
            # backwards-compatability with Carbon 2.
            $stringBytes = [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, $unicodeBytes)
        }
        finally
        {
            $unicodeBytes.Clear()
        }

        try
        {
            if( $PSCmdlet.ParameterSetName -like 'DPAPI*' )
            {
                if( $PSCmdlet.ParameterSetName -eq 'DPAPIForUser' )
                {
                    $protectStringPath = Join-Path -Path $moduleBinRoot -ChildPath 'Protect-CString.ps1' -Resolve
                    $encodedString = Protect-CString -String $String -ForComputer
                    $powershellArgs = @(
                        '-ExecutionPolicy',
                        'ByPass',
                        '-NonInteractive',
                        '-File',
                        $protectStringPath,
                        '-ProtectedString',
                        $encodedString
                    )
                    return Invoke-CPowerShell -ArgumentList $powershellArgs -Credential $Credential | Select-Object -First 1
                }
                else
                {
                    $scope = [Security.Cryptography.DataProtectionScope]::CurrentUser
                    if( $PSCmdlet.ParameterSetName -eq 'DPAPILocalMachine' )
                    {
                        $scope = [Security.Cryptography.DataProtectionScope]::LocalMachine
                    }

                    $encryptedBytes = [Security.Cryptography.ProtectedData]::Protect( $stringBytes, $null, $scope )
                }
            }
            elseif( $PSCmdlet.ParameterSetName -like 'Rsa*' )
            {

                if( -not $Padding )
                {
                    $Padding = [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1
                }

                $encryptedBytes = $Certificate.PublicKey.Key.Encrypt($stringBytes, $Padding)
            }
            elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' )
            {
                $aes = [Security.Cryptography.Aes]::Create()
                try
                {
                    $aes.Padding = [Security.Cryptography.PaddingMode]::PKCS7
                    $aes.KeySize = $keyBytes.Length * 8
                    $aes.Key = $keyBytes

                    $memoryStream = [IO.MemoryStream]::New()
                    try
                    {
                        $cryptoStream =
                            [Security.Cryptography.CryptoStream]::New(
                                $memoryStream,
                                $aes.CreateEncryptor(),
                                ([Security.Cryptography.CryptoStreamMode]::Write)
                            )

                        try
                        {
                            $cryptoStream.Write($stringBytes, 0, $stringBytes.Length)
                        }
                        finally
                        {
                            $cryptoStream.Dispose()
                        }

                        $encryptedBytes = & {
                                                $aes.IV
                                                $memoryStream.ToArray()
                                            }
                    }
                    finally
                    {
                        $memoryStream.Dispose()
                    }
                }
                finally
                {
                    $aes.Dispose()
                }
            }

            return [Convert]::ToBase64String( $encryptedBytes )
        }
        catch
        {
            Write-Error -ErrorRecord $_ -ErrorAction $ErrorActionPreference
        }
        finally
        {
            if( $encryptedBytes )
            {
                $encryptedBytes.Clear()
            }

            if( $stringBytes )
            {
                $stringBytes.Clear()
            }

            if( $keyBytes )
            {
                $keyBytes.Clear()
            }
        }
    }
}



function Uninstall-CCertificate
{
    <#
    .SYNOPSIS
    Removes a certificate from a certificate store.
     
    .DESCRIPTION
    The `Uninstall-CCertificate` function uses .NET's certificates API to remove a certificate from a certificate store
    for the machine or current user. Use the thumbprint to identify which certificate to remove. The thumbprint is
    unique to each certificate. The user performing the removal must have read and write permission on the store where
    the certificate is located.
 
    If the certificate isn't in the store, nothing happens, not even an error.
 
    To uninstall a certificate from a remote computer, use the `Session`parameter. You can create a new session with the
    `New-PSSession` cmdlet. You can pass multiple sessions.
 
    You can uninstall a certificate using just its thumbprint. `Uninstall-CCertificate` will search through all
    certificate locations and stores and uninstall all certificates that have the thumbprint. When you enumerate all
    certificates over a remoting session, you get a terminating `The system cannot open the device or file specified`
    error, so you can't delete a certificate with just a thumbprint over remoting.
 
    .EXAMPLE
    Uninstall-CCertificate -Thumbprint '570895470234023dsaaefdbcgbefa'
 
    Demonstrates how to delete a certificate from all stores it is installed in. `Uninstall-CCertificate` searches every
    certificate stores and deletes all certificates with the given thumbprint.
 
    .EXAMPLE
    '570895470234023dsaaefdbcgbefa' | Uninstall-CCertificate
 
    Demonstrates that you can pipe a thumbprint to `Uninstall-CCertificate`. The certificate is uninstall from all
    stores it is in.
 
    .EXAMPLE
    Get-Item -Path 'cert:\LocalMachine\My\570895470234023dsaaefdbcgbefa' | Uninstall-CCertificate
 
    Demonstrates that you can pipe a certificate `Uninstall-CCertificate`. The certificate is uninstalled from all
    stores it is in.
 
    .EXAMPLE
    Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation CurrentUser -StoreName My
     
    Removes the 570895470234023dsaaefdbcgbefa certificate from the current user's Personal certificate store.
     
    .EXAMPLE
    Uninstall-CCertificate -Certificate $cert -StoreLocation LocalMachine -StoreName Root
     
    Demonstrates how you can remove a certificate by passing it to the `Certificate` parameter.
 
    .EXAMPLE
    Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation LocalMachine -StoreName 'SharePoint'
 
    Demonstrates how to uninstall a certificate from a custom, non-standard store.
 
    .EXAMPLE
    Uninstall-CCertificate -Thumbprint 570895470234023dsaaefdbcgbefa -StoreLocation CurrentUser -StoreName My -Session $session
     
    Demonstrates how to uninstall a certificate from a remote computer.
    #>

    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName='ByThumbprint')]
    param(
        # The thumbprint of the certificate to remove.
        #
        # If you want to uninstall the certificate from all stores it is installed in, you can pipe the thumbprint to this parameter or you can pipe a certificate object. (This functionality was added in Carbon 2.5.0.)
        [Parameter(Mandatory, ParameterSetName='ByThumbprint', ValueFromPipelineByPropertyName, ValueFromPipeline)]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        [String] $Thumbprint,
        
        # The certificate to remove
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        [Security.Cryptography.X509Certificates.X509Certificate2] $Certificate,
        
        # The location of the certificate's store.
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,
        
        # The name of the certificate's store.
        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndStoreName')]
        [Security.Cryptography.X509Certificates.StoreName] $StoreName,

        [Parameter(Mandatory, ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(Mandatory, ParameterSetName='ByCertificateAndCustomStoreName')]
        [String] $CustomStoreName,

        # Use the `Session` parameter to uninstall a certificate on remote computer(s) using PowerShell remoting. Use
        # `New-PSSession` to create a session.
        #
        # Due to a bug in PowerShell, you can't remove a certificate by just its thumbprint over remoting. Using just a
        # thumbprint requires us to enumerate through all installed certificates. When you do this over remoting,
        # PowerShell throws a terminating `The system cannot open the device or file specified` error.
        [Parameter(ParameterSetName='ByThumbprintAndStoreName')]
        [Parameter(ParameterSetName='ByThumbprintAndCustomStoreName')]
        [Parameter(ParameterSetName='ByCertificateAndStoreName')]
        [Parameter(ParameterSetName='ByCertificateAndCustomStoreName')]
        [Management.Automation.Runspaces.PSSession[]] $Session
    )
    
    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        if( $PSCmdlet.ParameterSetName -eq 'ByThumbprint' )
        {
            # Must be in this order. Delete LocalMachine certs *first* so they don't show
            # up in CurrentUser stores. If you delete a certificate that "cascades" into
            # the CurrentUser store first, you'll get errors when running non-
            # interactively as SYSTEM.
            $certsToDelete = & {
                Get-CCertificate -StoreLocation LocalMachine -Thumbprint $Thumbprint
                Get-CCertificate -StoreLocation CurrentUser -Thumbprint $Thumbprint
            }
            foreach( $certToDelete in $certsToDelete )
            {
                Uninstall-CCertificate -Thumbprint $Thumbprint `
                                      -StoreLocation $certToDelete.StoreLocation `
                                      -StoreName $certToDelete.StoreName
            }
            return
        }

        if( $PSCmdlet.ParameterSetName -like 'ByCertificate*' )
        {
            $Thumbprint = $Certificate.Thumbprint
        }
    
        $invokeCommandParameters = @{}
        if( $Session )
        {
            $invokeCommandParameters['Session'] = $Session
        }

        if( $CustomStoreName )
        {
            # This is just so we can pass a value to the Invoke-Command script block. The store name enum doesn't have a
            # "not set" value so when it is "$null", the call to Invoke-Command fails.
            $StoreName = [Security.Cryptography.X509Certificates.StoreName]::My
        }

        Invoke-Command @invokeCommandParameters -ScriptBlock {
            [CmdletBinding()]
            param(
                # The thumbprint of the certificate to remove.
                [String] $Thumbprint,
        
                # The location of the certificate's store.
                [Security.Cryptography.X509Certificates.StoreLocation] $StoreLocation,
        
                # The name of the certificate's store.
                [Security.Cryptography.X509Certificates.StoreName] $StoreName,

                # The name of the non-standard, custom store where the certificate should be un-installed.
                [String] $CustomStoreName
            )

            Set-StrictMode -Version 'Latest'

            if( $CustomStoreName )
            {
                $storeNameDisplay = $CustomStoreName
                $store = [Security.Cryptography.X509Certificates.X509Store]::New($CustomStoreName, $StoreLocation)
            }
            else
            {
                $storeNameDisplay = $StoreName.ToString()
                $store = [Security.Cryptography.X509Certificates.X509Store]::New($StoreName, $StoreLocation)
            }

            $certToRemove = $null
            try
            {
                $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly) )
                $certToRemove = $store.Certificates | Where-Object { $_.Thumbprint -eq $Thumbprint }
                if( -not $certToRemove )
                {
                    return
                }
            }
            catch
            {
                $ex = $_.Exception.InnerException
                while( $ex.InnerException )
                {
                    $ex = $ex.InnerException
                }
                $msg = "[$($ex.GetType().FullName)] exception reading certificates from $($StoreLocation)\" +
                       "$($storeNameDisplay) store: $($ex)"
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }
            finally
            {
                $store.Close()
            }

            try
            {
                $store.Open( ([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) )
                $target = $certToRemove.FriendlyName
                if( -not $target )
                {
                    $target = $certToRemove.Subject
                }

                $shouldProcessTarget = "$($target) in $($StoreLocation)\$($storeNameDisplay)"
                if( $PSCmdlet.ShouldProcess($shouldProcessTarget, 'remove') )
                {
                    $msg = "Uninstalling certificate ""$($target)"" ($($Thumbprint)) from $($StoreLocation)\" +
                           "$($storeNameDisplay) store."
                    Write-Verbose $msg
                    $certToRemove | ForEach-Object { $store.Remove($_) }
                }
            }
            catch
            {
                $ex = $_.Exception.InnerException
                while( $ex.InnerException )
                {
                    $ex = $ex.InnerException
                }
                $msg = "[$($ex.GetType().FullName)] exception uninstalling certificate in $($StoreLocation)\" +
                       "$($storeNameDisplay) store: $($ex)"
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }
            finally
            {
                $store.Close()
            }
        } -ArgumentList $Thumbprint,$StoreLocation,$StoreName,$CustomStoreName
    }
}



function Unprotect-CString
{
    <#
    .SYNOPSIS
    Decrypts a string.
 
    .DESCRIPTION
    `Unprotect-CString` decrypts a string encrypted via the Data Protection API (DPAPI), RSA, or AES into an array of
    bytes, which is then converted to an array of chars, which are stored in a `[securestring]`. All arrays of bytes and
    chars are cleared from memory once decryption completes.
 
    Use the `AsPlainText` switch to return a plain text string instead. When you do this, your decrypted string will
    remain in memory (and maybe disk) for an unknowable amount of time.
 
    `Unprotect-CString` can decrypt using the following techniques.
 
    ## Data Protection API
 
    The DPAPI only works on Windows. The encrypted string must have also been encrypted with the DPAPI. The string must
    have been encrypted at the current user's scope or the local machine scope.
 
    ## RSA
 
    RSA is an assymetric encryption/decryption algorithm, which requires a public/private key pair. It uses a private
    key to decrypt a secret encrypted with the public key. Only the private key can decrypt secrets.
 
    You can specify the private key in these ways:
 
     * with a `[Security.Cryptography.X509Certificates.X509Certificate2]` object, via the `Certificate` parameter
     * with an X509 certificate file, via the `PrivateKeyPath` parameter. On Windows, you can use paths to items in the
       `cert:\` drive.
 
     On Windows, you can also pass the thumbprint to a certificate to the `Thumbprint` parameter, and
     `Unprotect-CString` will search the `cert:\` store for a matching certificate with a private key.
 
    ## AES
 
    AES is a symmetric encryption/decryption algorithm. You supply a 16-, 24-, or 32-byte key, password, or passphrase
    with the `Key` parameter, and that key is used to decrypt. You must decrypt with the same key you used to encrypt.
    `Unprotect-CString` uses `[Security.Cryptography.Aes]::Create()` to get an object that can do the decryption.
 
    You can only pass a `[securestring]` or byte array as the key. When passing a secure string, make sure that when
    encoded as UTF-8 and converted to a byte array, it is 16, 24, or 32 bytes long. This code will tell you how long your
    plain text password is, in UTF-8 bytes:
 
        [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length
 
    Symmetric encryption requires a random, unique initialization vector (i.e. IV) everytime you encrypt something. If
    you encrypted the string with `Protect-CString`, one was generated for you and prepended to the encrypted string. If
    you encrypted the original string yourself, make sure the first 16 bytes of the encrypted text is the IV (since
    the encrypted bytes are base64 encoded, that means the first 24 characters of the encrypted string should be the
    IV).
 
    The help topic for `Protect-CString` demonstrates how to generate an AES key and how to encode it as a base64
    string.
 
    .LINK
    New-CRsaKeyPair
 
    .LINK
    Protect-CString
 
    .LINK
    http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $encryptedPassword
 
    Demonstrates how to decrypt a protected string which was encrypted with Microsoft's DPAPI. Windows only.
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Certificate $myCert
 
    Demonstrates how to decrypt a secret using RSA with a `[Security.Cryptography.X509Certificates.X509Certificate2]`
    object. You're responsible for creating/loading it. (Carbon's `New-CRsaKeyPair` function can create public/private
    key pairs for you.)
 
    .EXAMPLE
    $ciphertext | Unprotect-CString -Certificate $certWithPrivateKey
 
    Demonstrates that you can pipe encrypted strings to `Unprotect-CString`.
 
    .EXAMPLE
    $ciphertext | Unprotect-CString -Certificate $certWithPrivateKey -AsSecureString
 
    Demonstrates that you can get a secure string returned to you by using the `AsSecureString` switch. This is the most
    secure way to decrypt, as the decrypted text is only in memory as arrays of bytes/chars during decryption. The
    arrays are immediately cleared after decryption. The decrypted text is never stored as a `[String]` (which remain
    in memory).
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Thumbprint '44A7C27F3353BC53F82318C14490D7E2500B6D9E'
 
    Demonstrates how to decrypt a secret with a certificate by passing its thumbprint to the `Thumbprint` parameter.
    `Unprotect-CString` will search the Windows certificate stores to find the certificate. All local machine and user
    stores are searched. The current user must have permission/access to the certificate's private key. Windows only.
 
    .EXAMPLE
    Unprotect -ProtectedString $ciphertext -PrivateKeyPath 'C:\Projects\Security\publickey.cer'
 
    Demonstrates how to decrypt a secret by passing the path to an RSA private key to the `PrivateKeyPath` parameter.
    The private key file must be loadable by the `[Security.Cryptography.X509Certificates.X509Certificate]` class.
 
    .EXAMPLE
    Unprotect -ProtectedString $ciphertext -PrivateKeyPath 'cert:\LocalMachine\My\44A7C27F3353BC53F82318C14490D7E2500B6D9E'
 
    Demonstrates how to decrypt a secret using a certificate in the Windows store by passing the path to the certificate
    in PowerShell's `cert:` drive. The certificate must have a private key. Windows only.
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Key 'gT4XPfvcJmHkQ5tYjY3fNgi7uwG4FB9j'
 
    Demonstrates how to decrypt a secret that was encrypted with a key, password, or passphrase. In this case, we are
    decrypting with a plaintext password.
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Key (Read-Host -Prompt 'Enter password (must be 16, 24, or 32 characters long):') -AsSecureString)
 
    Demonstrates how to decrypt a secret with a secure string that is the key, password, or passphrase. In this case,
    the user is prompted for the password securely.
 
    .EXAMPLE
    Unprotect-CString -ProtectedString $ciphertext -Key ([byte[]]@(163,163,185,174,205,55,157,219,121,146,251,116,43,203,63,38,73,154,230,112,82,112,151,29,189,135,254,187,164,104,45,30))
 
    Demonstrates that you can pass in an array of bytes as the key to the `Key` parameter. Those bytes will be used to
    decrypt the ciphertext.
    #>

    [CmdletBinding(DefaultParameterSetName='DPAPI')]
    param(
        [Parameter(Mandatory, Position=0, ValueFromPipeline)]
        # The text to decrypt.
        [String]$ProtectedString,

        [Parameter(Mandatory, ParameterSetName='RSAByCertificate')]
        # The private key to use for decrypting.
        [Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,

        [Parameter(Mandatory, ParameterSetName='RSAByThumbprint')]
        # The thumbprint of the certificate, found in one of the Windows certificate stores, to use when decrypting. All
        # certificate stores are searched. The current user must have permission to the private key. Windows only.
        [String]$Thumbprint,

        [Parameter(Mandatory, ParameterSetName='RSAByPath')]
        # The path to the private key to use for decrypting. If given a path on the file system, the file must be
        # loadable as a `[Security.X509Certificates.X509Certificate2]` object. On Windows, you can also pass the path
        # to a certificate in PowerShell's `cert:` drive.
        [String]$PrivateKeyPath,

        [Parameter(ParameterSetName='RSAByPath')]
        # The password for the private key, if it has one. Must be a `[securestring]`.
        [securestring]$Password,

        [Parameter(ParameterSetName='RSAByCertificate')]
        [Parameter(ParameterSetName='RSAByThumbprint')]
        [Parameter(ParameterSetName='RSAByPath')]
        # The padding mode to use when decrypting. Defaults to `[Security.Cryptography.RSAEncryptionPadding]::OaepSHA1`.
        [Security.Cryptography.RSAEncryptionPadding]$Padding,

        [Parameter(Mandatory, ParameterSetName='Symmetric')]
        # The key to use to decrypt the secret. Must be a `[securestring]` or an array of bytes. The characters in the
        # secure string are converted to UTF-8 encoding before being converted into bytes. Make sure the key is the
        # correct length when UTF-8 encoded, i.e. make sure the following code returns a 16, 24, or 32 byte byte array
        # (where $key is the plain text key).
        #
        # [Text.Encoding]::Convert([Text.Encoding]::Unicode, [Text.Encoding]::UTF8, [Text.Encoding]::Unicode.GetBytes($key)).Length
        [Object]$Key,

        # Returns the decrypted value as plain text. The default is to return the decrypted value as a `[securestring]`.
        # When returned as a secure string, the decrypted bytes are only stored in memory as arrays of bytes and chars,
        # which are all cleared once the decrypted text is in the secure string. Once a secure string is converted to a
        # string, that string stays in memory (and possibly disk) for an unknowable amout of time.
        [switch]$AsPlainText
    )

    process
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

        [byte[]]$keyBytes = [byte[]]::New(0)

        # Find and validate the RSA certificate, if needed. We do it here so our try/catch around the actual
        # decryption doesn't handle these errors.
        if( $PSCmdlet.ParameterSetName -like 'RSA*' )
        {
            if( $PSCmdlet.ParameterSetName -notlike '*ByCertificate' )
            {
                if( $PSCmdlet.ParameterSetName -like '*ByThumbprint' )
                {
                    $PrivateKeyPath = "cert:\*\*\$($Thumbprint)"
                }

                $passwordParam = @{ }
                if( $Password )
                {
                    $passwordParam = @{ Password = $Password }
                }

                $certificates = Get-CCertificate -Path $PrivateKeyPath @passwordParam
                $count = $certificates | Measure-Object | Select-Object -ExpandProperty 'Count'
                if( $count -gt 1 )
                {
                    $certificates = $certificates | Where-Object { $_.HasPrivateKey -and $_.PrivateKey }
                    $privateKeyCount = $certificates | Measure-Object | Select-Object -ExpandProperty 'Count'

                    if( $privateKeyCount -gt 1 )
                    {
                        $msg = "Found $($privateKeyCount) certificates (which contain private keys) at ""$($PrivateKeyPath)"". " +
                            'Arbitrarily choosing the first one. If you get errors, consider passing the exact path to ' +
                            'the certificate you want to the "Unprotect-CString" function''s "PrivateKeyPath" parameter.'
                        Write-Warning -Message $msg
                    }
                    elseif( $privateKeyCount -eq 0 )
                    {

                        $installedInCertStoreMsg = ''
                        if ($PSCmdlet.ParameterSetName -eq 'RSAByThumbprint')
                        {
                            $installedInCertStoreMsg =
                                'This is usually because the certificate was installed without a private key or the ' +
                                'current user doesn''t have permission to read the private key.'
                        }

                        "Found $($count) certificates at ""$($PrivateKeyPath)"" but none of them contain a private " +
                        "key or the private key is null.$(' ' + $installedInCertStoreMsg)" | Write-Error
                        return
                    }
                }
                $Certificate = $certificates | Select-Object -First 1
                if( -not $Certificate )
                {
                    return
                }
            }

            $certDesc = "Certificate ""$($Certificate.Subject)"" ($($Certificate.Thumbprint))"
            if( -not $Certificate.HasPrivateKey )
            {
                $msg = "$($certDesc) doesn't have a private key. When decrypting with RSA, secrets are encrypted with " +
                    'the public key, and decrypted with a private key.'
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }

            if( -not $Certificate.PrivateKey )
            {
                $msg = "$($certDesc) has a private key, but it is null or not set. This usually means your certificate " +
                    'was imported incorrectly or was created without a private key. Make sure you''ve generated an ' +
                    'RSA public/private key pair and are using the private key. If the private key is in the Windows ' +
                    'certificate store, make sure the current user has permission to read the private key (use ' +
                    'Carbon''s `Grant-CPermission` function).'
                Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                return
            }
        }
        elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' )
        {
            $keyBytes = ConvertTo-AesKey -InputObject $Key -From 'Unprotect-CString'
            if( -not $keyBytes )
            {
                return
            }
        }


        [byte[]]$decryptedBytes = [byte[]]::New(0)
        [byte[]]$encryptedBytes = [Convert]::FromBase64String($ProtectedString)
        try
        {
            if( $PSCmdlet.ParameterSetName -eq 'DPAPI' )
            {
                $decryptedBytes = [Security.Cryptography.ProtectedData]::Unprotect( $encryptedBytes, $null, 0 )
            }
            elseif( $PSCmdlet.ParameterSetName -like 'RSA*' )
            {
                [Security.Cryptography.RSA]$privateKey = $null
                $privateKeyType = $Certificate.PrivateKey.GetType()
                $isRsa = $privateKeyType.IsSubclassOf([Security.Cryptography.RSA])
                if( -not $isRsa )
                {
                    $msg = "$($certDesc) is not an RSA key. Found a private key of type " +
                           """$($privateKeyType.FullName)"", but expected type " +
                           """$([Security.Cryptography.RSA].FullName)"" or one of its sub-types."
                    Write-Error -Message $msg -ErrorAction $ErrorActionPreference
                    return
                }

                if( -not $Padding )
                {
                    $Padding = [Security.Cryptography.RSAEncryptionPadding]::OaepSHA1
                }

                $privateKey = $Certificate.PrivateKey
                $decryptedBytes = $privateKey.Decrypt($encryptedBytes, $padding)
            }
            elseif( $PSCmdlet.ParameterSetName -eq 'Symmetric' )
            {
                $aes = [Security.Cryptography.Aes]::Create()
                try
                {
                    $aes.Padding = [Security.Cryptography.PaddingMode]::PKCS7
                    $aes.KeySize = $keyBytes.Length * 8
                    $aes.Key = $keyBytes
                    $iv = [byte[]]::New($aes.IV.Length)
                    [Array]::Copy($encryptedBytes, $iv, 16)

                    $encryptedBytes = $encryptedBytes[16..($encryptedBytes.Length - 1)]
                    $encryptedStream = New-Object -TypeName 'IO.MemoryStream' -ArgumentList (,$encryptedBytes)
                    try
                    {
                        $cryptoStream =
                            [Security.Cryptography.CryptoStream]::New($encryptedStream,
                                $aes.CreateDecryptor($aes.Key, $iv),
                                ([Security.Cryptography.CryptoStreamMode]::Read))
                        try
                        {
                            $streamReader = [IO.StreamReader]::New($cryptoStream)
                            try
                            {
                                [byte[]]$decryptedBytes = [Text.Encoding]::UTF8.GetBytes($streamReader.ReadToEnd())
                            }
                            finally
                            {
                                $streamReader.Dispose()
                            }
                        }
                        finally
                        {
                            $cryptoStream.Dispose()
                        }
                    }
                    finally
                    {
                        $encryptedStream.Dispose()
                    }
                }
                finally
                {
                    $aes.Dispose()
                }
            }

            $decryptedBytes = [Text.Encoding]::Convert([Text.Encoding]::UTF8, [Text.Encoding]::Unicode, $decryptedBytes)
            if( $AsPlainText )
            {
                return [Text.Encoding]::Unicode.GetString($decryptedBytes)
            }
            else
            {
                $secureString = [Security.SecureString]::New()
                [char[]]$chars = [Text.Encoding]::Unicode.GetChars( $decryptedBytes )
                for( $idx = 0; $idx -lt $chars.Count ; $idx++ )
                {
                    $secureString.AppendChar( $chars[$idx] )
                    $chars[$idx] = 0
                }

                $secureString.MakeReadOnly()
                return $secureString
            }
        }
        catch
        {
            Write-Error -ErrorRecord $_ -ErrorAction $ErrorActionPreference
        }
        finally
        {
            if( $decryptedBytes )
            {
                $decryptedBytes.Clear()
            }

            if( $encryptedBytes )
            {
                $encryptedBytes.Clear()
            }

            if( $keyBytes )
            {
                $keyBytes.Clear()
            }
        }
    }
}


function Use-CallerPreference
{
    <#
    .SYNOPSIS
    Sets the PowerShell preference variables in a module's function based on the callers preferences.
 
    .DESCRIPTION
    Script module functions do not automatically inherit their caller's variables, including preferences set by common
    parameters. This means if you call a script with switches like `-Verbose` or `-WhatIf`, those that parameter don't
    get passed into any function that belongs to a module.
 
    When used in a module function, `Use-CallerPreference` will grab the value of these common parameters used by the
    function's caller:
 
     * ErrorAction
     * Debug
     * Confirm
     * InformationAction
     * Verbose
     * WarningAction
     * WhatIf
     
    This function should be used in a module's function to grab the caller's preference variables so the caller doesn't
    have to explicitly pass common parameters to the module function.
 
    This function is adapted from the [`Get-CallerPreference` function written by David Wyatt](https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d).
 
    There is currently a [bug in PowerShell](https://connect.microsoft.com/PowerShell/Feedback/Details/763621) that
    causes an error when `ErrorAction` is implicitly set to `Ignore`. If you use this function, you'll need to add
    explicit `-ErrorAction $ErrorActionPreference` to every `Write-Error` call. Please vote up this issue so it can get
    fixed.
 
    .LINK
    about_Preference_Variables
 
    .LINK
    about_CommonParameters
 
    .LINK
    https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d
 
    .LINK
    http://powershell.org/wp/2014/01/13/getting-your-script-module-functions-to-inherit-preference-variables-from-the-caller/
 
    .EXAMPLE
    Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
 
    Demonstrates how to set the caller's common parameter preference variables in a module function.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        #[Management.Automation.PSScriptCmdlet]
        # The module function's `$PSCmdlet` object. Requires the function be decorated with the `[CmdletBinding()]`
        # attribute.
        $Cmdlet,

        [Parameter(Mandatory)]
        # The module function's `$ExecutionContext.SessionState` object. Requires the function be decorated with the
        # `[CmdletBinding()]` attribute.
        #
        # Used to set variables in its callers' scope, even if that caller is in a different script module.
        [Management.Automation.SessionState]$SessionState
    )

    Set-StrictMode -Version 'Latest'

    # List of preference variables taken from the about_Preference_Variables and their common parameter name (taken
    # from about_CommonParameters).
    $commonPreferences = @{
                              'ErrorActionPreference' = 'ErrorAction';
                              'DebugPreference' = 'Debug';
                              'ConfirmPreference' = 'Confirm';
                              'InformationPreference' = 'InformationAction';
                              'VerbosePreference' = 'Verbose';
                              'WarningPreference' = 'WarningAction';
                              'WhatIfPreference' = 'WhatIf';
                          }

    foreach( $prefName in $commonPreferences.Keys )
    {
        $parameterName = $commonPreferences[$prefName]

        # Don't do anything if the parameter was passed in.
        if( $Cmdlet.MyInvocation.BoundParameters.ContainsKey($parameterName) )
        {
            continue
        }

        $variable = $Cmdlet.SessionState.PSVariable.Get($prefName)
        # Don't do anything if caller didn't use a common parameter.
        if( -not $variable )
        {
            continue
        }

        if( $SessionState -eq $ExecutionContext.SessionState )
        {
            Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
        }
        else
        {
            $SessionState.PSVariable.Set($variable.Name, $variable.Value)
        }
    }
}