BaseEncoder.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 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 |
#Requires -Version 3.0 Set-StrictMode -Version Latest Function Get-RandomByteArray() { <# .SYNOPSIS A PowerShell function to generate an arbitrary number of cryptographically safe random bytes. .DESCRIPTION Takes a [System.UInt32] parameter specifying the number of bytes to generate and invokes [Security.Cryptography.RNGCryptoServiceProvider]::GetBytes() to return a [System.Byte[]] object containing that number of crypto-quality random bytes. .PARAMETER NumBytes [System.UInt32] object that specifies the number of random bytes to generate. Must be between 1 and [System.UInt32]::MaxValue (4294967295). .INPUTS Single [System.UInt32] parameter indicating the number of bytes to generate. .OUTPUTS [System.Byte[]] array containing the requested number of bytes that have been randomly generated by [Security.Cryptography.RNGCryptoServiceProvider]::GetBytes(). .EXAMPLE Get 64 random bytes: $Bytes = Get-RandomByteArray 64 .NOTES RNGCryptoServiceProvider is used over Get-Random because - when invoked inside a loop or other rapid iteration like the pipeline - Get-Random tends produce duplicate output on fast systems. This is because by default Get-Random uses [Environment]::TickCount (number of milliseconds elapsed since system startup) as a seed and repeated invocation over a loop on a fast system (i.e. sub-1ms execution time) effectively generates multiple calls to the same RNG using identical seeds; hence, identical outputs. RNGCryptoServiceProvider does not have this problem, therefore RNGCryptoServiceProvider was chosen to make the script safe for situations where random bytes might be generated via a loop or through pipeline operations. #> [CmdletBinding( SupportsShouldProcess=$False, DefaultParameterSetName="ByteOutput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="ByteOutput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Number of random bytes to generate, between 1 and [System.UInt32]::MaxValue (4294967295).' )] [ValidateNotNullOrEmpty()] [ValidateRange(1,[System.UInt32]::MaxValue)] [Alias('Value','Number')] [System.UInt32]$NumBytes ) [System.Byte[]]$Buffer = New-Object -TypeName System.Byte[] $NumBytes $RNG = [Security.Cryptography.RNGCryptoServiceProvider]::Create() $RNG.GetBytes($Buffer) Return ($Buffer) } Function Get-CompressedByteArray { <# .SYNOPSIS A PowerShell function to apply GZip compression to a byte array. .DESCRIPTION Takes a [System.Byte[]] array as input and returns a [System.Byte[]] array containing a GZip-compressed version of the input bytes. .PARAMETER ByteArray [System.Byte[]] object containing arbitrary bytes on which to apply compression. .PARAMETER CompressionLevel [System.IO.Compression.CompressionLevel] enum that determines the level of compression; valid values are "Fastest", "NoCompression" and "Optimal". By default if no CompressionLevel is specified, "Optimal" will be used. .INPUTS [System.Byte[]] object. .OUTPUTS [System.Byte[]] object. .EXAMPLE GZip compress a byte array using Optimal compression level: $GZBytes = Get-CompressedByteArray($Bytes) .EXAMPLE GZip compress a byte array using Fastest compression level: $GZBytes = Get-CompressedByteArray($Bytes) -CompressionLevel Fastest .NOTES This function provides a simple wrapper for the .NET System.IO.Compression.GzipStream class - no spectacular hand-rolled compression code here. #> [CmdletBinding( SupportsShouldProcess=$False, DefaultParameterSetName="ByteInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Byte array to GZip compress' )] [ValidateNotNullOrEmpty()] [Alias('Data','Bytes')] [System.Byte[]]$ByteArray, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$False, Position=1, HelpMessage='GZip compression level, valid values are "Fastest", "NoCompression" and "Optimal"; default "Optimal"' )] [ValidateNotNullOrEmpty()] [System.IO.Compression.CompressionLevel]$CompressionLevel ) PROCESS { [System.IO.MemoryStream]$OutputStream = New-Object -TypeName System.IO.MemoryStream [System.Object]$GZStream = New-Object -TypeName System.IO.Compression.GzipStream $OutputStream,([IO.Compression.CompressionMode]::Compress),$CompressionLevel Try { $GZStream.Write($ByteArray,0,$ByteArray.Length) [System.Byte[]]$ResultObject = $OutputStream.ToArray() Return ($ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $GZStream.Close() $GZStream.Dispose() $OutputStream.Close() $OutputStream.Dispose() } } } Function Get-DecompressedByteArray { <# .SYNOPSIS A PowerShell function decompress GZip-compressed byte arrays. .DESCRIPTION Takes a [System.Byte[]] array containing a GZip-compressed data as input and returns a [System.Byte[]] array of the corresponding decompressed data. .PARAMETER ByteArray [System.Byte[]] object containing arbitrary bytes to decompress. .INPUTS [System.Byte[]] object. .OUTPUTS [System.Byte[]] object. .EXAMPLE Decompress a byte array:: $Bytes = Get-DecompressedByteArray($GZBytes) .NOTES The function will check the first two bytes of the input object for the GZip "magic number" 0x1F,0x8B - if the magic number is not present the function assumes the byte array is not compressed and returns the original input object without modification. #> [CmdletBinding( SupportsShouldProcess=$False, DefaultParameterSetName="ByteInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Byte array to GZip decompress' )] [ValidateNotNullOrEmpty()] [Alias('Data','Bytes')] [System.Byte[]]$ByteArray ) PROCESS { If (Compare-Object -ReferenceObject ([System.Byte[]]$ByteArray[0,1]) -DifferenceObject ([System.Byte[]](0x1F,0x8B))) { Write-Warning "Data stream is missing GZip magic number, bytes are probably not compressed." Return ($ByteArray) #TODO: determine best way to handle missing GZip header - returning the original byte array isn't elegant } [System.Object]$InputStream = New-Object -TypeName System.IO.MemoryStream(,$ByteArray) [System.Object]$OutputStream = New-Object -TypeName System.IO.MemoryStream [System.Object]$GZStream = New-Object -TypeName System.IO.Compression.GzipStream $InputStream,([IO.Compression.CompressionMode]::Decompress) Try { $GZStream.CopyTo($OutputStream) [System.Byte[]]$ResultObject = $OutputStream.ToArray() Return ($ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $GZStream.Close() $GZStream.Dispose() $InputStream.Close() $InputStream.Dispose() $OutputStream.Close() $OutputStream.Dispose() } } } Function ConvertTo-Ascii85() { <# .SYNOPSIS A PowerShell function to convert arbitrary data into an Ascii85 encoded string. .DESCRIPTION Takes a string, byte array or file object as input and returns a Ascii85 encoded string or location of the Ascii85 result output file object. The default input and output type if positional parameters are used is [System.String]. .PARAMETER Bytes [System.Byte[]] object containing a byte array to be encoded as Ascii85 string. Accepts pipeline input. .PARAMETER String [System.String] object containing plain text to be encoded as Ascii85 string. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be converted to Ascii85 string and output as a new file; output files are written as UTF-8 no BOM. Accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing Ascii85 encoded data from the input file. Can be used with any input mode (Bytes, String, or InFile). .PARAMETER Unormatted By default the function adds line breaks to output string every 64 characters and adds A85 start/end delimiters (<~ / ~>); this parameter suppresses formatting and returns the Ascii85 string result as a single, unbroken string object with no delimiters. .PARAMETER AutoSave [System.String] containing a new file extension to use to automatically generate files. When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter, for example -AutoSave "A85" would create the OutFile name <InFile>.A85. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw string output instead of a PSObject. This parameter limits the functionality of the pipeline but is convenient for simple encoding operations. .INPUTS Any single object or collection of strings, bytes, or files (such as those from Get-ChildItem) can be piped to the function for processing into Ascii85 encoded data. .OUTPUTS The output is always an ASCII string; if any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a UTF8 no BOM text file with the Ascii85 encoded data as contents. Unless -Unformatted is specified, the console or file string data is formatted with start and end delimiters (<~ / ~>) and line breaks are added every 64 character. If -Unformatted is present, the output is a [System.String] with no line breaks or delimiters. If outputting to the console, the string is returned within a PSObject with a single member named Ascii85EncodedData as [System.String]; if -Raw is specified, the [System.String] is not wrapped in a PSObject and returned directly. This means that output using -Raw cannot easily use the pipeline, but makes it a useful option for quick encoding operations. The -Verbose parameter will return the function's total execution time. .EXAMPLE Convert a string directly into Ascii85: ConvertTo-Ascii85 "This is a plaintext string" .EXAMPLE Pipe an object (string or array of strings, byte array or array of byte arrays, file info or array of file info objects) to the function for encoding as Ascii85: $MyObject | ConvertTo-Ascii85 .EXAMPLE Convert a byte array to Ascii85 and return the output with block formatting and not wrapped in a PSObject (as a raw [System.String]): ConvertTo-Ascii85 -ByteArray $Bytes -Raw .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Ascii85 encoded file with block formatting for each input file: Get-ChildItem C:\Text\*.txt | ConvertTo-Ascii85 -AutoSave "A85" .EXAMPLE Use file based input to Ascii85 encode an input file and output the results as new file C:\Text\Ascii85.txt with no line breaks or delimiters: ConvertTo-Ascii85 -File C:\Text\file.txt -OutFile C:\Text\Ascii85.txt -Unformatted .NOTES Ascii85 is similar but slightly different than the Base85 encoding scheme from which it is derived. More info on Ascii85 can be found here: https://en.wikipedia.org/wiki/Ascii85 #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Byte array to Ascii85 encode.' )] [ValidateNotNullOrEmpty()] [Alias('ByteArray','Data')] [System.Byte[]]$Bytes, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='String to Ascii85 encode.' )] [ValidateNotNullOrEmpty()] [Alias('Plaintext','Text')] [System.String]$String, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to Ascii85 encode.' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName','File')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$False, Position=1, HelpMessage='Output result as UTF8-NoBOM encoded text to specified file instead of writing to console.' )] [Parameter( ParameterSetName="ByteInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Do not format output string using header, footer or line breaks.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Unformatted, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning a string instead of a file, return a raw string instead of PSObject; applies to both console and file output modes.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File If ($Raw) { Write-Warning "File output mode specified; Parameter '-Raw' will be ignored." } } Switch ($PSCmdlet.ParameterSetName) { "ByteInput" { [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,$Bytes) Break } "StringInput" { [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,[System.Text.Encoding]::ASCII.GetBytes($String)) Break } "FileInput" { [System.IO.Stream]$InputStream = [System.IO.File]::Open($InFile.FullName,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::ReadWrite) Break } } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() [System.Object]$BinaryReader = New-Object -TypeName System.IO.BinaryReader($InputStream) [System.Object]$Ascii85Output = New-Object -TypeName System.Text.StringBuilder If (-Not $Unformatted) { [void]$Ascii85Output.Append("<~") [System.UInt16]$LineLen = 2 } Try { While ([System.Byte[]]$BytesRead = $BinaryReader.ReadBytes(4)) { [System.UInt16]$ByteLength = $BytesRead.Length If ($ByteLength -lt 4) { [System.Byte[]]$WorkingBytes = ,0x00 * 4 [System.Buffer]::BlockCopy($BytesRead,0,$WorkingBytes,0,$ByteLength) [System.Array]::Resize([ref]$BytesRead,4) [System.Buffer]::BlockCopy($WorkingBytes,0,$BytesRead,0,4) } If ([BitConverter]::IsLittleEndian) { [Array]::Reverse($BytesRead) } [System.Char[]]$A85Chars = ,0x00 * 5 [System.UInt32]$Sum = [BitConverter]::ToUInt32($BytesRead,0) [System.UInt16]$ByteLen = [Math]::Ceiling(($ByteLength / 4) * 5) If ($ByteLength -eq 4 -And $Sum -eq 0) { [System.Char[]]$A85Chunk = "z" } Else { [System.Char[]]$A85Chunk = ,0x00 * $ByteLen $A85Chars[0] = [System.Text.Encoding]::ASCII.GetChars([Math]::Floor(($Sum / [Math]::Pow(85,4)) % 85) + 33)[0] $A85Chars[1] = [System.Text.Encoding]::ASCII.GetChars([Math]::Floor(($Sum / [Math]::Pow(85,3)) % 85) + 33)[0] $A85Chars[2] = [System.Text.Encoding]::ASCII.GetChars([Math]::Floor(($Sum / [Math]::Pow(85,2)) % 85) + 33)[0] $A85Chars[3] = [System.Text.Encoding]::ASCII.GetChars([Math]::Floor(($Sum / 85) % 85) + 33)[0] $A85Chars[4] = [System.Text.Encoding]::ASCII.GetChars([Math]::Floor($Sum % 85) + 33)[0] [System.Array]::Copy($A85Chars,$A85Chunk,$ByteLen) } ForEach ($A85Char in $A85Chunk) { [void]$Ascii85Output.Append($A85Char) If (-Not $Unformatted) { If ($LineLen -eq 64) { [void]$Ascii85Output.Append("`r`n") $LineLen = 0 } Else { $LineLen++ } } } } If (-Not $Unformatted) { If ($LineLen -le 62) { [void]$Ascii85Output.Append("~>") } Else { [void]$Ascii85Output.Append("~`r`n>") } } [System.String]$Ascii85Result = $Ascii85Output.ToString() $Ascii85ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllLines($OutFile.FullName,$Ascii85Result,(New-Object -TypeName System.Text.UTF8Encoding $False)) $Ascii85ResultObject = $OutFile } Else { If ($Raw) { $Ascii85ResultObject = $Ascii85Result } Else { Add-Member -InputObject $Ascii85ResultObject -MemberType 'NoteProperty' -Name 'Ascii85EncodedData' -Value $Ascii85Result } } Return ($Ascii85ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $BinaryReader.Close() $BinaryReader.Dispose() $InputStream.Close() $InputStream.Dispose() $Timer.Stop() [System.String]$TimeLapse = "Ascii85 encode completed in $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertFrom-Ascii85() { <# .SYNOPSIS A PowerShell function to convert an arbitrary Ascii85 encoded string into a byte array or binary file. .DESCRIPTION Takes a string of Ascii85 formatted data and decodes into the original ASCII string or byte array. Input includes a Ascii85 string or a file containing an Ascii85 string. Both formatted (line breaks) and unformatted Ascii85 data are supported. The default input and output type if positional parameters are used is [System.String]; it is also possible to write a binary file from the Ascii85 input using -OutFile. .PARAMETER Ascii85EncodedString [System.String] object containing Ascii85 encoded data. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be loaded as a string object and decoded from Ascii85 string; accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing Ascii85 decoded data from the input file. Can be used with any input mode (Bytes, String, or InFile); file content will be raw decoded bytes. .PARAMETER OutBytes Return the decoded data as [System.Byte[]] to the console instead of the default ASCII string. .PARAMETER AutoSave When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter; for example, -AutoSave "BIN" will result in OutFile name <InFile>.bin. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw output instead of a PSObject. Depending on the parameters used, the return object could be of type [System.String] or [System.Byte[]]. .INPUTS Any single object, array or collection of strings or files (such as those from Get-ChildItem) can be piped to the function for processing from Ascii85 encoded data. Input data from file is always processed as ASCII text regardless of source file text encoding. .OUTPUTS In the case of direct string input, a [System.String] containing the decoded data as ASCII text is returned within a PSObject with a single member named Ascii85DecodedData. If any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a binary file with the Ascii85 decoded data as contents. If -OutBytes is specified, data is returned to the console as [System.Byte[]] wrapped in a PSObject. If -Raw is specified, the [System.String] or [System.Byte[]] is not wrapped in a PSObject and is returned directly. This means that output using -Raw cannot easily use the pipeline. The -Verbose parameter will return the function's total execution time. .EXAMPLE Convert a Ascii85 string to a decoded byte array: [System.Byte[]]$Bytes = ConvertFrom-Ascii85 "6uQRXD.RU,@<?4%DBS" -OutBytes -Raw .EXAMPLE Decode a Ascii85 encoded string: ConvertFrom-Ascii85 -Ascii85EncodedString "6uQRXD.RU,@<?4%DBS" .EXAMPLE Pipe an object (string or array of strings, file info or array of file info objects) to the function for decoding from Ascii85: $MyObject | ConvertFrom-Ascii85 .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Ascii85 decoded file for each input file: Get-ChildItem C:\Text\*.A85 | ConvertFrom-Ascii85 -AutoSave "BIN" .EXAMPLE Use file based input to decode an input file and output the results as new file C:\Text\file.txt: ConvertFrom-Ascii85 -File C:\Text\file.A85 -OutFile C:\Text\file.txt .NOTES Ascii85 is similar but slightly different than the Base85 encoding scheme from which it is derived. More info on Ascii85 can be found here: https://en.wikipedia.org/wiki/Ascii85. Because Ascii85 encoded text uses some PowerSehll reserved characters in its output (notably ` and $), when using string input it is sometimes necessary to escape certain characters in order for input to be read correctly. File input does not suffer from this limitation. #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Input A85encoded string.' )] [ValidateNotNullOrEmpty()] [Alias('String','Plaintext','Text','A85EncodedData')] [System.String]$Ascii85EncodedString, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to A85decode' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, Position=1, HelpMessage='Path to output file when decoding in file mode.' )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Output decoded data as raw bytes instead of ASCII text.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$OutBytes, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Determine the output file name from the A85encoded data header; only applies to file mode. Can be mixed with -AutoSave or -OutFile when using pipeline to extract the file name if it exists, and rely on -AutoSave / -OutFile if it does not.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Auto, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning to console, return a raw byte array instead of PSObject.' )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { If ($PSBoundParameters.ContainsKey("AutoSave") -and $PSCmdlet.ParameterSetName -ne "FileInput") { Write-Error "-AutoSave can only be used in file input mode." -ErrorAction Stop } [System.String]$NON_A85_Pattern = "[^\x21-\x75]" [System.String]$OFS = "" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } Switch ($PSCmdlet.ParameterSetName) { "StringInput" { [System.String]$A85String = $Ascii85EncodedString.Replace("<~","").Replace("~>","").Replace(" ","").Replace("`r`n","").Replace("`n","") Break } "FileInput" { [System.String]$A85String = ([System.IO.File]::ReadAllText($InFile.FullName)).Replace("<~","").Replace("~>","").Replace(" ","").Replace("`r`n","").Replace("`n","") Break } } If ($A85String -match $NON_A85_Pattern) { Throw "Invalid Ascii85 data detected in input stream." } [System.Object]$InputStream = New-Object -TypeName System.IO.MemoryStream([System.Text.Encoding]::ASCII.GetBytes($A85String),0,$A85String.Length) [System.Object]$BinaryReader = New-Object -TypeName System.IO.BinaryReader($InputStream) [System.Object]$OutputStream = New-Object -TypeName System.IO.MemoryStream [System.Object]$BinaryWriter = New-Object -TypeName System.IO.BinaryWriter($OutputStream) If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() Try { While ([System.Byte[]]$BytesRead = $BinaryReader.ReadBytes(5)) { [System.Boolean]$AtEnd = ($BinaryReader.BaseStream.Length -eq $BinaryReader.BaseStream.Position) [System.UInt16]$ByteLength = $BytesRead.Length If ($ByteLength -lt 5) { [System.Byte[]]$WorkingBytes = ,0x75 * 5 [System.Buffer]::BlockCopy($BytesRead,0,$WorkingBytes,0,$ByteLength) [System.Array]::Resize([ref]$BytesRead,5) [System.Buffer]::BlockCopy($WorkingBytes,0,$BytesRead,0,5) } [System.UInt16]$ByteLen = [Math]::Floor(($ByteLength * 4) / 5) [System.Byte[]]$BinChunk = ,0x00 * $ByteLen If ($BytesRead[0] -eq 0x7A) { $BinaryWriter.Write($BinChunk) If (-Not $AtEnd) { $BinaryReader.BaseStream.Position = $BinaryReader.BaseStream.Position - 4 Continue } } Else { [System.UInt32]$Sum = 0 $Sum += ($BytesRead[0] - 33) * [Math]::Pow(85,4) $Sum += ($BytesRead[1] - 33) * [Math]::Pow(85,3) $Sum += ($BytesRead[2] - 33) * [Math]::Pow(85,2) $Sum += ($BytesRead[3] - 33) * 85 $Sum += ($BytesRead[4] - 33) [System.Byte[]]$A85Bytes = [System.BitConverter]::GetBytes($Sum) If ([BitConverter]::IsLittleEndian) { [Array]::Reverse($A85Bytes) } [System.Buffer]::BlockCopy($A85Bytes,0,$BinChunk,0,$ByteLen) $BinaryWriter.Write($BinChunk) } } $ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllBytes($OutFile,($OutputStream.ToArray())) $ResultObject = $OutFile } Else { If ($OutBytes -and $Raw) { $ResultObject = $OutputStream.ToArray() } ElseIf ($OutBytes) { Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'Ascii85DecodedData' -Value $OutputStream.ToArray() } ElseIf ($Raw) { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString(($OutputStream.ToArray())) $ResultObject = $Results } Else { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString(($OutputStream.ToArray())) Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'AsciiDecodedString' -Value $Results } } Return ($ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $BinaryReader.Close() $BinaryReader.Dispose() $BinaryWriter.Close() $BinaryWriter.Dispose() $InputStream.Close() $InputStream.Dispose() $OutputStream.Close() $OutputStream.Dispose() $Timer.Stop() [System.String]$TimeLapse = "Ascii85 decode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertTo-Base16() { <# .SYNOPSIS A PowerShell function to convert arbitrary data into a Base16 (hexadecimal) encoded string. .DESCRIPTION Takes a string, byte array or file object as input and returns a Base16 encoded string or location of the Base16 result output file object. The default input and output type if positional parameters are used is [System.String]. .PARAMETER Bytes [System.Byte[]] object containing a byte array to be encoded as Base16 string. Accepts pipeline input. .PARAMETER String [System.String] object containing plain text to be encoded as Base16 string. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be converted to Base16 string and output as a new file; output files are written as UTF-8 no BOM. Accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing Base16 encoded data from the input file. Can be used with any input mode (Bytes, String, or InFile). .PARAMETER Unormatted By default the function adds line breaks to output string every 64 characters and block style header / footer (-----BEGIN BASE16 ENCODED DATA-----/-----END BASE16 ENCODED DATA-----); this parameter suppresses formatting and returns the Base16 string result as a single, unbroken string object with no header or footer. .PARAMETER AutoSave [System.String] containing a new file extension to use to automatically generate files. When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter, for example -AutoSave "B16" would create the OutFile name <InFile>.B16. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw string output instead of a PSObject. This parameter limits the functionality of the pipeline but is convenient for simple encoding operations. .INPUTS Any single object or collection of strings, bytes, or files (such as those from Get-ChildItem) can be piped to the function for processing into Base16 encoded data. .OUTPUTS The output is always an ASCII string; if any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a UTF8 no BOM text file with the Base16 encoded data as contents. Unless -Unformatted is specified, the console or file string data is formatted with block headers (-----BEGIN BASE16 ENCODED DATA-----/-----END BASE16 ENCODED DATA-----) and line breaks are added every 64 character. If -Unformatted is present, the output is a [System.String] with no line breaks or header / footer. If outputting to the console, the string is returned within a PSObject with a single member named Base16EncodedData as [System.String]; if -Raw is specified, the [System.String] is not wrapped in a PSObject and returned directly. This means that output using -Raw cannot easily use the pipeline, but makes it a useful option for quick encoding operations. The -Verbose parameter will return the function's total execution time. .EXAMPLE Convert a string directly into Base16: ConvertTo-Base16 "This is a plaintext string" .EXAMPLE Pipe an object (string or array of strings, byte array or array of byte arrays, file info or array of file info objects) to the function for encoding as Base16: $MyObject | ConvertTo-Base16 .EXAMPLE Convert a byte array to Base16 and return the output with block formatting and not wrapped in a PSObject (as a raw [System.String]): ConvertTo-Base16 -ByteArray $Bytes -Raw .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Base16 encoded file with block formatting for each input file: Get-ChildItem C:\Text\*.txt | ConvertTo-Base16 -AutoSave "B16" .EXAMPLE Use file based input to Base16 encode an input file and output the results as new file C:\Text\Base16.txt with no line breaks or header / footer: ConvertTo-Base16 -File C:\Text\file.txt -OutFile C:\Text\Base16.txt -Unformatted .NOTES This function uses the built-in ToString("X2") method for converting arbitrary bytes into hexadecimal string; more information on the Base16, Base16, and Base16 Data Encoding standard can be found on the IETF web site: https://tools.ietf.org/html/rfc4648 #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Byte array to Base16 encode.' )] [ValidateNotNullOrEmpty()] [Alias('ByteArray','Data')] [System.Byte[]]$Bytes, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='String to Base16 encode.' )] [ValidateNotNullOrEmpty()] [Alias('Plaintext','Text')] [System.String]$String, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to Base16 encode.' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName','File')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$False, Position=1, HelpMessage='Output result to specified file as UTF8-NoBOM text instead of console.' )] [Parameter( ParameterSetName="ByteInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Do not format output string using header/footer and line breaks.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Unformatted, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning a string instead of a file, return a raw string instead of PSObject; applies to both console and file output modes.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { [System.String]$B16Header = "-----BEGIN BASE16 ENCODED DATA-----" [System.String]$B16Footer = "-----END BASE16 ENCODED DATA-----" [System.String]$OFS = "" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File If ($Raw) { Write-Warning "File output mode specified; Parameter '-Raw' will be ignored." } } Switch ($PSCmdlet.ParameterSetName) { "ByteInput" { [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,$Bytes) Break } "StringInput" { [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,[System.Text.Encoding]::ASCII.GetBytes($String)) Break } "FileInput" { [System.IO.Stream]$InputStream = [System.IO.File]::Open($InFile.FullName,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::ReadWrite) Break } } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() [System.Object]$BinaryReader = New-Object -TypeName System.IO.BinaryReader($InputStream) [System.Object]$Base16Output = New-Object -TypeName System.Text.StringBuilder If (-Not $Unformatted) { [void]$Base16Output.Append("$($B16Header)`r`n") } [System.String]$B16Line = [String]::Empty Try { While ([System.Byte[]]$BytesRead = $BinaryReader.ReadBytes(2)) { [System.Boolean]$AtEnd = ($BinaryReader.BaseStream.Length -eq $BinaryReader.BaseStream.Position) [System.String]$B16 = ForEach ($Byte in $BytesRead) { $Byte.ToString("X2") } $B16Line += $B16 If ($B16Line.Length -eq 64 -and -not $Unformatted) { [void]$Base16Output.Append($B16Line + "`r`n") [System.String]$B16Line = [String]::Empty } ElseIf ($AtEnd) { [void]$Base16Output.Append($B16Line) } } If (-Not $Unformatted) { [void]$Base16Output.Append("`r`n$($B16Footer)") } [System.String]$Base16Result = $Base16Output.ToString() $Base16ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllLines($OutFile.FullName,$Base16Result,(New-Object -TypeName System.Text.UTF8Encoding $False)) $Base16ResultObject = $OutFile } Else { If ($Raw) { $Base16ResultObject = $Base16Result } Else { Add-Member -InputObject $Base16ResultObject -MemberType 'NoteProperty' -Name 'Base16EncodedData' -Value $Base16Result } } Return ($Base16ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $BinaryReader.Close() $BinaryReader.Dispose() $InputStream.Close() $InputStream.Dispose() $Timer.Stop() [System.String]$TimeLapse = "Base16 encode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertFrom-Base16() { <# .SYNOPSIS A PowerShell function to convert an arbitrary Base16 encoded string into a byte array or binary file. .DESCRIPTION Takes a string of Base16 formatted data and decodes into the original ASCII string or byte array. Input includes a Base16 string or a file containing Base16 string. Both formatted (line breaks) and unformatted Base16 data are supported. The default input and output type if positional parameters are used is [System.String]; it is also possible to write a binary file from the Base16 input using -OutFile. .PARAMETER Base16EncodedString [System.String] object containing Base16 encoded data. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be loaded as a string object and decoded from Base16 string; accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing Base16 decoded data from the input file. Can be used with any input mode (Bytes, String, or InFile); file content will be raw decoded bytes. .PARAMETER OutBytes Return the decoded data as [System.Byte[]] to the console instead of the default ASCII string. .PARAMETER AutoSave When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter; for example, -AutoSave "BIN" will result in OutFile name <InFile>.bin. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw output instead of a PSObject. Depending on the parameters used, the return object could be of type [System.String] or [System.Byte[]]. .INPUTS Any single object, array or collection of strings or files (such as those from Get-ChildItem) can be piped to the function for processing from Base16 encoded data. Input data from file is always processed as ASCII text regardless of source file text encoding. .OUTPUTS In the case of direct string input, a [System.String] containing the decoded data as ASCII text is returned within a PSObject with a single member named Base16DecodedData. If any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a binary file with the Base16 decoded data as contents. If -OutBytes is specified, data is returned to the console as [System.Byte[]] wrapped in a PSObject. If -Raw is specified, the [System.String] or [System.Byte[]] is not wrapped in a PSObject and is returned directly. This means that output using -Raw cannot easily use the pipeline. The -Verbose parameter will return the function's total execution time. .EXAMPLE Pipe an object (string or array of strings, file info or array of file info objects) to the function for decoding from Base16: $MyObject | ConvertFrom-Base16 .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Base16 decoded file for each input file: Get-ChildItem C:\Text\*.B16 | ConvertFrom-Base16 -AutoSave "BIN" .EXAMPLE Use file based input to decode an input file and output the results as new file C:\Text\file.txt: ConvertFrom-Base16 -File C:\Text\file.B16 -OutFile C:\Text\file.txt .NOTES This function uses the built-in [System.Convert]::ToByte() method to convert bytes to Base 16 (hex); more information on the Base16, Base16, and Base16 Data Encoding standard can be found on the IETF web site: https://tools.ietf.org/html/rfc4648 #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Base16 encoded string.' )] [ValidateNotNullOrEmpty()] [Alias('String','Plaintext','Text','Base16EncodedData')] [System.String]$Base16EncodedString, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to Base16 decode.' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, Position=1, HelpMessage='Path to output file when decoding in file mode.' )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Output decoded data as raw bytes instead of ASCII text.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$OutBytes, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning to console, return a raw byte array instead of PSObject.' )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { If ($PSBoundParameters.ContainsKey("AutoSave") -and $PSCmdlet.ParameterSetName -ne "FileInput") { Write-Error "-AutoSave can only be used in file input mode." -ErrorAction Stop } [System.String]$B16CHARSET_Pattern = "^[A-F0-9 ]*$" [System.String]$B16Header = "-----BEGIN BASE16 ENCODED DATA-----" [System.String]$B16Footer = "-----END BASE16 ENCODED DATA-----" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File } Switch ($PSCmdlet.ParameterSetName) { "StringInput" { [System.String]$Base16String = $Base16EncodedString.Replace($B16Header,"").Replace($B16Footer,"").Replace(" ","").Replace("`r`n","").Replace("`n","") Break } "FileInput" { [System.String]$Base16String = ([System.IO.File]::ReadAllText($InFile.FullName)).Replace($B16Header,"").Replace($B16Footer,"").Replace(" ","").Replace("`r`n","").Replace("`n","") Break } } If (-not ($Base16String -imatch $B16CHARSET_Pattern)) { Throw "Invalid Base16 data encountered." } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() Try { [System.Byte[]]$B16Results = [System.Byte[]]::new($Base16String.Length / 2) For($i = 0; $i -lt $Base16String.Length; $i += 2){ $B16Results[$i / 2] = [System.Convert]::ToByte($Base16String.Substring($i, 2), 16) } $ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllBytes($OutFile,$B16Results) $ResultObject = $OutFile } Else { If ($OutBytes -and $Raw) { $ResultObject = $B16Results } ElseIf ($OutBytes) { Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'Base16DecodedData' -Value $B16Results } ElseIf ($Raw) { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString($B16Results) $ResultObject = $Results } Else { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString($B16Results) Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'Base16DecodedString' -Value $Results } } Return ($ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $Timer.Stop() [System.String]$TimeLapse = "Base16 decode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertTo-Base32() { <# .SYNOPSIS A PowerShell function to convert arbitrary data into a Base32 encoded string. .DESCRIPTION Takes a string, byte array or file object as input and returns a Base32 encoded string or location of the Base32 result output file object. The default input and output type if positional parameters are used is [System.String]. .PARAMETER Bytes [System.Byte[]] object containing a byte array to be encoded as Base32 string. Accepts pipeline input. .PARAMETER String [System.String] object containing plain text to be encoded as Base32 string. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be converted to Base32 string and output as a new file; output files are written as UTF-8 no BOM. Accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing Base32 encoded data from the input file. Can be used with any input mode (Bytes, String, or InFile). .PARAMETER Unormatted By default the function adds line breaks to output string every 64 characters and block style header / footer (-----BEGIN BASE32 ENCODED DATA-----/-----END BASE32 ENCODED DATA-----); this parameter suppresses formatting and returns the Base32 string result as a single, unbroken string object with no header or footer. .PARAMETER Base32Hex Use the alternative charset described in RFC4648 for "Base32 Hex" (0123456789ABCDEFGHIJKLMNOPQRSTUV) instead of the typical Base32 charset (ABCDEFGHIJKLMNOPQRSTUVWXYZ234567). .PARAMETER AutoSave [System.String] containing a new file extension to use to automatically generate files. When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter, for example -AutoSave "B32" would create the OutFile name <InFile>.b32. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw string output instead of a PSObject. This parameter limits the functionality of the pipeline but is convenient for simple encoding operations. .INPUTS Any single object or collection of strings, bytes, or files (such as those from Get-ChildItem) can be piped to the function for processing into Base32 encoded data. .OUTPUTS The output is always an ASCII string; if any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a UTF8 no BOM text file with the Base32 encoded data as contents. Unless -Unformatted is specified, the console or file string data is formatted with block headers (-----BEGIN BASE32 ENCODED DATA-----/-----END BASE32 ENCODED DATA-----) and line breaks are added every 64 character. If -Unformatted is present, the output is a [System.String] with no line breaks or header / footer. If outputting to the console, the string is returned within a PSObject with a single member named Base32EncodedData as [System.String]; if -Raw is specified, the [System.String] is not wrapped in a PSObject and returned directly. This means that output using -Raw cannot easily use the pipeline, but makes it a useful option for quick encoding operations. The -Verbose parameter will return the function's total execution time. .EXAMPLE Convert a string directly into Base32: ConvertTo-Base32 "This is a plaintext string" .EXAMPLE Pipe an object (string or array of strings, byte array or array of byte arrays, file info or array of file info objects) to the function for encoding as Base32: $MyObject | ConvertTo-Base32 .EXAMPLE Convert a byte array to Base32 and return the output with block formatting and not wrapped in a PSObject (as a raw [System.String]): ConvertTo-Base32 -ByteArray $Bytes -Raw .EXAMPLE Load the contents of a file as byte array and convert directly into Base32-Hex: ConvertTo-Base32 -Base32Hex -ByteArray ([System.IO.File]::ReadAllBytes('C:\File.txt')) .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Base32 encoded file with block formatting for each input file: Get-ChildItem C:\Text\*.txt | ConvertTo-Base32 -AutoSave "B32" .EXAMPLE Use file based input to Base32 encode an input file and output the results as new file C:\Text\base32.txt with no line breaks or header / footer: ConvertTo-Base32 -File C:\Text\file.txt -OutFile C:\Text\base32.txt -Unformatted .NOTES More information on the Base16, Base32, and Base64 Data Encoding standard can be found on the IETF web site: https://tools.ietf.org/html/rfc4648 #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Byte array to Base32 encode.' )] [ValidateNotNullOrEmpty()] [Alias('ByteArray','Data')] [System.Byte[]]$Bytes, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='String to Base32 encode.' )] [ValidateNotNullOrEmpty()] [Alias('Plaintext','Text')] [System.String]$String, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to Base32 encode.' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName','File')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$False, Position=1, HelpMessage='Output result to specified file as UTF8-NoBOM text instead of console.' )] [Parameter( ParameterSetName="ByteInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Do not format output string using header/footer and line breaks.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Unformatted, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Use extended Base32 Hex charset instead of standard Base32 charset.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Base32Hex, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning a string instead of a file, return a raw string instead of PSObject; applies to both console and file output modes.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { If ($Base32Hex) { [System.String]$B32CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUV" [System.String]$B32Name = "Base32-Hex" } Else { [System.String]$B32CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" [System.String]$B32Name = "Base32" } [System.String]$B32Header = "-----BEGIN $($B32Name.ToUpper()) ENCODED DATA-----" [System.String]$B32Footer = "-----END $($B32Name.ToUpper()) ENCODED DATA-----" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File If ($Raw) { Write-Warning "File output mode specified; Parameter '-Raw' will be ignored." } } Switch ($PSCmdlet.ParameterSetName) { "ByteInput" { [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,$Bytes) Break } "StringInput" { [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,[System.Text.Encoding]::ASCII.GetBytes($String)) Break } "FileInput" { [System.IO.Stream]$InputStream = [System.IO.File]::Open($InFile.FullName,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::ReadWrite) Break } } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() [System.Object]$BinaryReader = New-Object -TypeName System.IO.BinaryReader($InputStream) [System.Object]$Base32Output = New-Object -TypeName System.Text.StringBuilder If (-Not $Unformatted) { [void]$Base32Output.Append("$($B32Header)`r`n") } Try { While ([System.Byte[]]$BytesRead = $BinaryReader.ReadBytes(5)) { [System.Boolean]$AtEnd = ($BinaryReader.BaseStream.Length -eq $BinaryReader.BaseStream.Position) [System.UInt16]$ByteLength = $BytesRead.Length If ($ByteLength -lt 5) { [System.Byte[]]$WorkingBytes = ,0x00 * 5 [System.Buffer]::BlockCopy($BytesRead,0,$WorkingBytes,0,$ByteLength) [System.Array]::Resize([ref]$BytesRead,5) [System.Buffer]::BlockCopy($WorkingBytes,0,$BytesRead,0,5) } [System.Char[]]$B32Chars = ,0x00 * 8 [System.Char[]]$B32Chunk = ,"=" * 8 $B32Chars[0] = ($B32CHARSET[($BytesRead[0] -band 0xF8) -shr 3]) $B32Chars[1] = ($B32CHARSET[(($BytesRead[0] -band 0x07) -shl 2) -bor (($BytesRead[1] -band 0xC0) -shr 6)]) $B32Chars[2] = ($B32CHARSET[($BytesRead[1] -band 0x3E) -shr 1]) $B32Chars[3] = ($B32CHARSET[(($BytesRead[1] -band 0x01) -shl 4) -bor (($BytesRead[2] -band 0xF0) -shr 4)]) $B32Chars[4] = ($B32CHARSET[(($BytesRead[2] -band 0x0F) -shl 1) -bor (($BytesRead[3] -band 0x80) -shr 7)]) $B32Chars[5] = ($B32CHARSET[($BytesRead[3] -band 0x7C) -shr 2]) $B32Chars[6] = ($B32CHARSET[(($BytesRead[3] -band 0x03) -shl 3) -bor (($BytesRead[4] -band 0xE0) -shr 5)]) $B32Chars[7] = ($B32CHARSET[$BytesRead[4] -band 0x1F]) [System.Array]::Copy($B32Chars,$B32Chunk,([Math]::Ceiling(($ByteLength / 5) * 8))) If ($BinaryReader.BaseStream.Position % 8 -eq 0 -and -Not $Unformatted -and -not $AtEnd) { [void]$Base32Output.Append($B32Chunk) [void]$Base32Output.Append("`r`n") } Else { [void]$Base32Output.Append($B32Chunk) } } If (-Not $Unformatted) { [void]$Base32Output.Append("`r`n$($B32Footer)") } [System.String]$Base32Result = $Base32Output.ToString() $Base32ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllLines($OutFile.FullName,$Base32Result,(New-Object -TypeName System.Text.UTF8Encoding $False)) $Base32ResultObject = $OutFile } Else { If ($Raw) { $Base32ResultObject = $Base32Result } Else { Add-Member -InputObject $Base32ResultObject -MemberType 'NoteProperty' -Name 'Base32EncodedData' -Value $Base32Result } } Return ($Base32ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $BinaryReader.Close() $BinaryReader.Dispose() $InputStream.Close() $InputStream.Dispose() $Timer.Stop() [System.String]$TimeLapse = "Base32 encode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertFrom-Base32() { <# .SYNOPSIS A PowerShell function to convert an arbitrary Base32 encoded string into a byte array or binary file. .DESCRIPTION Takes a string of Base32 formatted data and decodes into the original ASCII string or byte array. Input includes a Base32 string or a file containing Base32 string. Both formatted (line breaks) and unformatted Base32 data are supported. The default input and output type if positional parameters are used is [System.String]; it is also possible to write a binary file from the Base32 input using -OutFile. .PARAMETER Base32EncodedString [System.String] object containing Base32 encoded data. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be loaded as a string object and decoded from Base32 string; accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing Base32 decoded data from the input file. Can be used with any input mode (Bytes, String, or InFile); file content will be raw decoded bytes. .PARAMETER Base32Hex Use the alternative charset described in RFC4648 for "Base32 Hex" (0123456789ABCDEFGHIJKLMNOPQRSTUV) instead of the typical Base32 charset (ABCDEFGHIJKLMNOPQRSTUVWXYZ234567) when decoding. .PARAMETER OutBytes Return the decoded data as [System.Byte[]] to the console instead of the default ASCII string. .PARAMETER AutoSave When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter; for example, -AutoSave "BIN" will result in OutFile name <InFile>.bin. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw output instead of a PSObject. Depending on the parameters used, the return object could be of type [System.String] or [System.Byte[]]. .INPUTS Any single object, array or collection of strings or files (such as those from Get-ChildItem) can be piped to the function for processing from Base32 encoded data. Input data from file is always processed as ASCII text regardless of source file text encoding. .OUTPUTS In the case of direct string input, a [System.String] containing the decoded data as ASCII text is returned within a PSObject with a single member named Base32DecodedData. If any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a binary file with the Base32 decoded data as contents. If -OutBytes is specified, data is returned to the console as [System.Byte[]] wrapped in a PSObject. If -Raw is specified, the [System.String] or [System.Byte[]] is not wrapped in a PSObject and is returned directly. This means that output using -Raw cannot easily use the pipeline. The -Verbose parameter will return the function's total execution time. .EXAMPLE Convert a Base32 string to a decoded byte array: [System.Byte[]]$Bytes = ConvertFrom-Base32 "IIAGCADTABSQAMYAGIAA====" -OutBytes -Raw .EXAMPLE Decode a Base32 encoded string: ConvertFrom-Base32 -Base32EncodedString "IIAGCADTABSQAMYAGIAA====" .EXAMPLE Pipe an object (string or array of strings, file info or array of file info objects) to the function for decoding from Base32: $MyObject | ConvertFrom-Base32 .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Base32 decoded file for each input file: Get-ChildItem C:\Text\*.b32 | ConvertFrom-Base32 -AutoSave "BIN" .EXAMPLE Use file based input to decode an input file and output the results as new file C:\Text\file.txt: ConvertFrom-Base32 -File C:\Text\file.b32 -OutFile C:\Text\file.txt .NOTES More information on the Base16, Base32, and Base64 Data Encoding standard can be found on the IETF web site: https://tools.ietf.org/html/rfc4648 #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Base32 encoded string.' )] [ValidateNotNullOrEmpty()] [Alias('String','Plaintext','Text','Base32EncodedData')] [System.String]$Base32EncodedString, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to Base32 decode.' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, Position=1, HelpMessage='Path to output file when decoding in file mode.' )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Use extended Base32 Hex charset instead of standard Base32 charset.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Base32Hex, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Output decoded data as raw bytes instead of ASCII text.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$OutBytes, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning to console, return a raw byte array instead of PSObject.' )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { If ($PSBoundParameters.ContainsKey("AutoSave") -and $PSCmdlet.ParameterSetName -ne "FileInput") { Write-Error "-AutoSave can only be used in file input mode." -ErrorAction Stop } If ($Base32Hex) { [System.String]$B32CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUV" [System.String]$B32CHARSET_Pattern = "^[A-V0-9 ]+=*$" [System.String]$B32Name = "Base32-Hex" } Else { [System.String]$B32CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" [System.String]$B32CHARSET_Pattern = "^[A-Z2-7 ]+=*$" [System.String]$B32Name = "Base32" } [System.String]$B32Header = "-----BEGIN $($B32Name.ToUpper()) ENCODED DATA-----" [System.String]$B32Footer = "-----END $($B32Name.ToUpper()) ENCODED DATA-----" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File } Switch ($PSCmdlet.ParameterSetName) { "StringInput" { [System.String]$Base32String = $Base32EncodedString.Replace($B32Header,"").Replace($B32Footer,"").Replace(" ","").Replace("`r`n","").Replace("`n","").ToUpper() Break } "FileInput" { [System.String]$Base32String = ([System.IO.File]::ReadAllText($InFile.FullName)).Replace($B32Header,"").Replace($B32Footer,"").Replace(" ","").Replace("`r`n","").Replace("`n","").ToUpper() Break } } If (-not ($Base32String -match $B32CHARSET_Pattern)) { Throw ("Invalid Base32 data encountered in input stream.") } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() [System.Object]$InputStream = New-Object -TypeName System.IO.MemoryStream([System.Text.Encoding]::ASCII.GetBytes($Base32String),0,$Base32String.Length) [System.Object]$BinaryReader = New-Object -TypeName System.IO.BinaryReader($InputStream) [System.Object]$OutputStream = New-Object -TypeName System.IO.MemoryStream [System.Object]$BinaryWriter = New-Object -TypeName System.IO.BinaryWriter($OutputStream) Try { While ([System.Char[]]$CharsRead = $BinaryReader.ReadChars(8)) { [System.Byte[]]$B32Bytes = ,0x00 * 5 [System.UInt16]$CharLen = 8 - ($CharsRead -Match "=").Count [System.UInt16]$ByteLen = [Math]::Floor(($CharLen * 5) / 8) [System.Byte[]]$BinChunk = ,0x00 * $ByteLen If ($CharLen -lt 8) { [System.Char[]]$WorkingChars = ,"A" * 8 [System.Array]::Copy($CharsRead,$WorkingChars,$CharLen) [System.Array]::Resize([ref]$CharsRead,8) [System.Array]::Copy($WorkingChars,$CharsRead,8) } $B32Bytes[0] = (($B32CHARSET.IndexOf($CharsRead[0]) -band 0x1F) -shl 3) -bor (($B32CHARSET.IndexOf($CharsRead[1]) -band 0x1C) -shr 2) $B32Bytes[1] = (($B32CHARSET.IndexOf($CharsRead[1]) -band 0x03) -shl 6) -bor (($B32CHARSET.IndexOf($CharsRead[2]) -band 0x1F) -shl 1) -bor (($B32CHARSET.IndexOf($CharsRead[3]) -band 0x10) -shr 4) $B32Bytes[2] = (($B32CHARSET.IndexOf($CharsRead[3]) -band 0x0F) -shl 4) -bor (($B32CHARSET.IndexOf($CharsRead[4]) -band 0x1E) -shr 1) $B32Bytes[3] = (($B32CHARSET.IndexOf($CharsRead[4]) -band 0x01) -shl 7) -bor (($B32CHARSET.IndexOf($CharsRead[5]) -band 0x1F) -shl 2) -bor (($B32CHARSET.IndexOf($CharsRead[6]) -band 0x18) -shr 3) $B32Bytes[4] = (($B32CHARSET.IndexOf($CharsRead[6]) -band 0x07) -shl 5) -bor ($B32CHARSET.IndexOf($CharsRead[7]) -band 0x1F) [System.Buffer]::BlockCopy($B32Bytes, 0, $BinChunk, 0, $ByteLen) $BinaryWriter.Write($BinChunk) } $ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllBytes($OutFile,($OutputStream.ToArray())) $ResultObject = $OutFile } Else { If ($OutBytes -and $Raw) { $ResultObject = $OutputStream.ToArray() } ElseIf ($OutBytes) { Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'ByteArray' -Value $OutputStream.ToArray() } ElseIf ($Raw) { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString(($OutputStream.ToArray())) $ResultObject = $Results } Else { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString(($OutputStream.ToArray())) Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'Base32DecodedString' -Value $Results } } Return ($ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $BinaryReader.Close() $BinaryReader.Dispose() $BinaryWriter.Close() $BinaryWriter.Dispose() $InputStream.Close() $InputStream.Dispose() $OutputStream.Close() $OutputStream.Dispose() $Timer.Stop() [System.String]$TimeLapse = "Base32 decode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertTo-Base64() { <# .SYNOPSIS A PowerShell function to convert arbitrary data into a Base64 encoded string. .DESCRIPTION Takes a string, byte array or file object as input and returns a Base64 encoded string or location of the Base64 result output file object. The default input and output type if positional parameters are used is [System.String]. .PARAMETER Bytes [System.Byte[]] object containing a byte array to be encoded as Base64 string. Accepts pipeline input. .PARAMETER String [System.String] object containing plain text to be encoded as Base64 string. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be converted to Base64 string and output as a new file; output files are written as UTF-8 no BOM. Accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing Base64 encoded data from the input file. Can be used with any input mode (Bytes, String, or InFile). .PARAMETER Unormatted By default the function adds line breaks to output string every 64 characters and block style header / footer (-----BEGIN BASE64 ENCODED DATA-----/-----END BASE64 ENCODED DATA-----); this parameter suppresses formatting and returns the Base64 string result as a single, unbroken string object with no header or footer. .PARAMETER AutoSave [System.String] containing a new file extension to use to automatically generate files. When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter, for example -AutoSave "B64" would create the OutFile name <InFile>.B64. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw string output instead of a PSObject. This parameter limits the functionality of the pipeline but is convenient for simple encoding operations. .INPUTS Any single object or collection of strings, bytes, or files (such as those from Get-ChildItem) can be piped to the function for processing into Base64 encoded data. .OUTPUTS The output is always an ASCII string; if any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a UTF8 no BOM text file with the Base64 encoded data as contents. Unless -Unformatted is specified, the console or file string data is formatted with block headers (-----BEGIN BASE64 ENCODED DATA-----/-----END BASE64 ENCODED DATA-----) and line breaks are added every 64 character. If -Unformatted is present, the output is a [System.String] with no line breaks or header / footer. If outputting to the console, the string is returned within a PSObject with a single member named Base64EncodedData as [System.String]; if -Raw is specified, the [System.String] is not wrapped in a PSObject and returned directly. This means that output using -Raw cannot easily use the pipeline, but makes it a useful option for quick encoding operations. The -Verbose parameter will return the function's total execution time. .EXAMPLE Convert a string directly into Base64: ConvertTo-Base64 "This is a plaintext string" .EXAMPLE Pipe an object (string or array of strings, byte array or array of byte arrays, file info or array of file info objects) to the function for encoding as Base64: $MyObject | ConvertTo-Base64 .EXAMPLE Convert a byte array to Base64 and return the output with block formatting and not wrapped in a PSObject (as a raw [System.String]): ConvertTo-Base64 -ByteArray $Bytes -Raw .EXAMPLE Load the contents of a file as byte array and convert directly into Base64-Hex: ConvertTo-Base64 -Base64Hex -ByteArray ([System.IO.File]::ReadAllBytes('C:\File.txt')) .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Base64 encoded file with block formatting for each input file: Get-ChildItem C:\Text\*.txt | ConvertTo-Base64 -AutoSave "B64" .EXAMPLE Use file based input to Base64 encode an input file and output the results as new file C:\Text\Base64.txt with no line breaks or header / footer: ConvertTo-Base64 -File C:\Text\file.txt -OutFile C:\Text\Base64.txt -Unformatted .NOTES This function uses the built-in [System.Convert]::ToBase64String() method so it is obscenely fast compared to the hand-rolled methods used in other functions from this module. More information on the Base16, Base64, and Base64 Data Encoding standard can be found on the IETF web site: https://tools.ietf.org/html/rfc4648 #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Byte array to Base64 encode.' )] [ValidateNotNullOrEmpty()] [Alias('ByteArray','Data')] [System.Byte[]]$Bytes, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='String to Base64 encode.' )] [ValidateNotNullOrEmpty()] [Alias('Plaintext','Text')] [System.String]$String, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to Base64 encode.' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName','File')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$False, Position=1, HelpMessage='Output result to specified file as UTF8-NoBOM text instead of console.' )] [Parameter( ParameterSetName="ByteInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Do not format output string using header/footer and line breaks.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Unformatted, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning a string instead of a file, return a raw string instead of PSObject; applies to both console and file output modes.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { [System.String]$B64Header = "-----BEGIN BASE64 ENCODED DATA-----" [System.String]$B64Footer = "-----END BASE64 ENCODED DATA-----" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File If ($Raw) { Write-Warning "File output mode specified; Parameter '-Raw' will be ignored." } } Switch ($PSCmdlet.ParameterSetName) { "ByteInput" { [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,$Bytes) Break } "StringInput" { [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,[System.Text.Encoding]::ASCII.GetBytes($String)) Break } "FileInput" { [System.IO.Stream]$InputStream = [System.IO.File]::Open($InFile.FullName,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::ReadWrite) Break } } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() [System.Object]$BinaryReader = New-Object -TypeName System.IO.BinaryReader($InputStream) [System.Object]$Base64Output = New-Object -TypeName System.Text.StringBuilder If (-Not $Unformatted) { [void]$Base64Output.Append("$($B64Header)`r`n") } [System.String]$B64Line = [String]::Empty Try { While ([System.Byte[]]$BytesRead = $BinaryReader.ReadBytes(3)) { [System.Boolean]$AtEnd = ($BinaryReader.BaseStream.Length -eq $BinaryReader.BaseStream.Position) $B64Line += [System.Convert]::ToBase64String($BytesRead) If ($B64Line.Length -eq 64 -and -not $Unformatted) { [void]$Base64Output.Append($B64Line + "`r`n") [System.String]$B64Line = [String]::Empty } ElseIf ($AtEnd) { [void]$Base64Output.Append($B64Line) } } If (-Not $Unformatted) { [void]$Base64Output.Append("`r`n$($B64Footer)") } [System.String]$Base64Result = $Base64Output.ToString() $Base64ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllLines($OutFile.FullName,$Base64Result,(New-Object -TypeName System.Text.UTF8Encoding $False)) $Base64ResultObject = $OutFile } Else { If ($Raw) { $Base64ResultObject = $Base64Result } Else { Add-Member -InputObject $Base64ResultObject -MemberType 'NoteProperty' -Name 'Base64EncodedData' -Value $Base64Result } } Return ($Base64ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $BinaryReader.Close() $BinaryReader.Dispose() $InputStream.Close() $InputStream.Dispose() $Timer.Stop() [System.String]$TimeLapse = "Base64 encode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertFrom-Base64() { <# .SYNOPSIS A PowerShell function to convert an arbitrary Base64 encoded string into a byte array or binary file. .DESCRIPTION Takes a string of Base64 formatted data and decodes into the original ASCII string or byte array. Input includes a Base64 string or a file containing Base64 string. Both formatted (line breaks) and unformatted Base64 data are supported. The default input and output type if positional parameters are used is [System.String]; it is also possible to write a binary file from the Base64 input using -OutFile. .PARAMETER Base64EncodedString [System.String] object containing Base64 encoded data. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be loaded as a string object and decoded from Base64 string; accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing Base64 decoded data from the input file. Can be used with any input mode (Bytes, String, or InFile); file content will be raw decoded bytes. .PARAMETER OutBytes Return the decoded data as [System.Byte[]] to the console instead of the default ASCII string. .PARAMETER AutoSave When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter; for example, -AutoSave "BIN" will result in OutFile name <InFile>.bin. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw output instead of a PSObject. Depending on the parameters used, the return object could be of type [System.String] or [System.Byte[]]. .INPUTS Any single object, array or collection of strings or files (such as those from Get-ChildItem) can be piped to the function for processing from Base64 encoded data. Input data from file is always processed as ASCII text regardless of source file text encoding. .OUTPUTS In the case of direct string input, a [System.String] containing the decoded data as ASCII text is returned within a PSObject with a single member named Base64DecodedData. If any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a binary file with the Base64 decoded data as contents. If -OutBytes is specified, data is returned to the console as [System.Byte[]] wrapped in a PSObject. If -Raw is specified, the [System.String] or [System.Byte[]] is not wrapped in a PSObject and is returned directly. This means that output using -Raw cannot easily use the pipeline. The -Verbose parameter will return the function's total execution time. .EXAMPLE Convert a Base64 string to a decoded byte array: [System.Byte[]]$Bytes = ConvertFrom-Base64 "VGhpcyBpcyBCYXNlNjQgdGV4dA==" -OutBytes -Raw .EXAMPLE Decode a Base64 encoded string: ConvertFrom-Base64 -Base64EncodedString "VGhpcyBpcyBCYXNlNjQgdGV4dA==" .EXAMPLE Pipe an object (string or array of strings, file info or array of file info objects) to the function for decoding from Base64: $MyObject | ConvertFrom-Base64 .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Base64 decoded file for each input file: Get-ChildItem C:\Text\*.B64 | ConvertFrom-Base64 -AutoSave "BIN" .EXAMPLE Use file based input to decode an input file and output the results as new file C:\Text\file.txt: ConvertFrom-Base64 -File C:\Text\file.B64 -OutFile C:\Text\file.txt .NOTES This function uses the built-in [System.Convert]::FromBase64String() method so it is obscenely fast compared to the hand-rolled methods used in other functions from this module. More information on the Base16, Base64, and Base64 Data Encoding standard can be found on the IETF web site: https://tools.ietf.org/html/rfc4648 #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Base64 encoded string.' )] [ValidateNotNullOrEmpty()] [Alias('String','Plaintext','Text','Base64EncodedData')] [System.String]$Base64EncodedString, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to Base64 decode.' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, Position=1, HelpMessage='Path to output file when decoding in file mode.' )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Output decoded data as raw bytes instead of ASCII text.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$OutBytes, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning to console, return a raw byte array instead of PSObject.' )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { If ($PSBoundParameters.ContainsKey("AutoSave") -and $PSCmdlet.ParameterSetName -ne "FileInput") { Write-Error "-AutoSave can only be used in file input mode." -ErrorAction Stop } [System.String]$B64CHARSET_Pattern = "^[a-zA-Z0-9/+]*={0,2}$" [System.String]$B64Header = "-----BEGIN BASE64 ENCODED DATA-----" [System.String]$B64Footer = "-----END BASE64 ENCODED DATA-----" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File } Switch ($PSCmdlet.ParameterSetName) { "StringInput" { [System.String]$Base64String = $Base64EncodedString.Replace($B64Header,"").Replace($B64Footer,"").Replace(" ","").Replace("`r`n","").Replace("`n","") Break } "FileInput" { [System.String]$Base64String = ([System.IO.File]::ReadAllText($InFile.FullName)).Replace($B64Header,"").Replace($B64Footer,"").Replace(" ","").Replace("`r`n","").Replace("`n","") Break } } If (-not ($Base64String -imatch $B64CHARSET_Pattern)) { Throw "Invalid Base64 data encountered." Return } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() Try { [System.Byte[]]$B64Results = [System.Byte[]][Convert]::FromBase64String($Base64String) $ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllBytes($OutFile,$B64Results) $ResultObject = $OutFile } Else { If ($OutBytes -and $Raw) { $ResultObject = $B64Results } ElseIf ($OutBytes) { Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'Base64DecodedData' -Value $B64Results } ElseIf ($Raw) { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString($B64Results) $ResultObject = $Results } Else { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString($B64Results) Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'Base64DecodedString' -Value $Results } } Return ($ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $Timer.Stop() [System.String]$TimeLapse = "Base64 decode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertTo-UUEncoding() { <# .SYNOPSIS A PowerShell function to convert an arbitrary byte array into a UNIX-to-UNIX (UU) encoded string. .DESCRIPTION Takes a string, byte array or file as input and returns a UUencoded string or file info for a new UUencoded copy of the input file as a result. The default input and output type if positional parameters are used is [System.String]. .PARAMETER Bytes [System.Byte[]] object containing a byte array to be UUencoded. Accepts pipeline input. .PARAMETER String [System.String] object containing plain text to be UUencoded. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be converted to UUencoded string and output as a new file; output files are written as UTF-8 no BOM. Accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing UUencoded data from the input file. Can be used with any input mode (Bytes, String, or InFile). .PARAMETER AutoSave [System.String] containing a new file extension to use to automatically generate files. When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter. For example, -AutoSave "UU" will produce OutFile name <InFile>.UU. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Unformatted When the -Unformatted switch is specified, the returned uuencoded string has no header, footer, line breaks or byte length indicators; a single unbroken [System.String] is returned instead. Using this option will produce output that is considered invalid by most uudecode applications and such data cannot be decoded by utilities like the Linux uuencode binary. However, unformatted uuencoded strings can still be successfully decoded by this module's ConvertFrom-UUEncoding function. .PARAMETER Raw Optional switch parameter that when present will produce raw string output instead of a PSObject. This parameter limits the functionality of the pipeline but is convenient for simple encoding operations within a script. .INPUTS Any single object or collection of strings, bytes, or files (such as those from Get-ChildItem) can be piped to the function for processing into UUencoded data. .OUTPUTS The output is always an ASCII string; if any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a UTF8 no BOM text file with the UUencoded data as contents. String data is formatted with uuencode-compliant header, footer, line length and line breaks - it is possible to decode UUencoded data from this function using the Linux UUdecode utility. The function adds required uuencoding header row (begin nnnn filename) and ending row (end); the function also adds a line break every 60 characters per the specification, and a UUencoded value containing the line length is also inserted at the beginning of each line for a total of 61 characters per line on full line input. This format is required by the specification and is not mutable. If outputting to the console, the string is returned within a PSObject as [System.String] with a single member named UUEncodedData; if -Raw is specified, the [System.String] is not wrapped in a PSObject and returned directly. This means that output using -Raw cannot easily use the pipeline, but makes it a useful option for quick encoding operations. The -Verbose parameter will return the function's total execution time. .EXAMPLE Convert a string directly into UUencoded string: ConvertTo-UUEncoding "This is a plaintext string" -Raw .EXAMPLE Pipe an object (string or array of strings, byte array or array of byte arrays, file info or array of file info objects) to the function for uuencoding: $MyObject | ConvertTo-UUEncoding .EXAMPLE Convert a byte array to UUencoded string and return the output with block formatting and not wrapped in a PSObject (as a raw [System.String]): ConvertTo-UUEncoding -ByteArray $Bytes -Raw .EXAMPLE Load the contents of a file as byte array and convert directly UUencoded string: ConvertTo-UUEncoding -ByteArray ([System.IO.File]::ReadAllBytes('C:\File.txt')) .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new UUencoded file with block formatting for each input file: Get-ChildItem C:\Text\*.txt | ConvertTo-UUEncoding -AutoSave "UU" .EXAMPLE Use file based input to uuencode an input file and output the results as new file C:\Text\UU.txt: ConvertTo-UUEncoding -File C:\Text\file.txt -OutFile C:\Text\UU.txt .NOTES UNIX-style line breaks (\n) are used as opposed to Windows-style line breaks (\r\n) on output string data; this is to maintain compatibility with Linux UUdecode utilities. This function is really geared more toward encoding / decoding files vs. string or pipeline input. UUencoding in general has been largely replaced by Base64, which does not suffer from the same technical limitations. #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Byte array to uuencode.' )] [ValidateNotNullOrEmpty()] [Alias('ByteArray','Data')] [System.Byte[]]$Bytes, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='String to uuencode.' )] [ValidateNotNullOrEmpty()] [Alias('Plaintext','Text')] [System.String]$String, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to uuencode' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName','File')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$False, Position=1, HelpMessage='Output result to file instead of console.' )] [Parameter( ParameterSetName="ByteInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Do not format output string using header/footer and line breaks.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Unformatted, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning a string instead of a file, return a raw string instead of PSObject.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { [System.String]$OFS = "" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File If ($Raw) { Write-Warning "File output mode specified; Parameter '-Raw' will be ignored." } } Switch ($PSCmdlet.ParameterSetName) { "ByteInput" { [System.String]$UUName = "byteinput" [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,$Bytes) Break } "StringInput" { [System.String]$UUName = "stringinput" [System.IO.Stream]$InputStream = New-Object -TypeName System.IO.MemoryStream(,[System.Text.Encoding]::ASCII.GetBytes($String)) Break } "FileInput" { [System.String]$UUName = $InFile.Name.ToString() [System.IO.Stream]$InputStream = [System.IO.File]::Open($InFile.FullName,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::ReadWrite) Break } } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() [System.Object]$BinaryReader = New-Object -TypeName System.IO.BinaryReader($InputStream) [System.String]$UULine = [String]::Empty [System.Object]$UUOutput = New-Object -TypeName System.Text.StringBuilder If (-Not $Unformatted) { [void]$UUOutput.Append("begin 0744 $($UUName)`n") } Try { While ([System.Byte[]]$BytesRead = $BinaryReader.ReadBytes(3)) { [System.Boolean]$AtEnd = ($BinaryReader.BaseStream.Length -eq $BinaryReader.BaseStream.Position) [System.UInt16]$ByteLength = $BytesRead.Length If ($ByteLength -lt 3) { [System.Byte[]]$WorkingBytes = ,0x01 * 3 [System.Buffer]::BlockCopy($BytesRead,0,$WorkingBytes,0,$ByteLength) [System.Array]::Resize([ref]$BytesRead,3) [System.Buffer]::BlockCopy($WorkingBytes,0,$BytesRead,0,3) } [System.Char[]]$UUChars = ,0x00 * 4 [System.Char[]]$UUChunk = ,0x00 * 4 $UUChars[0] = [System.Text.Encoding]::ASCII.GetChars((($BytesRead[0] -band 0xFC) -shr 2) + 32)[0] $UUChars[1] = [System.Text.Encoding]::ASCII.GetChars(((($BytesRead[0] -band 0x03) -shl 4 ) -bor (($BytesRead[1] -band 0xF0) -shr 4 )) + 32)[0] $UUChars[2] = [System.Text.Encoding]::ASCII.GetChars(((($BytesRead[1] -band 0x0F) -shl 2 ) -bor (($BytesRead[2] -band 0xC0) -shr 6 )) + 32)[0] $UUChars[3] = [System.Text.Encoding]::ASCII.GetChars(($BytesRead[2] -band 0x3F) + 32)[0] [System.Array]::Copy($UUChars,$UUChunk,([Math]::Ceiling(($ByteLength / 3) * 4))) $UULine += $UUChunk If ($UULine.Length -eq 60) { Switch ($Unformatted) { $False { [void]$UUOutput.Append(([System.Text.Encoding]::ASCII.GetChars((($UULine.Length / 4) * 3) + 32))[0] + $UULine + "`n") [System.String]$UULine = [String]::Empty Break } $True { [void]$UUOutput.Append($UULine) [System.String]$UULine = [String]::Empty Break } } } If ($AtEnd) { [System.UInt16]$TrimEnd = 3 - $ByteLength Switch ($Unformatted) { $False { [void]$UUOutput.Append(([System.Text.Encoding]::ASCII.GetChars(((($UULine.Length / 4) * 3) - $TrimEnd) + 32))[0] + $UULine.SubString(0,($UULine.Length - $TrimEnd))) Break } $True { [void]$UUOutput.Append($UULine.SubString(0,($UULine.Length - $TrimEnd))) Break } } } } If (-Not $Unformatted) { [void]$UUOutput.Append("`n```nend") } [System.String]$UUResult = $UUOutput.ToString() $UUResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllLines($OutFile.FullName,$UUResult,(New-Object -TypeName System.Text.UTF8Encoding $False)) $UUResultObject = $OutFile } Else { If ($Raw) { $UUResultObject = $UUResult } Else { Add-Member -InputObject $UUResultObject -MemberType 'NoteProperty' -Name 'UUEncodedData' -Value $UUResult } } Return ($UUResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $BinaryReader.Close() $BinaryReader.Dispose() $InputStream.Close() $InputStream.Dispose() $Timer.Stop() [System.String]$TimeLapse = "UUencode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Function ConvertFrom-UUEncoding() { <# .SYNOPSIS A PowerShell function to convert UUencoded string data into a byte array or binary file. .DESCRIPTION Takes a string of UUencoded data and decodes into the original ASCII string or byte array. Input includes a UUencoded string or a file containing UUencoded data. The default input and output type if positional parameters are used is [System.String]. It is also possible to write a binary file using -OutFile. .PARAMETER UUEncodedString [System.String] object containing UUencoded data. Accepts pipeline input. .PARAMETER InFile [System.IO.Fileinfo] object containing the details of a file on disk to be loaded as a string object and UUdecoded; accepts pipeline input. .PARAMETER OutFile Optional [System.IO.Fileinfo] object containing the details of the new file to write to disk containing UUencoded data from the input file. Can be used with any input mode (Bytes, String, or InFile); file content will be raw decoded bytes. .PARAMETER OutBytes Return the decoded data as [System.Byte[]] to the console instead of the default ASCII string. .PARAMETER Auto If the input data contains the header row, automatically extrapolates the destination file name. If -Auto is specified in file output mode and the input data does not contain a header row or is not formatted and -AutoSave or -OutFile are not present, the function will return an error. .PARAMETER AutoSave When paired with -InFile, automatically create an output filename of in the form of the original file name plus the suffix specified after the parameter. For example, -AutoSave "UUDEC" will produce OutFile name <InFile>.UUDEC. Useful if piping the output of Get-ChildItem to the function to convert files as a bulk operation. Cannot be used with input methods other than -InFile. .PARAMETER Raw Optional switch parameter that when present will produce raw output instead of a PSObject. Depending on the parameters used, the return object could be of type [System.String] or [System.Byte[]]. .INPUTS Any single object, array or collection of strings or files (such as those from Get-ChildItem) can be piped to the function for processing from UUencoded data. Input data from file is always processed as ASCII text regardless of source file text encoding. .OUTPUTS In the case of direct string input, a [System.String] containing the decoded data as ASCII text is returned within a PSObject with a single member named UUDecodedData. If any input method is used with -OutFile or -InFile is used with -AutoSave, the output is a [System.IO.FileInfo] object containing details of a binary file with the decoded data as contents. If -OutBytes is specified, data is returned to the console as [System.Byte[]] wrapped in a PSObject. If -Raw is specified, the [System.String] or [System.Byte[]] is not wrapped in a PSObject and is returned directly. This means that output using -Raw cannot easily use the pipeline. The -Verbose parameter will return the function's total execution time. .EXAMPLE Pipe an object (string or array of strings, file info or array of file info objects) to the function for decoding from Base32: $MyObject | ConvertFrom-UUEncoding .EXAMPLE Pipe the results of a directory listing from Get-ChildItem and generate a new Base32 decoded file for each input file: Get-ChildItem C:\Text\*.UU | ConvertFrom-UUEncoding -AutoSave "UUDEC" .EXAMPLE Use file based input to decode an input file and output the results as new file C:\Text\file.txt: ConvertFrom-UUEncoding -File C:\Text\file.UU -OutFile C:\Text\file.txt .NOTES If the input data contains the header row, the output file name can be automatically extracted from the UUencoded data. If this row is absent and -Auto is specified, the function will return an error. This function is really geared more toward encoding / decoding files vs. string or pipeline input; it is really just for historical reference as UUencoding was superseded by Base64 encoding which is technically superior. #> [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact="High", DefaultParameterSetName="StringInput" )] [OutputType([System.Management.Automation.PSObject])] Param( [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True, Position=0, HelpMessage='Input uuencoded string.' )] [ValidateNotNullOrEmpty()] [Alias('String','Plaintext','Text','UUEncodedData')] [System.String]$UUEncodedString, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True,Position=0, HelpMessage='File to uudecode' )] [ValidateNotNullOrEmpty()] [Alias('Filename','FullName')] [ValidateScript({ If (-Not($_ | Test-Path -PathType Leaf)) { throw ("Invalid input file name specified.") }Else{ $True } })] [ValidateScript({ Try { $_.Open([System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::None).Close() $True } Catch { throw ("Input file is locked for reading or could not obtain read access.") } })] [System.IO.Fileinfo]$InFile, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, Position=1, HelpMessage='Path to output file when decoding in file mode.' )] [ValidateNotNullOrEmpty()] [System.IO.Fileinfo]$OutFile, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Output decoded data as raw bytes instead of ASCII text.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$OutBytes, [Parameter( ParameterSetName="ByteInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='Determine the output file name from the uuencoded data header; only applies to file mode. Can be mixed with -AutoSave or -OutFile when using pipeline to extract the file name if it exists, and rely on -AutoSave / -OutFile if it does not.' )] [Parameter( ParameterSetName="StringInput" )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Auto, [Parameter( ParameterSetName="FileInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When in file input mode, automatically select output file name using the specified suffix as the file extension; not valid with any other input mode (String or Bytes).' )] [ValidateNotNullOrEmpty()] [ValidateScript({ If (-Not(($_.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1))) { throw ("AutoSave suffix contains illegal characters.") } Else { $True } })] [System.String]$AutoSave, [Parameter( ParameterSetName="StringInput", ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, Mandatory=$False, HelpMessage='When returning to console, return a raw byte array instead of PSObject.' )] [Parameter( ParameterSetName="FileInput" )] [ValidateNotNullOrEmpty()] [Switch]$Raw ) BEGIN { If ($PSBoundParameters.ContainsKey("AutoSave") -and $PSCmdlet.ParameterSetName -ne "FileInput") { Write-Error "-AutoSave can only be used in file input mode." -ErrorAction Stop } [System.String]$NON_UU_Pattern = "[^\u0000-\u007F“”]" [System.String]$OFS = "" } PROCESS { If ($PSBoundParameters.ContainsKey('InFile') -and $PSBoundParameters.ContainsKey('AutoSave')) { $OutFile = ($InFile.FullName.ToString()) + ".$($AutoSave)" } Switch ($PSCmdlet.ParameterSetName) { "StringInput" { [System.Object]$InputStream = New-Object -TypeName System.IO.MemoryStream(,[System.Text.Encoding]::ASCII.GetBytes($UUEncodedString)) [System.IO.StreamReader]$StreamReader = New-Object -TypeName System.IO.StreamReader($InputStream) Break } "FileInput" { [System.Object]$InputStream = [System.IO.File]::Open($InFile.FullName,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::ReadWrite) [System.IO.StreamReader]$StreamReader = New-Object -TypeName System.IO.StreamReader($InputStream) Break } } [System.Boolean]$Unformatted = $False [System.Object]$OutputStream = New-Object -TypeName System.IO.MemoryStream [System.Object]$BinaryWriter = New-Object -TypeName System.IO.BinaryWriter($OutputStream) [System.Char[]]$UUHeaderProbe = ,0x00 * 5 Try { [void]$StreamReader.Read($UUHeaderProbe,0,5) If (($UUHeaderProbe -join "").ToLower() -ne "begin") { [System.Char[]]$UUProbe = ,0x00 * 65535 [System.UInt16]$UUProbeLength = $StreamReader.Read($UUProbe,0,65535) [System.String]$UUProbeLine = ($UUProbe -join "").Substring(0,$UUProbeLength) If ($UUProbeLine -match $NON_UU_Pattern) { Throw "Invalid UUencoded data encountered first 64KB of file - file may not be UUencoded." } $Unformatted = $True } $StreamReader.BaseStream.Position = 0 $StreamReader.DiscardBufferedData() If (-Not $Unformatted) { [System.String[]]$UUHeader = ($StreamReader.ReadLine()) -split " " } Else { [System.String[]]$UUHeader = [System.String]::Empty } If ($PSBoundParameters.ContainsKey('Auto') -And $Unformatted) { $StreamReader.Close() $StreamReader.Dispose() $BinaryWriter.Close() $BinaryWriter.Dispose() $OutputStream.Close() $OutputStream.Dispose() Write-Error "The -Auto parameter was used but the input stream does not appear to contain a header row. You will need to specify -OutFile or -AutoSave in order to produce file output." -ErrorAction Stop } ElseIf ($PSBoundParameters.ContainsKey('Auto') -And -Not $Unformatted -And $UUHeader[2]) { $OutFile = Join-Path (Get-Location).path $UUHeader[2] } If ($OutFile) { If ((Test-Path $OutFile -PathType Leaf) -and ($PSCmdlet.ShouldProcess($OutFile,'Overwrite'))) { Remove-Item $OutFile -Confirm:$False } If (Test-Path $OutFile -PathType Leaf) { Write-Error "Could not overwrite existing output file '$($Outfile)'" -ErrorAction Stop } $Null = New-Item -Path $OutFile -ItemType File } [System.Object]$Timer = [System.Diagnostics.Stopwatch]::StartNew() While ([System.Char[]]$UULine = $StreamReader.ReadLine()) { If (-Not $Unformatted) { If (($UULine -join "") -eq "end" -or $UULine[0] -eq "``") { Break } } If (($UULine -join "") -match $NON_UU_Pattern) { Throw "Invalid UUencode data encountered in input stream." } [System.Object]$ProcessStream = New-Object -TypeName System.IO.MemoryStream($UULine,0,$UULine.Length) [System.Object]$BinaryReader = New-Object -TypeName System.IO.BinaryReader($ProcessStream) If (-Not $Unformatted) { [void]$BinaryReader.ReadByte() } While ([System.Byte[]]$BytesRead = $BinaryReader.ReadBytes(4)) { [System.UInt16]$ByteLength = $BytesRead.Length If ($ByteLength -lt 4) { [System.Byte[]]$WorkingBytes = ,0x00 * 4 [System.Buffer]::BlockCopy($BytesRead,0,$WorkingBytes,0,$ByteLength) [System.Array]::Resize([ref]$BytesRead,4) [System.Buffer]::BlockCopy($WorkingBytes,0,$BytesRead,0,4) } [System.Byte[]]$UUBytes = ,0x00 * 3 [System.UInt16]$ByteLen = [Math]::Floor(($ByteLength * 3) / 4) [System.Byte[]]$BinChunk = ,0x00 * $ByteLen $UUBytes[0] = ((($BytesRead[0] - 32) -band 0x3F) -shl 2) -bor ((($BytesRead[1] - 32) -band 0x30) -shr 4) $UUBytes[1] = ((($BytesRead[1] - 32) -band 0x0F) -shl 4) -bor ((($BytesRead[2] - 32) -band 0x3C) -shr 2) $UUBytes[2] = ((($BytesRead[2] - 32) -band 0x03) -shl 6) -bor (($BytesRead[3] - 32) -band 0x3F) [System.Buffer]::BlockCopy($UUBytes,0,$BinChunk,0,$ByteLen) $BinaryWriter.Write($BinChunk) } } $ResultObject = New-Object -TypeName PSObject If ($OutFile) { [System.IO.File]::WriteAllBytes($OutFile,($OutputStream.ToArray())) $ResultObject = $OutFile } Else { If ($OutBytes -and $Raw) { $ResultObject = $OutputStream.ToArray() } ElseIf ($OutBytes) { Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'UUDecodedData' -Value $OutputStream.ToArray() } ElseIf ($Raw) { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString(($OutputStream.ToArray())) $ResultObject = $Results } Else { [System.String]$Results = [System.Text.Encoding]::ASCII.GetString(($OutputStream.ToArray())) Add-Member -InputObject $ResultObject -MemberType 'NoteProperty' -Name 'UUDecodedString' -Value $Results } } Return ($ResultObject) } Catch { Write-Error "Exception: $($_.Exception.Message)" Break } Finally { $BinaryWriter.Close() $BinaryWriter.Dispose() $InputStream.Close() $InputStream.Dispose() $OutputStream.Close() $OutputStream.Dispose() $StreamReader.Close() $StreamReader.Dispose() $Timer.Stop() [System.String]$TimeLapse = "UUdecode completed after $($Timer.Elapsed.Hours) hours, $($Timer.Elapsed.Minutes) minutes, $($Timer.Elapsed.Seconds) seconds, $($Timer.Elapsed.Milliseconds) milliseconds" Write-Verbose $TimeLapse } } } Export-ModuleMember -Function Get-RandomByteArray Export-ModuleMember -Function Get-CompressedByteArray Export-ModuleMember -Function Get-DecompressedByteArray Export-ModuleMember -Function ConvertTo-Ascii85 Export-ModuleMember -Function ConvertFrom-Ascii85 Export-ModuleMember -Function ConvertTo-Base16 Export-ModuleMember -Function ConvertFrom-Base16 Export-ModuleMember -Function ConvertTo-Base32 Export-ModuleMember -Function ConvertFrom-Base32 Export-ModuleMember -Function ConvertTo-Base64 Export-ModuleMember -Function ConvertFrom-Base64 Export-ModuleMember -Function ConvertTo-UUEncoding Export-ModuleMember -Function ConvertFrom-UUEncoding |