aboutsummaryrefslogtreecommitdiffstats
path: root/keyserver/curl-shim.h
blob: 9cec8406560197a5682f300c1a262fff4bc722e7 (plain)
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
/* curl-shim.h
 * Copyright (C) 2005, 2006 Free Software Foundation, Inc.
 *
 * This file is part of GNUPG.
 *
 * GNUPG is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GNUPG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
 * USA.
 */

#ifndef _CURL_SHIM_H_
#define _CURL_SHIM_H_

#include "http.h"

typedef enum
  {
    CURLE_OK=0,
    CURLE_UNSUPPORTED_PROTOCOL=1,
    CURLE_COULDNT_CONNECT=7,
    CURLE_FTP_COULDNT_RETR_FILE=19,
    CURLE_HTTP_RETURNED_ERROR=22,
    CURLE_WRITE_ERROR=23
  } CURLcode;

typedef enum
  {
    CURLOPT_URL,
    CURLOPT_USERPWD,
    CURLOPT_WRITEFUNCTION,
    CURLOPT_FILE,
    CURLOPT_ERRORBUFFER,
    CURLOPT_FOLLOWLOCATION,
    CURLOPT_MAXREDIRS,
    CURLOPT_STDERR,
    CURLOPT_VERBOSE,
    CURLOPT_SSL_VERIFYPEER,
    CURLOPT_PROXY,
    CURLOPT_CAINFO,
    CURLOPT_POST,
    CURLOPT_POSTFIELDS,
    CURLOPT_FAILONERROR
  } CURLoption;

typedef size_t (*write_func)(char *buffer,size_t size,
			     size_t nitems,void *outstream);

typedef struct
{
  char *url;
  char *auth;
  char *errorbuffer;
  char *proxy;
  write_func writer;
  void *file;
  char *postfields;
  unsigned int status;
  FILE *errors;
  struct
  {
    unsigned int post:1;
    unsigned int failonerror:1;
    unsigned int verbose:1;
  } flags;
  http_t hd;
} CURL;

typedef struct
{
  const char **protocols;
} curl_version_info_data; 

#define CURL_ERROR_SIZE 256
#define CURL_GLOBAL_DEFAULT 0
#define CURLVERSION_NOW 0

CURLcode curl_global_init(long flags);
void curl_global_cleanup(void);
CURL *curl_easy_init(void);
CURLcode curl_easy_setopt(CURL *curl,CURLoption option,...);
CURLcode curl_easy_perform(CURL *curl);
void curl_easy_cleanup(CURL *curl);
char *curl_escape(char *str,int len);
#define curl_free(x) free(x)
#define curl_version() "GnuPG curl-shim "VERSION
curl_version_info_data *curl_version_info(int type);

#endif /* !_CURL_SHIM_H_ */
' href='#n438'>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
#+TITLE: GNU Privacy Guard (GnuPG) Made Easy Python Bindings HOWTO (English)
#+AUTHOR: Ben McGinnes
#+LATEX_COMPILER: xelatex
#+LATEX_CLASS: article
#+LATEX_CLASS_OPTIONS: [12pt]
#+LATEX_HEADER: \usepackage{xltxtra}
#+LATEX_HEADER: \usepackage[margin=1in]{geometry}
#+LATEX_HEADER: \setmainfont[Ligatures={Common}]{Times New Roman}
#+LATEX_HEADER: \author{Ben McGinnes <ben@gnupg.org>}
#+HTML_HEAD_EXTRA: <link type="application/rss+xml" href="https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gpgme.git;a=rss;f=lang/python/docs/GPGMEpythonHOWTOen.org"/>


* Introduction
  :PROPERTIES:
  :CUSTOM_ID: intro
  :END:

| Version:        | 0.1.4                                    |
| GPGME Version:  | 1.12.0-draft                             |
| Author:         | [[https://gnupg.org/people/index.html#sec-1-5][Ben McGinnes]] <ben@gnupg.org>             |
| Author GPG Key: | DB4724E6FA4286C92B4E55C4321E4E2373590E5D |
| Language:       | Australian English, British English      |
| xml:lang:       | en-AU, en-GB, en                         |

This document provides basic instruction in how to use the GPGME
Python bindings to programmatically leverage the GPGME library.


** Python 2 versus Python 3
   :PROPERTIES:
   :CUSTOM_ID: py2-vs-py3
   :END:

Though the GPGME Python bindings themselves provide support for both
Python 2 and 3, the focus is unequivocally on Python 3 and
specifically from Python 3.4 and above.  As a consequence all the
examples and instructions in this guide use Python 3 code.

Much of it will work with Python 2, but much of it also deals with
Python 3 byte literals, particularly when reading and writing data.
Developers concentrating on Python 2.7, and possibly even 2.6, will
need to make the appropriate modifications to support the older string
and unicode types as opposed to bytes.

There are multiple reasons for concentrating on Python 3; some of
which relate to the immediate integration of these bindings, some of
which relate to longer term plans for both GPGME and the python
bindings and some of which relate to the impending EOL period for
Python 2.7.  Essentially, though, there is little value in tying the
bindings to a version of the language which is a dead end and the
advantages offered by Python 3 over Python 2 make handling the data
types with which GPGME deals considerably easier.


** Examples
   :PROPERTIES:
   :CUSTOM_ID: howto-python3-examples
   :END:

All of the examples found in this document can be found as Python 3
scripts in the =lang/python/examples/howto= directory.


** Unofficial Drafts
   :PROPERTIES:
   :CUSTOM_ID: unofficial-drafts
   :END:

In addition to shipping with each release of GPGME, there is a section
on locations to read or download [[#draft-editions][draft editions]] of this document from
at the end of it.  These are unofficial versions produced in between
major releases.


** What's New
   :PROPERTIES:
   :CUSTOM_ID: new-stuff
   :END:

The most obviously new point for those reading this guide is this
section on other new things, but that's hardly important.  Not given
all the other things which spurred the need for adding this section
and its subsections.

*** New in GPGME 1·12·0
    :PROPERTIES:
    :CUSTOM_ID: new-stuff-1-12-0
    :END:

There have been quite a number of additions to GPGME and the Python
bindings to it since the last release of GPGME with versions 1.11.0
and 1.11.1 in April, 2018.

The bullet points of new additiions are:

- an expanded section on [[#installation][installing]] and [[#snafu][troubleshooting]] the Python
  bindings.
- The release of Python 3.7.0; which appears to be working just fine
  with our bindings, in spite of intermittent reports of problems for
  many other Python projects with that new release.
- In order to fix some other issues, there are certain underlying
  functions which are more exposed through the [[#howto-get-context][gpg.Context()]], but
  ongoing documentation ought to clarify that or otherwise provide the
  best means of using the bindings.  Some additions to =gpg.core= and
  the =Context()=, however, were intended (see below).
- Continuing work in identifying and confirming the cause of
  oft-reported [[#snafu-runtime-not-funtime][problems installing the Python bindings on Windows]].
- GSOC: Google's Surreptitiously Ordered Conscription ... erm ... oh,
  right; Google's Summer of Code.  Though there were two hopeful
  candidates this year; only one ended up involved with the GnuPG
  Project directly, the other concentrated on an unrelated third party
  project with closer ties to one of the GNU/Linux distributions than
  to the GnuPG Project.  Thus the Python bindings benefited from GSOC
  participant Jacob Adams, who added the key_import function; building
  on prior work by Tobias Mueller.
- Several new methods functions were added to the gpg.Context(),
  including: [[#howto-import-key][key_import]], [[#howto-export-key][key_export]], [[#howto-export-public-key][key_export_minimal]] and
  [[#howto-export-secret-key][key_export_secret]].
- Importing and exporting examples include versions integrated with
  Marcel Fest's recently released [[https://github.com/Selfnet/hkp4py][HKP for Python]] module.  Some
  [[#hkp4py][additional notes on this module]] are included at the end of the HOWTO.
- Instructions for dealing with semi-walled garden implementations
  like ProtonMail are also included.  This is intended to make things
  a little easier when communicating with users of ProtonMail's
  services and should not be construed as an endorsement of said
  service.  The GnuPG Project neither favours, nor disfavours
  ProtonMail and the majority of this deals with interacting with the
  ProtonMail keyserver.
- Semi-formalised the location where [[#draft-editions][draft versions]] of this HOWTO may
  periodically be accessible.  This is both for the reference of
  others and testing the publishing of the document itself.
- Added a new section for [[#advanced-use][advanced or experimental use]].
- Began the advanced use cases with [[#cython][a section]] on using the module with
  [[http://cython.org/][Cython]].


* GPGME Concepts
  :PROPERTIES:
  :CUSTOM_ID: gpgme-concepts
  :END:


** A C API
   :PROPERTIES:
   :CUSTOM_ID: gpgme-c-api
   :END:

Unlike many modern APIs with which programmers will be more familiar
with these days, the GPGME API is a C API.  The API is intended for
use by C coders who would be able to access its features by including
the =gpgme.h= header file with their own C source code and then access
its functions just as they would any other C headers.

This is a very effective method of gaining complete access to the API
and in the most efficient manner possible.  It does, however, have the
drawback that it cannot be directly used by other languages without
some means of providing an interface to those languages.  This is
where the need for bindings in various languages stems.


** Python bindings
   :PROPERTIES:
   :CUSTOM_ID: gpgme-python-bindings
   :END:

The Python bindings for GPGME provide a higher level means of
accessing the complete feature set of GPGME itself.  It also provides
a more pythonic means of calling these API functions.

The bindings are generated dynamically with SWIG and the copy of
=gpgme.h= generated when GPGME is compiled.

This means that a version of the Python bindings is fundamentally tied
to the exact same version of GPGME used to generate that copy of
=gpgme.h=.


** Difference between the Python bindings and other GnuPG Python packages
   :PROPERTIES:
   :CUSTOM_ID: gpgme-python-bindings-diffs
   :END:

There have been numerous attempts to add GnuPG support to Python over
the years.  Some of the most well known are listed here, along with
what differentiates them.


*** The python-gnupg package maintained by Vinay Sajip
    :PROPERTIES:
    :CUSTOM_ID: diffs-python-gnupg
    :END:

This is arguably the most popular means of integrating GPG with
Python.  The package utilises the =subprocess= module to implement
wrappers for the =gpg= and =gpg2= executables normally invoked on the
command line (=gpg.exe= and =gpg2.exe= on Windows).

The popularity of this package stemmed from its ease of use and
capability in providing the most commonly required features.

Unfortunately it has been beset by a number of security issues in the
past; most of which stemmed from using unsafe methods of accessing the
command line via the =subprocess= calls.  While some effort has been
made over the last two to three years (as of 2018) to mitigate this,
particularly by no longer providing shell access through those
subprocess calls, the wrapper is still somewhat limited in the scope
of its GnuPG features coverage.

The python-gnupg package is available under the MIT license.


*** The gnupg package created and maintained by Isis Lovecruft
    :PROPERTIES:
    :CUSTOM_ID: diffs-isis-gnupg
    :END:

In 2015 Isis Lovecruft from the Tor Project forked and then
re-implemented the python-gnupg package as just gnupg.  This new
package also relied on subprocess to call the =gpg= or =gpg2=
binaries, but did so somewhat more securely.

The naming and version numbering selected for this package, however,
resulted in conflicts with the original python-gnupg and since its
functions were called in a different manner to python-gnupg, the
release of this package also resulted in a great deal of consternation
when people installed what they thought was an upgrade that
subsequently broke the code relying on it.

The gnupg package is available under the GNU General Public License
version 3.0 (or any later version).


*** The PyME package maintained by Martin Albrecht
    :PROPERTIES:
    :CUSTOM_ID: diffs-pyme
    :END:

This package is the origin of these bindings, though they are somewhat
different now.  For details of when and how the PyME package was
folded back into GPGME itself see the /Short History/ document[fn:1]
in the Python bindings =docs= directory.[fn:2]

The PyME package was first released in 2002 and was also the first
attempt to implement a low level binding to GPGME.  In doing so it
provided access to considerably more functionality than either the
=python-gnupg= or =gnupg= packages.

The PyME package is only available for Python 2.6 and 2.7.

Porting the PyME package to Python 3.4 in 2015 is what resulted in it
being folded into the GPGME project and the current bindings are the
end result of that effort.

The PyME package is available under the same dual licensing as GPGME
itself: the GNU General Public License version 2.0 (or any later
version) and the GNU Lesser General Public License version 2.1 (or any
later version).


* GPGME Python bindings installation
  :PROPERTIES:
  :CUSTOM_ID: gpgme-python-install
  :END:


** No PyPI
   :PROPERTIES:
   :CUSTOM_ID: do-not-use-pypi
   :END:

Most third-party Python packages and modules are available and
distributed through the Python Package Installer, known as PyPI.

Due to the nature of what these bindings are and how they work, it is
infeasible to install the GPGME Python bindings in the same way.

This is because the bindings use SWIG to dynamically generate C
bindings against =gpgme.h= and =gpgme.h= is generated from
=gpgme.h.in= at compile time when GPGME is built from source.  Thus to
include a package in PyPI which actually built correctly would require
either statically built libraries for every architecture bundled with
it or a full implementation of C for each architecture.

See the additional notes regarding [[#snafu-cffi][CFFI and SWIG]] at the end of this
section for further details.


** Requirements
   :PROPERTIES:
   :CUSTOM_ID: gpgme-python-requirements
   :END:

The GPGME Python bindings only have three requirements:

1. A suitable version of Python 2 or Python 3.  With Python 2 that
   means CPython 2.7 and with Python 3 that means CPython 3.4 or
   higher.
2. [[https://www.swig.org][SWIG]].
3. GPGME itself.  Which also means that all of GPGME's dependencies
   must be installed too.


*** Recommended Additions
   :PROPERTIES:
   :CUSTOM_ID: gpgme-python-recommendations
   :END:

Though none of the following are absolute requirements, they are all
recommended for use with the Python bindings.  In some cases these
recommendations refer to which version(s) of CPython to use the
bindings with, while others refer to third party modules which provide
a significant advantage in some way.

1. If possible, use Python 3 instead of 2.
2. Favour a more recent version of Python since even 3.4 is due to
   reach EOL soon.  In production systems and services, Python 3.6
   should be robust enough to be relied on.
3. If possible add the following Python modules which are not part of
   the standard library: [[http://docs.python-requests.org/en/latest/index.html][Requests]], [[http://cython.org/][Cython]] and [[https://github.com/Selfnet/hkp4py][hkp4py]].  Chances are
   quite high that at least the first one and maybe two of those will
   already be installed.


** Installation
   :PROPERTIES:
   :CUSTOM_ID: installation
   :END:

Installing the Python bindings is effectively achieved by compiling
and installing GPGME itself.

Once SWIG is installed with Python and all the dependencies for GPGME
are installed you only need to confirm that the version(s) of Python
you want the bindings installed for are in your =$PATH=.

By default GPGME will attempt to install the bindings for the most
recent or highest version number of Python 2 and Python 3 it detects
in =$PATH=.  It specifically checks for the =python= and =python3=
executables first and then checks for specific version numbers.

For Python 2 it checks for these executables in this order: =python=,
=python2= and =python2.7=.

For Python 3 it checks for these executables in this order: =python3=,
=python3.6=, =python3.5=, =python3.4= and =python3.7=.[fn:3]


*** Installing GPGME
    :PROPERTIES:
    :CUSTOM_ID: install-gpgme
    :END:

See the GPGME =README= file for details of how to install GPGME from
source.


** Known Issues
   :PROPERTIES:
   :CUSTOM_ID: snafu
   :END:

There are a few known issues with the current build process and the
Python bindings.  For the most part these are easily addressed should
they be encountered.


*** Breaking Builds
    :PROPERTIES:
    :CUSTOM_ID: snafu-a-swig-of-this-builds-character
    :END:

Occasionally when installing GPGME with the Python bindings included
it may be observed that the =make= portion of that process induces a
large very number of warnings and, eventually errors which end that
part of the build process.  Yet following that with =make check= and
=make install= appears to work seamlessly.

The cause of this is related to the way SWIG needs to be called to
dynamically generate the C bindings for GPGME in the first place.  So
the entire process will always produce =lang/python/python2-gpg/= and
=lang/python/python3-gpg/= directories.  These should contain the
build output generated during compilation, including the complete
bindings and module installed into =site-packages=.

Occasionally the errors in the early part or some other conflict
(e.g. not installing as */root/* or */su/*) may result in nothing
being installed to the relevant =site-packages= directory and the
build directory missing a lot of expected files.  Even when this
occurs, the solution is actually quite simple and will always work.

That solution is simply to run the following commands as either the
*root* user or prepended with =sudo -H=[fn:4] in the =lang/python/=
directory:

#+BEGIN_SRC shell
  /path/to/pythonX.Y setup.py build
  /path/to/pythonX.Y setup.py build
  /path/to/pythonX.Y setup.py install
#+END_SRC

Yes, the build command does need to be run twice.  Yes, you still need
to run the potentially failing or incomplete steps during the
=configure=, =make= and =make install= steps with installing GPGME.
This is because those steps generate a lot of essential files needed,
both by and in order to create, the bindings (including both the
=setup.py= and =gpgme.h= files).


**** IMPORTANT Note
     :PROPERTIES:
     :CUSTOM_ID: snafu-swig-build-note
     :END:

If specifying a selected number of languages to create bindings for,
try to leave Python last.  Currently the majority of the other
language bindings are also preceding Python of either version when
listed alphabetically and so that just happens by default currently.

If Python is set to precede one of the other languages then it is
possible that the errors described here may interrupt the build
process before generating bindings for those other languages.  In
these cases it may be preferable to configure all preferred language
bindings separately with alternative =configure= steps for GPGME using
the =--enable-languages=$LANGUAGE= option.


*** Reinstalling Responsibly
    :PROPERTIES:
    :CUSTOM_ID: snafu-lessons-for-the-lazy
    :END:

Regardless of whether you're installing for one version of Python or
several, there will come a point where reinstallation is required.
With most Python module installations, the installed files go into the
relevant site-packages directory and are then forgotten about.  Then
the module is upgraded, the new files are copied over the old and
that's the end of the matter.

While the same is true of these bindings, there have been intermittent
issues observed on some platforms which have benefited significantly
from removing all the previous installations of the bindings before
installing the updated versions.

Removing the previous version(s) is simply a matter of changing to the
relevant =site-packages= directory for the version of Python in
question and removing the =gpg/= directory and any accompanying
egg-info files for that module.

In most cases this will require root or administration privileges on
the system, but the same is true of installing the module in the first
place.


*** Multiple installations
    :PROPERTIES:
    :CUSTOM_ID: snafu-the-full-monty
    :END:

For a veriety of reasons it may be either necessary or just preferable
to install the bindings to alternative installed Python versions which
meet the requirements of these bindings.

On POSIX systems this will generally be most simply achieved by
running the manual installation commands (build, build, install) as
described in the previous section for each Python installation the
bindings need to be installed to.

As per the SWIG documentation: the compilers, libraries and runtime
used to build GPGME and the Python Bindings *must* match those used to
compile Python itself, including the version number(s) (at least going
by major version numbers and probably minor numbers too).

On most POSIX systems, including OS X, this will very likely be the
case in most, if not all, cases.


*** Won't Work With Windows
    :PROPERTIES:
    :CUSTOM_ID: snafu-runtime-not-funtime
    :END:

There are semi-regular reports of Windows users having considerable
difficulty in installing and using the Python bindings at all.  Very
often, possibly even always, these reports come from Cygwin users
and/or MinGW users and/or Msys2 users.  Though not all of them have
been confirmed, it appears that these reports have also come from
people who installed Python using the Windows installer files from the
[[https://python.org][Python website]] (i.e. mostly MSI installers, sometimes self-extracting
=.exe= files).

The Windows versions of Python are not built using Cygwin, MinGW or
Msys2; they're built using Microsoft Visual Studio.  Furthermore the
version used is /considerably/ more advanced than the version which
MinGW obtained a small number of files from many years ago in order to
be able to compile anything at all.  Not only that, but there are
changes to the version of Visual Studio between some micro releases,
though that is is particularly the case with Python 2.7, since it has
been kept around far longer than it should have been.

There are two theoretical solutions to this issue:

 1. Compile and install the GnuPG stack, including GPGME and the
    Python bibdings using the same version of Microsoft Visual Studio
    used by the Python Foundation to compile the version of Python
    installed.

    If there are multiple versions of Python then this will need to be
    done with each different version of Visual Studio used.

 2. Compile and install Python using the same tools used by choice,
    such as MinGW or Msys2.

Do *not* use the official Windows installer for Python unless
following the first method.

In this type of situation it may even be for the best to accept that
there are less limitations on permissive software than free software
and simply opt to use a recent version of the Community Edition of
Microsoft Visual Studio to compile and build all of it, no matter
what.

Investigations into the extent or the limitations of this issue are
ongoing.


*** CFFI is the Best™ and GPGME should use it instead of SWIG
    :PROPERTIES:
    :CUSTOM_ID: snafu-cffi
    :END:

There are many reasons for favouring [[https://cffi.readthedocs.io/en/latest/overview.html][CFFI]] and proponents of it are
quite happy to repeat these things as if all it would take to switch
from SWIG to CFFI is repeating that list as if it were a new concept.

The fact is that there are things which Python's CFFI implementation
cannot handle in the GPGME C code.  Beyond that there are features of
SWIG which are simply not available with CFFI at all.  SWIG generates
the bindings to Python using the =gpgme.h= file, but that file is not
a single version shipped with each release, it too is generated when
GPGME is compiled.

CFFI is currently unable to adapt to such a potentially mutable
codebase.  If there were some means of applying SWIG's dynamic code
generation to produce the Python/CFFI API modes of accessing the GPGME
libraries (or the source source code directly), but such a thing does
not exist yet either and it currently appears that work is needed in
at least one of CFFI's dependencies before any of this can be
addressed.

So if you're a massive fan of CFFI; that's great, but if you want this
project to switch to CFFI then rather than just insisting that it
should, I'd suggest you volunteer to bring CFFI up to the level this
project needs.

If you're actually seriously considering doing so, then I'd suggest
taking the =gpgme-tool.c= file in the GPGME =src/= directory and
getting that to work with any of the CFFI API methods (not the ABI
methods, they'll work with pretty much anything).  When you start
running into trouble with "ifdefs" then you'll know what sort of
things are lacking.  That doesn't even take into account the amount of
work saved via SWIG's code generation techniques either.


* Fundamentals
  :PROPERTIES:
  :CUSTOM_ID: howto-fund-a-mental
  :END:

Before we can get to the fun stuff, there are a few matters regarding
GPGME's design which hold true whether you're dealing with the C code
directly or these Python bindings.


** No REST
   :PROPERTIES:
   :CUSTOM_ID: no-rest-for-the-wicked
   :END:

The first part of which is or will be fairly blatantly obvious upon
viewing the first example, but it's worth reiterating anyway.  That
being that this API is /*not*/ a REST API.  Nor indeed could it ever
be one.

Most, if not all, Python programmers (and not just Python programmers)
know how easy it is to work with a RESTful API.  In fact they've
become so popular that many other APIs attempt to emulate REST-like
behaviour as much as they are able.  Right down to the use of JSON
formatted output to facilitate the use of their API without having to
retrain developers.

This API does not do that.  It would not be able to do that and also
provide access to the entire C API on which it's built.  It does,
however, provide a very pythonic interface on top of the direct
bindings and it's this pythonic layer that this HOWTO deals with.


** Context
   :PROPERTIES:
   :CUSTOM_ID: howto-get-context
   :END:

One of the reasons which prevents this API from being RESTful is that
most operations require more than one instruction to the API to
perform the task.  Sure, there are certain functions which can be
performed simultaneously, particularly if the result known or strongly
anticipated (e.g. selecting and encrypting to a key known to be in the
public keybox).

There are many more, however, which cannot be manipulated so readily:
they must be performed in a specific sequence and the result of one
operation has a direct bearing on the outcome of subsequent
operations.  Not merely by generating an error either.

When dealing with this type of persistent state on the web, full of
both the RESTful and REST-like, it's most commonly referred to as a
session.  In GPGME, however, it is called a context and every
operation type has one.


* Working with keys
  :PROPERTIES:
  :CUSTOM_ID: howto-keys
  :END:


** Key selection
   :PROPERTIES:
   :CUSTOM_ID: howto-keys-selection
   :END:

Selecting keys to encrypt to or to sign with will be a common
occurrence when working with GPGMe and the means available for doing
so are quite simple.

They do depend on utilising a Context; however once the data is
recorded in another variable, that Context does not need to be the
same one which subsequent operations are performed.

The easiest way to select a specific key is by searching for that
key's key ID or fingerprint, preferably the full fingerprint without
any spaces in it.  A long key ID will probably be okay, but is not
advised and short key IDs are already a problem with some being
generated to match specific patterns.  It does not matter whether the
pattern is upper or lower case.

So this is the best method:

#+BEGIN_SRC python -i
import gpg

k = gpg.Context().keylist(pattern="258E88DCBD3CD44D8E7AB43F6ECB6AF0DEADBEEF")
keys = list(k)
#+END_SRC

This is passable and very likely to be common:

#+BEGIN_SRC python -i
import gpg

k = gpg.Context().keylist(pattern="0x6ECB6AF0DEADBEEF")
keys = list(k)
#+END_SRC

And this is a really bad idea:

#+BEGIN_SRC python -i
import gpg

k = gpg.Context().keylist(pattern="0xDEADBEEF")
keys = list(k)
#+END_SRC

Alternatively it may be that the intention is to create a list of keys
which all match a particular search string.  For instance all the
addresses at a particular domain, like this:

#+BEGIN_SRC python -i
import gpg

ncsc = gpg.Context().keylist(pattern="ncsc.mil")
nsa = list(ncsc)
#+END_SRC


*** Counting keys
    :PROPERTIES:
    :CUSTOM_ID: howto-keys-counting
    :END:

Counting the number of keys in your public keybox (=pubring.kbx=), the
format which has superseded the old keyring format (=pubring.gpg= and
=secring.gpg=), or the number of secret keys is a very simple task.

#+BEGIN_SRC python -i
import gpg

c = gpg.Context()
seckeys = c.keylist(pattern=None, secret=True)
pubkeys = c.keylist(pattern=None, secret=False)

seclist = list(seckeys)
secnum = len(seclist)

publist = list(pubkeys)
pubnum = len(publist)

print("""
  Number of secret keys:  {0}
  Number of public keys:  {1}
""".format(secnum, pubnum))
#+END_SRC


** Get key
   :PROPERTIES:
   :CUSTOM_ID: howto-get-key
   :END:

An alternative method of getting a single key via its fingerprint is
available directly within a Context with =Context().get_key=.  This is
the preferred method of selecting a key in order to modify it, sign or
certify it and for obtaining relevant data about a single key as a
part of other functions; when verifying a signature made by that key,
for instance.

By default this method will select public keys, but it can select
secret keys as well.

This first example demonstrates selecting the current key of Werner
Koch, which is due to expire at the end of 2018:

#+BEGIN_SRC python -i
import gpg

fingerprint = "80615870F5BAD690333686D0F2AD85AC1E42B367"
key = gpg.Context().get_key(fingerprint)
#+END_SRC

Whereas this example demonstrates selecting the author's current key
with the =secret= key word argument set to =True=:

#+BEGIN_SRC python -i
import gpg

fingerprint = "DB4724E6FA4286C92B4E55C4321E4E2373590E5D"
key = gpg.Context().get_key(fingerprint, secret=True)
#+END_SRC

It is, of course, quite possible to select expired, disabled and
revoked keys with this function, but only to effectively display
information about those keys.

It is also possible to use both unicode or string literals and byte
literals with the fingerprint when getting a key in this way.


** Importing keys
   :PROPERTIES:
   :CUSTOM_ID: howto-import-key
   :END:

Importing keys is possible with the =key_import()= method and takes
one argument which is a bytes literal object containing either the
binary or ASCII armoured key data for one or more keys.

The following example retrieves one or more keys from the SKS
keyservers via the web using the requests module.  Since requests
returns the content as a bytes literal object, we can then use that
directly to import the resulting data into our keybox.

#+BEGIN_SRC python -i
import gpg
import os.path
import requests

c = gpg.Context()
url = "https://sks-keyservers.net/pks/lookup"
pattern = input("Enter the pattern to search for key or user IDs: ")
payload = {"op": "get", "search": pattern}

r = requests.get(url, verify=True, params=payload)
result = c.key_import(r.content)

if result is not None and hasattr(result, "considered") is False:
    print(result)
elif result is not None and hasattr(result, "considered") is True:
    num_keys = len(result.imports)
    new_revs = result.new_revocations
    new_sigs = result.new_signatures
    new_subs = result.new_sub_keys
    new_uids = result.new_user_ids
    new_scrt = result.secret_imported
    nochange = result.unchanged
    print("""
  The total number of keys considered for import was:  {0}

     Number of keys revoked:  {1}
   Number of new signatures:  {2}
      Number of new subkeys:  {3}
     Number of new user IDs:  {4}
  Number of new secret keys:  {5}
   Number of unchanged keys:  {6}

  The key IDs for all considered keys were:
""".format(num_keys, new_revs, new_sigs, new_subs, new_uids, new_scrt,
           nochange))
    for i in range(num_keys):
        print("{0}\n".format(result.imports[i].fpr))
else:
    pass
#+END_SRC

*NOTE:* When searching for a key ID of any length or a fingerprint
(without spaces), the SKS servers require the the leading =0x=
indicative of hexadecimal be included.  Also note that the old short
key IDs (e.g. =0xDEADBEEF=) should no longer be used due to the
relative ease by which such key IDs can be reproduced, as demonstrated
by the Evil32 Project in 2014 (which was subsequently exploited in
2016).


*** Working with ProtonMail
    :PROPERTIES:
    :CUSTOM_ID: import-protonmail
    :END:

Here is a variation on the example above which checks the constrained
ProtonMail keyserver for ProtonMail public keys.

#+BEGIN_SRC python -i
import gpg
import requests
import sys

print("""
This script searches the ProtonMail key server for the specified key and
imports it.
""")

c = gpg.Context(armor=True)
url = "https://api.protonmail.ch/pks/lookup"
ksearch = []

if len(sys.argv) >= 2:
    keyterm = sys.argv[1]
else:
    keyterm = input("Enter the key ID, UID or search string: ")

if keyterm.count("@") == 2 and keyterm.startswith("@") is True:
    ksearch.append(keyterm[1:])
    ksearch.append(keyterm[1:])
    ksearch.append(keyterm[1:])
elif keyterm.count("@") == 1 and keyterm.startswith("@") is True:
    ksearch.append("{0}@protonmail.com".format(keyterm[1:]))
    ksearch.append("{0}@protonmail.ch".format(keyterm[1:]))
    ksearch.append("{0}@pm.me".format(keyterm[1:]))
elif keyterm.count("@") == 0:
    ksearch.append("{0}@protonmail.com".format(keyterm))
    ksearch.append("{0}@protonmail.ch".format(keyterm))
    ksearch.append("{0}@pm.me".format(keyterm))
elif keyterm.count("@") == 2 and keyterm.startswith("@") is False:
    uidlist = keyterm.split("@")
    for uid in uidlist:
        ksearch.append("{0}@protonmail.com".format(uid))
        ksearch.append("{0}@protonmail.ch".format(uid))
        ksearch.append("{0}@pm.me".format(uid))
elif keyterm.count("@") > 2:
    uidlist = keyterm.split("@")
    for uid in uidlist:
        ksearch.append("{0}@protonmail.com".format(uid))
        ksearch.append("{0}@protonmail.ch".format(uid))
        ksearch.append("{0}@pm.me".format(uid))
else:
    ksearch.append(keyterm)

for k in ksearch:
    payload = {"op": "get", "search": k}
    try:
        r = requests.get(url, verify=True, params=payload)
        if r.ok is True:
            result = c.key_import(r.content)
        elif r.ok is False:
            result = r.content
    except Exception as e:
        result = None

    if result is not None and hasattr(result, "considered") is False:
        print("{0} for {1}".format(result.decode(), k))
    elif result is not None and hasattr(result, "considered") is True:
        num_keys = len(result.imports)
        new_revs = result.new_revocations
        new_sigs = result.new_signatures
        new_subs = result.new_sub_keys
        new_uids = result.new_user_ids
        new_scrt = result.secret_imported
        nochange = result.unchanged
        print("""
The total number of keys considered for import was:  {0}

With UIDs wholely or partially matching the following string:

        {1}

   Number of keys revoked:  {2}
 Number of new signatures:  {3}
    Number of new subkeys:  {4}
   Number of new user IDs:  {5}
Number of new secret keys:  {6}
 Number of unchanged keys:  {7}

The key IDs for all considered keys were:
""".format(num_keys, k, new_revs, new_sigs, new_subs, new_uids, new_scrt,
           nochange))
        for i in range(num_keys):
            print(result.imports[i].fpr)
        print("")
    elif result is None:
        print(e)
#+END_SRC

Both the above example, [[../examples/howto/pmkey-import.py][pmkey-import.py]], and a version which prompts
for an alternative GnuPG home directory, [[../examples/howto/pmkey-import-alt.py][pmkey-import-alt.py]], are
available with the other examples and are executable scripts.

Note that while the ProtonMail servers are based on the SKS servers,
their server is related more to their API and is not feature complete
by comparison to the servers in the SKS pool.  One notable difference
being that the ProtonMail server does not permit non ProtonMail users
to update their own keys, which could be a vector for attacking
ProtonMail users who may not receive a key's revocation if it had been
compromised.


*** Importing with HKP for Python
    :PROPERTIES:
    :CUSTOM_ID: import-hkp4py
    :END:

Performing the same tasks with the [[https://github.com/Selfnet/hkp4py][hkp4py module]] (available via PyPI)
is not too much different, but does provide a number of options of
benefit to end users.  Not least of which being the ability to perform
some checks on a key before importing it or not.  For instance it may
be the policy of a site or project to only import keys which have not
been revoked.  The hkp4py module permits such checks prior to the
importing of the keys found.

#+BEGIN_SRC python -i
import gpg
import hkp4py
import sys

c = gpg.Context()
server = hkp4py.KeyServer("hkps://hkps.pool.sks-keyservers.net")
results = []

if len(sys.argv) > 2:
    pattern = " ".join(sys.argv[1:])
elif len(sys.argv) == 2:
    pattern = sys.argv[1]
else:
    pattern = input("Enter the pattern to search for keys or user IDs: ")

try:
    keys = server.search(pattern)
    print("Found {0} key(s).".format(len(keys)))
except Exception as e:
    keys = []
    for logrus in pattern.split():
        if logrus.startswith("0x") is True:
            key = server.search(logrus)
        else:
            key = server.search("0x{0}".format(logrus))
        keys.append(key[0])
    print("Found {0} key(s).".format(len(keys)))

for key in keys:
    import_result = c.key_import(key.key_blob)
    results.append(import_result)

for result in results:
    if result is not None and hasattr(result, "considered") is False:
        print(result)
    elif result is not None and hasattr(result, "considered") is True:
        num_keys = len(result.imports)
        new_revs = result.new_revocations
        new_sigs = result.new_signatures
        new_subs = result.new_sub_keys
        new_uids = result.new_user_ids
        new_scrt = result.secret_imported
        nochange = result.unchanged
        print("""
The total number of keys considered for import was:  {0}

   Number of keys revoked:  {1}
 Number of new signatures:  {2}
    Number of new subkeys:  {3}
   Number of new user IDs:  {4}
Number of new secret keys:  {5}
 Number of unchanged keys:  {6}

The key IDs for all considered keys were:
""".format(num_keys, new_revs, new_sigs, new_subs, new_uids, new_scrt,
           nochange))
        for i in range(num_keys):
            print(result.imports[i].fpr)
        print("")
    else:
        pass
#+END_SRC

Since the hkp4py module handles multiple keys just as effectively as
one (=keys= is a list of responses per matching key), the example
above is able to do a little bit more with the returned data before
anything is actually imported.


*** Importing from ProtonMail with HKP for Python
    :PROPERTIES:
    :CUSTOM_ID: import-protonmail-hkp4py
    :END:

Though this can provide certain benefits even when working with
ProtonMail, the scope is somewhat constrained there due to the
limitations of the ProtonMail keyserver.

For instance, searching the SKS keyserver pool for the term "gnupg"
produces hundreds of results from any time the word appears in any
part of a user ID.  Performing the same search on the ProtonMail
keyserver returns zero results, even though there are at least two
test accounts which include it as part of the username.

The cause of this discrepancy is the deliberate configuration of that
server by ProtonMail to require an exact match of the full email
address of the ProtonMail user whose key is being requested.
Presumably this is intended to reduce breaches of privacy of their
users as an email address must already be known before a key for that
address can be obtained.


**** Import from ProtonMail via HKP for Python Example no. 1
     :PROPERTIES:
     :CUSTOM_ID: import-hkp4py-pm1
     :END:

The following script is avalable with the rest of the examples under
the somewhat less than original name, =pmkey-import-hkp.py=.

#+BEGIN_SRC python -i
import gpg
import hkp4py
import os.path
import sys

print("""
This script searches the ProtonMail key server for the specified key and
imports it.

Usage:  pmkey-import-hkp.py [search strings]
""")

c = gpg.Context(armor=True)
server = hkp4py.KeyServer("hkps://api.protonmail.ch")
keyterms = []
ksearch = []
allkeys = []
results = []
paradox = []
homeless = None

if len(sys.argv) > 2:
    keyterms = sys.argv[1:]
elif len(sys.argv) == 2:
    keyterm = sys.argv[1]
    keyterms.append(keyterm)
else:
    key_term = input("Enter the key ID, UID or search string: ")
    keyterms = key_term.split()

for keyterm in keyterms:
    if keyterm.count("@") == 2 and keyterm.startswith("@") is True:
        ksearch.append(keyterm[1:])
        ksearch.append(keyterm[1:])
        ksearch.append(keyterm[1:])
    elif keyterm.count("@") == 1 and keyterm.startswith("@") is True:
        ksearch.append("{0}@protonmail.com".format(keyterm[1:]))
        ksearch.append("{0}@protonmail.ch".format(keyterm[1:]))
        ksearch.append("{0}@pm.me".format(keyterm[1:]))
    elif keyterm.count("@") == 0:
        ksearch.append("{0}@protonmail.com".format(keyterm))
        ksearch.append("{0}@protonmail.ch".format(keyterm))
        ksearch.append("{0}@pm.me".format(keyterm))
    elif keyterm.count("@") == 2 and keyterm.startswith("@") is False:
        uidlist = keyterm.split("@")
        for uid in uidlist:
            ksearch.append("{0}@protonmail.com".format(uid))
            ksearch.append("{0}@protonmail.ch".format(uid))
            ksearch.append("{0}@pm.me".format(uid))
    elif keyterm.count("@") > 2:
        uidlist = keyterm.split("@")
        for uid in uidlist:
            ksearch.append("{0}@protonmail.com".format(uid))
            ksearch.append("{0}@protonmail.ch".format(uid))
            ksearch.append("{0}@pm.me".format(uid))
    else:
        ksearch.append(keyterm)

for k in ksearch:
    print("Checking for key for: {0}".format(k))
    try:
        keys = server.search(k)
        if isinstance(keys, list) is True:
            for key in keys:
                allkeys.append(key)
                try:
                    import_result = c.key_import(key.key_blob)
                except Exception as e:
                    import_result = c.key_import(key.key)
        else:
            paradox.append(keys)
            import_result = None
    except Exception as e:
        import_result = None
    results.append(import_result)

for result in results:
    if result is not None and hasattr(result, "considered") is False:
        print("{0} for {1}".format(result.decode(), k))
    elif result is not None and hasattr(result, "considered") is True:
        num_keys = len(result.imports)
        new_revs = result.new_revocations
        new_sigs = result.new_signatures
        new_subs = result.new_sub_keys
        new_uids = result.new_user_ids
        new_scrt = result.secret_imported
        nochange = result.unchanged
        print("""
The total number of keys considered for import was:  {0}

With UIDs wholely or partially matching the following string:

        {1}

   Number of keys revoked:  {2}
 Number of new signatures:  {3}
    Number of new subkeys:  {4}
   Number of new user IDs:  {5}
Number of new secret keys:  {6}
 Number of unchanged keys:  {7}

The key IDs for all considered keys were:
""".format(num_keys, k, new_revs, new_sigs, new_subs, new_uids, new_scrt,
           nochange))
        for i in range(num_keys):
            print(result.imports[i].fpr)
        print("")
    elif result is None:
        pass
#+END_SRC


**** Import from ProtonMail via HKP for Python Example no. 2
     :PROPERTIES:
     :CUSTOM_ID: import-hkp4py-pm2
     :END:

Like its counterpart above, this script can also be found with the
rest of the examples, by the name pmkey-import-hkp-alt.py.

With this script a modicum of effort has been made to treat anything
passed as a =homedir= which either does not exist or which is not a
directory, as also being a pssible user ID to check for.  It's not
guaranteed to pick up on all such cases, but it should cover most of
them.

#+BEGIN_SRC python -i
import gpg
import hkp4py
import os.path
import sys

print("""
This script searches the ProtonMail key server for the specified key and
imports it.  Optionally enables specifying a different GnuPG home directory.

Usage:  pmkey-import-hkp.py [homedir] [search string]
   or:  pmkey-import-hkp.py [search string]
""")

c = gpg.Context(armor=True)
server = hkp4py.KeyServer("hkps://api.protonmail.ch")
keyterms = []
ksearch = []
allkeys = []
results = []
paradox = []
homeless = None

if len(sys.argv) > 3:
    homedir = sys.argv[1]
    keyterms = sys.argv[2:]
elif len(sys.argv) == 3:
    homedir = sys.argv[1]
    keyterm = sys.argv[2]
    keyterms.append(keyterm)
elif len(sys.argv) == 2:
    homedir = ""
    keyterm = sys.argv[1]
    keyterms.append(keyterm)
else:
    keyterm = input("Enter the key ID, UID or search string: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")
    keyterms.append(keyterm)

if len(homedir) == 0:
    homedir = None
    homeless = False

if homedir is not None:
    if homedir.startswith("~"):
        if os.path.exists(os.path.expanduser(homedir)) is True:
            if os.path.isdir(os.path.expanduser(homedir)) is True:
                c.home_dir = os.path.realpath(os.path.expanduser(homedir))
            else:
                homeless = True
        else:
            homeless = True
    elif os.path.exists(os.path.realpath(homedir)) is True:
        if os.path.isdir(os.path.realpath(homedir)) is True:
            c.home_dir = os.path.realpath(homedir)
        else:
            homeless = True
    else:
        homeless = True

# First check to see if the homedir really is a homedir and if not, treat it as
# a search string.
if homeless is True:
    keyterms.append(homedir)
    c.home_dir = None
else:
    pass

for keyterm in keyterms:
    if keyterm.count("@") == 2 and keyterm.startswith("@") is True:
        ksearch.append(keyterm[1:])
        ksearch.append(keyterm[1:])
        ksearch.append(keyterm[1:])
    elif keyterm.count("@") == 1 and keyterm.startswith("@") is True:
        ksearch.append("{0}@protonmail.com".format(keyterm[1:]))
        ksearch.append("{0}@protonmail.ch".format(keyterm[1:]))
        ksearch.append("{0}@pm.me".format(keyterm[1:]))
    elif keyterm.count("@") == 0:
        ksearch.append("{0}@protonmail.com".format(keyterm))
        ksearch.append("{0}@protonmail.ch".format(keyterm))
        ksearch.append("{0}@pm.me".format(keyterm))
    elif keyterm.count("@") == 2 and keyterm.startswith("@") is False:
        uidlist = keyterm.split("@")
        for uid in uidlist:
            ksearch.append("{0}@protonmail.com".format(uid))
            ksearch.append("{0}@protonmail.ch".format(uid))
            ksearch.append("{0}@pm.me".format(uid))
    elif keyterm.count("@") > 2:
        uidlist = keyterm.split("@")
        for uid in uidlist:
            ksearch.append("{0}@protonmail.com".format(uid))
            ksearch.append("{0}@protonmail.ch".format(uid))
            ksearch.append("{0}@pm.me".format(uid))
    else:
        ksearch.append(keyterm)

for k in ksearch:
    print("Checking for key for: {0}".format(k))
    try:
        keys = server.search(k)
        if isinstance(keys, list) is True:
            for key in keys:
                allkeys.append(key)
                try:
                    import_result = c.key_import(key.key_blob)
                except Exception as e:
                    import_result = c.key_import(key.key)
        else:
            paradox.append(keys)
            import_result = None
    except Exception as e:
        import_result = None
    results.append(import_result)

for result in results:
    if result is not None and hasattr(result, "considered") is False:
        print("{0} for {1}".format(result.decode(), k))
    elif result is not None and hasattr(result, "considered") is True:
        num_keys = len(result.imports)
        new_revs = result.new_revocations
        new_sigs = result.new_signatures
        new_subs = result.new_sub_keys
        new_uids = result.new_user_ids
        new_scrt = result.secret_imported
        nochange = result.unchanged
        print("""
The total number of keys considered for import was:  {0}

With UIDs wholely or partially matching the following string:

        {1}

   Number of keys revoked:  {2}
 Number of new signatures:  {3}
    Number of new subkeys:  {4}
   Number of new user IDs:  {5}
Number of new secret keys:  {6}
 Number of unchanged keys:  {7}

The key IDs for all considered keys were:
""".format(num_keys, k, new_revs, new_sigs, new_subs, new_uids, new_scrt,
           nochange))
        for i in range(num_keys):
            print(result.imports[i].fpr)
        print("")
    elif result is None:
        pass
#+END_SRC


** Exporting keys
   :PROPERTIES:
   :CUSTOM_ID: howto-export-key
   :END:

Exporting keys remains a reasonably simple task, but has been
separated into three different functions for the OpenPGP cryptographic
engine.  Two of those functions are for exporting public keys and the
third is for exporting secret keys.


*** Exporting public keys
    :PROPERTIES:
    :CUSTOM_ID: howto-export-public-key
    :END:

There are two methods of exporting public keys, both of which are very
similar to the other.  The default method, =key_export()=, will export
a public key or keys matching a specified pattern as normal.  The
alternative, the =key_export_minimal()= method, will do the same thing
except producing a minimised output with extra signatures and third
party signatures or certifications removed.

#+BEGIN_SRC python -i
import gpg
import os.path
import sys

print("""
This script exports one or more public keys.
""")

c = gpg.Context(armor=True)

if len(sys.argv) >= 4:
    keyfile = sys.argv[1]
    logrus = sys.argv[2]
    homedir = sys.argv[3]
elif len(sys.argv) == 3:
    keyfile = sys.argv[1]
    logrus = sys.argv[2]
    homedir = input("Enter the GPG configuration directory path (optional): ")
elif len(sys.argv) == 2:
    keyfile = sys.argv[1]
    logrus = input("Enter the UID matching the key(s) to export: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")
else:
    keyfile = input("Enter the path and filename to save the secret key to: ")
    logrus = input("Enter the UID matching the key(s) to export: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")

if homedir.startswith("~"):
    if os.path.exists(os.path.expanduser(homedir)) is True:
        c.home_dir = os.path.expanduser(homedir)
    else:
        pass
elif os.path.exists(homedir) is True:
    c.home_dir = homedir
else:
    pass

try:
    result = c.key_export(pattern=logrus)
except:
    result = c.key_export(pattern=None)

if result is not None:
    with open(keyfile, "wb") as f:
        f.write(result)
else:
    pass
#+END_SRC

It is important to note that the result will only return =None= when a
pattern has been entered for =logrus=, but it has not matched any
keys. When the search pattern itself is set to =None= this triggers
the exporting of the entire public keybox.

#+BEGIN_SRC python -i
import gpg
import os.path
import sys

print("""
This script exports one or more public keys in minimised form.
""")

c = gpg.Context(armor=True)

if len(sys.argv) >= 4:
    keyfile = sys.argv[1]
    logrus = sys.argv[2]
    homedir = sys.argv[3]
elif len(sys.argv) == 3:
    keyfile = sys.argv[1]
    logrus = sys.argv[2]
    homedir = input("Enter the GPG configuration directory path (optional): ")
elif len(sys.argv) == 2:
    keyfile = sys.argv[1]
    logrus = input("Enter the UID matching the key(s) to export: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")
else:
    keyfile = input("Enter the path and filename to save the secret key to: ")
    logrus = input("Enter the UID matching the key(s) to export: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")

if homedir.startswith("~"):
    if os.path.exists(os.path.expanduser(homedir)) is True:
        c.home_dir = os.path.expanduser(homedir)
    else:
        pass
elif os.path.exists(homedir) is True:
    c.home_dir = homedir
else:
    pass

try:
    result = c.key_export_minimal(pattern=logrus)
except:
    result = c.key_export_minimal(pattern=None)

if result is not None:
    with open(keyfile, "wb") as f:
        f.write(result)
else:
    pass
#+END_SRC


*** Exporting secret keys
    :PROPERTIES:
    :CUSTOM_ID: howto-export-secret-key
    :END:

Exporting secret keys is, functionally, very similar to exporting
public keys; save for the invocation of =pinentry= via =gpg-agent= in
order to securely enter the key's passphrase and authorise the export.

The following example exports the secret key to a file which is then
set with the same permissions as the output files created by the
command line secret key export options.

#+BEGIN_SRC python -i
import gpg
import os
import os.path
import sys

print("""
This script exports one or more secret keys.

The gpg-agent and pinentry are invoked to authorise the export.
""")

c = gpg.Context(armor=True)

if len(sys.argv) >= 4:
    keyfile = sys.argv[1]
    logrus = sys.argv[2]
    homedir = sys.argv[3]
elif len(sys.argv) == 3:
    keyfile = sys.argv[1]
    logrus = sys.argv[2]
    homedir = input("Enter the GPG configuration directory path (optional): ")
elif len(sys.argv) == 2:
    keyfile = sys.argv[1]
    logrus = input("Enter the UID matching the secret key(s) to export: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")
else:
    keyfile = input("Enter the path and filename to save the secret key to: ")
    logrus = input("Enter the UID matching the secret key(s) to export: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")

if len(homedir) == 0:
    homedir = None
elif homedir.startswith("~"):
    userdir = os.path.expanduser(homedir)
    if os.path.exists(userdir) is True:
        homedir = os.path.realpath(userdir)
    else:
        homedir = None
else:
    homedir = os.path.realpath(homedir)

if os.path.exists(homedir) is False:
    homedir = None
else:
    if os.path.isdir(homedir) is False:
        homedir = None
    else:
        pass

if homedir is not None:
    c.home_dir = homedir
else:
    pass

try:
    result = c.key_export_secret(pattern=logrus)
except:
    result = c.key_export_secret(pattern=None)

if result is not None:
    with open(keyfile, "wb") as f:
        f.write(result)
    os.chmod(keyfile, 0o600)
else:
    pass
#+END_SRC

Alternatively the approach of the following script can be used.  This
longer example saves the exported secret key(s) in files in the GnuPG
home directory, in addition to setting the file permissions as only
readable and writable by the user.  It also exports the secret key(s)
twice in order to output both GPG binary (=.gpg=) and ASCII armoured
(=.asc=) files.

#+BEGIN_SRC python -i
import gpg
import os
import os.path
import subprocess
import sys

print("""
This script exports one or more secret keys as both ASCII armored and binary
file formats, saved in files within the user's GPG home directory.

The gpg-agent and pinentry are invoked to authorise the export.
""")

if sys.platform == "win32":
    gpgconfcmd = "gpgconf.exe --list-dirs homedir"
else:
    gpgconfcmd = "gpgconf --list-dirs homedir"

a = gpg.Context(armor=True)
b = gpg.Context()
c = gpg.Context()

if len(sys.argv) >= 4:
    keyfile = sys.argv[1]
    logrus = sys.argv[2]
    homedir = sys.argv[3]
elif len(sys.argv) == 3:
    keyfile = sys.argv[1]
    logrus = sys.argv[2]
    homedir = input("Enter the GPG configuration directory path (optional): ")
elif len(sys.argv) == 2:
    keyfile = sys.argv[1]
    logrus = input("Enter the UID matching the secret key(s) to export: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")
else:
    keyfile = input("Enter the filename to save the secret key to: ")
    logrus = input("Enter the UID matching the secret key(s) to export: ")
    homedir = input("Enter the GPG configuration directory path (optional): ")

if len(homedir) == 0:
    homedir = None
elif homedir.startswith("~"):
    userdir = os.path.expanduser(homedir)
    if os.path.exists(userdir) is True:
        homedir = os.path.realpath(userdir)
    else:
        homedir = None
else:
    homedir = os.path.realpath(homedir)

if os.path.exists(homedir) is False:
    homedir = None
else:
    if os.path.isdir(homedir) is False:
        homedir = None
    else:
        pass

if homedir is not None:
    c.home_dir = homedir
else:
    pass

if c.home_dir is not None:
    if c.home_dir.endswith("/"):
        gpgfile = "{0}{1}.gpg".format(c.home_dir, keyfile)
        ascfile = "{0}{1}.asc".format(c.home_dir, keyfile)
    else:
        gpgfile = "{0}/{1}.gpg".format(c.home_dir, keyfile)
        ascfile = "{0}/{1}.asc".format(c.home_dir, keyfile)
else:
    if os.path.exists(os.environ["GNUPGHOME"]) is True:
        hd = os.environ["GNUPGHOME"]
    else:
        try:
            hd = subprocess.getoutput(gpgconfcmd)
        except:
            process = subprocess.Popen(gpgconfcmd.split(),
                                       stdout=subprocess.PIPE)
            procom = process.communicate()
            if sys.version_info[0] == 2:
                hd = procom[0].strip()
            else:
                hd = procom[0].decode().strip()
    gpgfile = "{0}/{1}.gpg".format(hd, keyfile)
    ascfile = "{0}/{1}.asc".format(hd, keyfile)

try:
    a_result = a.key_export_secret(pattern=logrus)
    b_result = b.key_export_secret(pattern=logrus)
except:
    a_result = a.key_export_secret(pattern=None)
    b_result = b.key_export_secret(pattern=None)

if a_result is not None:
    with open(ascfile, "wb") as f:
        f.write(a_result)
    os.chmod(ascfile, 0o600)
else:
    pass

if b_result is not None:
    with open(gpgfile, "wb") as f:
        f.write(b_result)
    os.chmod(gpgfile, 0o600)
else:
    pass
#+END_SRC


*** Sending public keys to the SKS Keyservers
    :PROPERTIES:
    :CUSTOM_ID: howto-send-public-key
    :END:

As with the previous section on importing keys, the =hkp4py= module
adds another option with exporting keys in order to send them to the
public keyservers.

The following example demonstrates how this may be done.

#+BEGIN_SRC python -i
import gpg
import hkp4py
import os.path
import sys

print("""
This script sends one or more public keys to the SKS keyservers and is
essentially a slight variation on the export-key.py script.
""")

c = gpg.Context(armor=True)
server = hkp4py.KeyServer("hkps://hkps.pool.sks-keyservers.net")

if len(sys.argv) > 2:
    logrus = " ".join(sys.argv[1:])
elif len(sys.argv) == 2:
    logrus = sys.argv[1]
else:
    logrus = input("Enter the UID matching the key(s) to send: ")

if len(logrus) > 0:
    try:
        export_result = c.key_export(pattern=logrus)
    except Exception as e:
        print(e)
        export_result = None
else:
    export_result = c.key_export(pattern=None)

if export_result is not None:
    try:
        try:
            send_result = server.add(export_result)
        except:
            send_result = server.add(export_result.decode())
        if send_result is not None:
            print(send_result)
        else:
            pass
    except Exception as e:
        print(e)
else:
    pass
#+END_SRC

An expanded version of this script with additional functions for
specifying an alternative homedir location is in the examples
directory as =send-key-to-keyserver.py=.

The =hkp4py= module appears to handle both string and byte literal text
data equally well, but the GPGME bindings deal primarily with byte
literal data only and so this script sends in that format first, then
tries the string literal form.


* Basic Functions
  :PROPERTIES:
  :CUSTOM_ID: howto-the-basics
  :END:

The most frequently called features of any cryptographic library will
be the most fundamental tasks for encryption software.  In this
section we will look at how to programmatically encrypt data, decrypt
it, sign it and verify signatures.


** Encryption
   :PROPERTIES:
   :CUSTOM_ID: howto-basic-encryption
   :END:

Encrypting is very straight forward.  In the first example below the
message, =text=, is encrypted to a single recipient's key.  In the
second example the message will be encrypted to multiple recipients.


*** Encrypting to one key
    :PROPERTIES:
    :CUSTOM_ID: howto-basic-encryption-single
    :END:

Once the the Context is set the main issues with encrypting data is
essentially reduced to key selection and the keyword arguments
specified in the =gpg.Context().encrypt()= method.

Those keyword arguments are: =recipients=, a list of keys encrypted to
(covered in greater detail in the following section); =sign=, whether
or not to sign the plaintext data, see subsequent sections on signing
and verifying signatures below (defaults to =True=); =sink=, to write
results or partial results to a secure sink instead of returning it
(defaults to =None=); =passphrase=, only used when utilising symmetric
encryption (defaults to =None=); =always_trust=, used to override the
trust model settings for recipient keys (defaults to =False=);
=add_encrypt_to=, utilises any preconfigured =encrypt-to= or
=default-key= settings in the user's =gpg.conf= file (defaults to
=False=); =prepare=, prepare for encryption (defaults to =False=);
=expect_sign=, prepare for signing (defaults to =False=); =compress=,
compresses the plaintext prior to encryption (defaults to =True=).

#+BEGIN_SRC python -i
import gpg

a_key = "0x12345678DEADBEEF"
text = b"""Some text to test with.

Since the text in this case must be bytes, it is most likely that