aboutsummaryrefslogtreecommitdiffstats
path: root/lang/python/examples
diff options
context:
space:
mode:
Diffstat (limited to 'lang/python/examples')
-rw-r--r--lang/python/examples/assuan.py4
-rw-r--r--lang/python/examples/decryption-filter.py7
-rwxr-xr-xlang/python/examples/delkey.py3
-rwxr-xr-xlang/python/examples/exportimport.py3
-rwxr-xr-xlang/python/examples/genkey.py3
-rwxr-xr-xlang/python/examples/howto/decrypt-file.py4
-rwxr-xr-xlang/python/examples/howto/encrypt-file.py10
-rwxr-xr-xlang/python/examples/howto/encrypt-sign-file.py10
-rwxr-xr-xlang/python/examples/howto/encrypt-to-group-gullible.py81
-rwxr-xr-xlang/python/examples/howto/encrypt-to-group-trustno1.py90
-rwxr-xr-xlang/python/examples/howto/encrypt-to-group.py91
-rwxr-xr-xlang/python/examples/howto/export-key.py73
-rwxr-xr-xlang/python/examples/howto/export-minimised-key.py73
-rwxr-xr-xlang/python/examples/howto/export-secret-key.py77
-rwxr-xr-xlang/python/examples/howto/export-secret-keys.py110
-rw-r--r--lang/python/examples/howto/groups.py18
-rwxr-xr-xlang/python/examples/howto/import-key.py93
-rwxr-xr-xlang/python/examples/howto/import-keys.py70
-rwxr-xr-xlang/python/examples/howto/mutt-groups.py64
-rwxr-xr-xlang/python/examples/howto/pmkey-import-alt.py132
-rwxr-xr-xlang/python/examples/howto/pmkey-import.py116
-rwxr-xr-xlang/python/examples/howto/symcrypt-file.py63
-rwxr-xr-xlang/python/examples/howto/temp-homedir-config.py31
-rw-r--r--lang/python/examples/inter-edit.py12
-rwxr-xr-xlang/python/examples/low_level-encrypt_to_all.py13
-rwxr-xr-xlang/python/examples/sign.py3
-rwxr-xr-xlang/python/examples/signverify.py3
-rwxr-xr-xlang/python/examples/simple.py7
-rw-r--r--lang/python/examples/testCMSgetkey.py4
-rwxr-xr-xlang/python/examples/verifydetails.py22
30 files changed, 1226 insertions, 64 deletions
diff --git a/lang/python/examples/assuan.py b/lang/python/examples/assuan.py
index dd42ad40..6784c9eb 100644
--- a/lang/python/examples/assuan.py
+++ b/lang/python/examples/assuan.py
@@ -14,14 +14,14 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
-
"""Demonstrate the use of the Assuan protocol engine"""
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import gpg
+del absolute_import, print_function, unicode_literals
+
with gpg.Context(protocol=gpg.constants.protocol.ASSUAN) as c:
# Invoke the pinentry to get a confirmation.
err = c.assuan_transact(['GET_CONFIRMATION', 'Hello there'])
diff --git a/lang/python/examples/decryption-filter.py b/lang/python/examples/decryption-filter.py
index 987dfd13..4d99330b 100644
--- a/lang/python/examples/decryption-filter.py
+++ b/lang/python/examples/decryption-filter.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
#
-# Copyright (C) 2016 g10 Code GmbH
+# Copyright (C) 2016, 2018 g10 Code GmbH
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -14,7 +14,6 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
-
"""A decryption filter
This demonstrates decryption using gpg3 in three lines of code. To
@@ -25,8 +24,10 @@ be used like this:
"""
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import gpg
+
+del absolute_import, print_function, unicode_literals
+
gpg.Context().decrypt(sys.stdin, sink=sys.stdout)
diff --git a/lang/python/examples/delkey.py b/lang/python/examples/delkey.py
index 12510f3e..30b3145a 100755
--- a/lang/python/examples/delkey.py
+++ b/lang/python/examples/delkey.py
@@ -20,10 +20,11 @@
# It deletes keys for [email protected] generated by genkey.py script
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import gpg
+del absolute_import, print_function, unicode_literals
+
with gpg.Context() as c:
# Note: We must not modify the key store during iteration,
# therefore, we explicitly make a list.
diff --git a/lang/python/examples/exportimport.py b/lang/python/examples/exportimport.py
index d84a01c3..36ced579 100755
--- a/lang/python/examples/exportimport.py
+++ b/lang/python/examples/exportimport.py
@@ -20,12 +20,13 @@
# It uses keys for [email protected] generated by genkey.py script
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import os
import gpg
+del absolute_import, print_function, unicode_literals
+
with gpg.Context(armor=True) as c, gpg.Data() as expkey:
diff --git a/lang/python/examples/genkey.py b/lang/python/examples/genkey.py
index a043500e..710a530a 100755
--- a/lang/python/examples/genkey.py
+++ b/lang/python/examples/genkey.py
@@ -18,10 +18,11 @@
# along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import gpg
+del absolute_import, print_function, unicode_literals
+
# This is the example from the GPGME manual.
parms = """<GnupgKeyParms format="internal">
diff --git a/lang/python/examples/howto/decrypt-file.py b/lang/python/examples/howto/decrypt-file.py
index b38acc79..2fe37f27 100755
--- a/lang/python/examples/howto/decrypt-file.py
+++ b/lang/python/examples/howto/decrypt-file.py
@@ -32,10 +32,10 @@ if len(sys.argv) == 3:
newfile = sys.argv[2]
elif len(sys.argv) == 2:
ciphertext = sys.argv[1]
- newfile = input("Enter path and filename of file to save decrypted data to: ")
+ newfile = input("Enter path and filename to save decrypted data to: ")
else:
ciphertext = input("Enter path and filename of encrypted file: ")
- newfile = input("Enter path and filename of file to save decrypted data to: ")
+ newfile = input("Enter path and filename to save decrypted data to: ")
with open(ciphertext, "rb") as cfile:
try:
diff --git a/lang/python/examples/howto/encrypt-file.py b/lang/python/examples/howto/encrypt-file.py
index ad4e1cef..7c84a6f9 100755
--- a/lang/python/examples/howto/encrypt-file.py
+++ b/lang/python/examples/howto/encrypt-file.py
@@ -3,6 +3,9 @@
from __future__ import absolute_import, division, unicode_literals
+import gpg
+import sys
+
# Copyright (C) 2018 Ben McGinnes <[email protected]>
#
# This program is free software; you can redistribute it and/or modify it under
@@ -24,9 +27,6 @@ from __future__ import absolute_import, division, unicode_literals
# Lesser General Public along with this program; if not, see
# <http://www.gnu.org/licenses/>.
-import gpg
-import sys
-
"""
Encrypts a file to a specified key. If entering both the key and the filename
on the command line, the key must be entered first.
@@ -55,7 +55,7 @@ with open(filename, "rb") as f:
with gpg.Context(armor=True) as ca:
try:
ciphertext, result, sign_result = ca.encrypt(text, recipients=rkey,
- sign=False)
+ sign=False)
with open("{0}.asc".format(filename), "wb") as fa:
fa.write(ciphertext)
except gpg.errors.InvalidRecipients as e:
@@ -64,7 +64,7 @@ with gpg.Context(armor=True) as ca:
with gpg.Context() as cg:
try:
ciphertext, result, sign_result = cg.encrypt(text, recipients=rkey,
- sign=False)
+ sign=False)
with open("{0}.gpg".format(filename), "wb") as fg:
fg.write(ciphertext)
except gpg.errors.InvalidRecipients as e:
diff --git a/lang/python/examples/howto/encrypt-sign-file.py b/lang/python/examples/howto/encrypt-sign-file.py
index 41aaac86..a08176b7 100755
--- a/lang/python/examples/howto/encrypt-sign-file.py
+++ b/lang/python/examples/howto/encrypt-sign-file.py
@@ -3,6 +3,9 @@
from __future__ import absolute_import, division, unicode_literals
+import gpg
+import sys
+
# Copyright (C) 2018 Ben McGinnes <[email protected]>
#
# This program is free software; you can redistribute it and/or modify it under
@@ -24,9 +27,6 @@ from __future__ import absolute_import, division, unicode_literals
# Lesser General Public along with this program; if not, see
# <http://www.gnu.org/licenses/>.
-import gpg
-import sys
-
"""
Signs and encrypts a file to a specified key. If entering both the key and the
filename on the command line, the key must be entered first.
@@ -58,13 +58,13 @@ with open(filename, "rb") as f:
with gpg.Context(armor=True) as ca:
ciphertext, result, sign_result = ca.encrypt(text, recipients=rkey,
always_trust=True,
- add_encrypt_to=True)
+ add_encrypt_to=True)
with open("{0}.asc".format(filename), "wb") as fa:
fa.write(ciphertext)
with gpg.Context() as cg:
ciphertext, result, sign_result = cg.encrypt(text, recipients=rkey,
always_trust=True,
- add_encrypt_to=True)
+ add_encrypt_to=True)
with open("{0}.gpg".format(filename), "wb") as fg:
fg.write(ciphertext)
diff --git a/lang/python/examples/howto/encrypt-to-group-gullible.py b/lang/python/examples/howto/encrypt-to-group-gullible.py
new file mode 100755
index 00000000..c96e8294
--- /dev/null
+++ b/lang/python/examples/howto/encrypt-to-group-gullible.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import sys
+from groups import group_lists
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+"""
+Uses the groups module to encrypt to multiple recipients.
+
+"""
+
+c = gpg.Context(armor=True)
+
+if len(sys.argv) > 3:
+ group_id = sys.argv[1]
+ filepath = sys.argv[2:]
+elif len(sys.argv) == 3:
+ group_id = sys.argv[1]
+ filepath = sys.argv[2]
+elif len(sys.argv) == 2:
+ group_id = sys.argv[1]
+ filepath = input("Enter the filename to encrypt: ")
+else:
+ group_id = input("Enter the group name to encrypt to: ")
+ filepath = input("Enter the filename to encrypt: ")
+
+with open(filepath, "rb") as f:
+ text = f.read()
+
+for i in range(len(group_lists)):
+ if group_lists[i][0] == group_id:
+ klist = group_lists[i][1]
+ else:
+ klist = None
+
+logrus = []
+
+if klist is not None:
+ for i in range(len(klist)):
+ apattern = list(c.keylist(pattern=klist[i], secret=False))
+ if apattern[0].can_encrypt == 1:
+ logrus.append(apattern[0])
+ else:
+ pass
+ try:
+ ciphertext, result, sign_result = c.encrypt(text, recipients=logrus,
+ add_encrypt_to=True)
+ except:
+ ciphertext, result, sign_result = c.encrypt(text, recipients=logrus,
+ add_encrypt_to=True,
+ always_trust=True)
+ with open("{0}.asc".format(filepath), "wb") as f:
+ f.write(ciphertext)
+else:
+ pass
+
+# EOF
diff --git a/lang/python/examples/howto/encrypt-to-group-trustno1.py b/lang/python/examples/howto/encrypt-to-group-trustno1.py
new file mode 100755
index 00000000..da0376b5
--- /dev/null
+++ b/lang/python/examples/howto/encrypt-to-group-trustno1.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import sys
+from groups import group_lists
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+"""
+Uses the groups module to encrypt to multiple recipients.
+
+"""
+
+c = gpg.Context(armor=True)
+
+if len(sys.argv) > 3:
+ group_id = sys.argv[1]
+ filepath = sys.argv[2:]
+elif len(sys.argv) == 3:
+ group_id = sys.argv[1]
+ filepath = sys.argv[2]
+elif len(sys.argv) == 2:
+ group_id = sys.argv[1]
+ filepath = input("Enter the filename to encrypt: ")
+else:
+ group_id = input("Enter the group name to encrypt to: ")
+ filepath = input("Enter the filename to encrypt: ")
+
+with open(filepath, "rb") as f:
+ text = f.read()
+
+for i in range(len(group_lists)):
+ if group_lists[i][0] == group_id:
+ klist = group_lists[i][1]
+ else:
+ klist = None
+
+logrus = []
+
+if klist is not None:
+ for i in range(len(klist)):
+ apattern = list(c.keylist(pattern=klist[i], secret=False))
+ if apattern[0].can_encrypt == 1:
+ logrus.append(apattern[0])
+ else:
+ pass
+ try:
+ ciphertext, result, sign_result = c.encrypt(text, recipients=logrus,
+ add_encrypt_to=True)
+ except gpg.errors.InvalidRecipients as e:
+ for i in range(len(e.recipients)):
+ for n in range(len(logrus)):
+ if logrus[n].fpr == e.recipients[i].fpr:
+ logrus.remove(logrus[n])
+ else:
+ pass
+ try:
+ ciphertext, result, sign_result = c.encrypt(text,
+ recipients=logrus,
+ add_encrypt_to=True)
+ except:
+ pass
+ with open("{0}.asc".format(filepath), "wb") as f:
+ f.write(ciphertext)
+else:
+ pass
+
+# EOF
diff --git a/lang/python/examples/howto/encrypt-to-group.py b/lang/python/examples/howto/encrypt-to-group.py
new file mode 100755
index 00000000..d4cb0745
--- /dev/null
+++ b/lang/python/examples/howto/encrypt-to-group.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import sys
+from groups import group_lists
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+"""
+Uses the groups module to encrypt to multiple recipients.
+
+"""
+
+c = gpg.Context(armor=True)
+
+if len(sys.argv) > 3:
+ group_id = sys.argv[1]
+ filepath = sys.argv[2:]
+elif len(sys.argv) == 3:
+ group_id = sys.argv[1]
+ filepath = sys.argv[2]
+elif len(sys.argv) == 2:
+ group_id = sys.argv[1]
+ filepath = input("Enter the filename to encrypt: ")
+else:
+ group_id = input("Enter the group name to encrypt to: ")
+ filepath = input("Enter the filename to encrypt: ")
+
+with open(filepath, "rb") as f:
+ text = f.read()
+
+for i in range(len(group_lists)):
+ if group_lists[i][0] == group_id:
+ klist = group_lists[i][1]
+ else:
+ klist = None
+
+logrus = []
+
+if klist is not None:
+ for i in range(len(klist)):
+ apattern = list(c.keylist(pattern=klist[i], secret=False))
+ if apattern[0].can_encrypt == 1:
+ logrus.append(apattern[0])
+ else:
+ pass
+ try:
+ ciphertext, result, sign_result = c.encrypt(text, recipients=logrus,
+ add_encrypt_to=True)
+ except gpg.errors.InvalidRecipients as e:
+ for i in range(len(e.recipients)):
+ for n in range(len(logrus)):
+ if logrus[n].fpr == e.recipients[i].fpr:
+ logrus.remove(logrus[n])
+ else:
+ pass
+ try:
+ ciphertext, result, sign_result = c.encrypt(text,
+ recipients=logrus,
+ add_encrypt_to=True,
+ always_trust=True)
+ except:
+ pass
+ with open("{0}.asc".format(filepath), "wb") as f:
+ f.write(ciphertext)
+else:
+ pass
+
+# EOF
diff --git a/lang/python/examples/howto/export-key.py b/lang/python/examples/howto/export-key.py
new file mode 100755
index 00000000..913bfce7
--- /dev/null
+++ b/lang/python/examples/howto/export-key.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import os.path
+import sys
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+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 key(s) 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
diff --git a/lang/python/examples/howto/export-minimised-key.py b/lang/python/examples/howto/export-minimised-key.py
new file mode 100755
index 00000000..3889adcd
--- /dev/null
+++ b/lang/python/examples/howto/export-minimised-key.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import os.path
+import sys
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+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 key(s) 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
diff --git a/lang/python/examples/howto/export-secret-key.py b/lang/python/examples/howto/export-secret-key.py
new file mode 100755
index 00000000..e9c53fe5
--- /dev/null
+++ b/lang/python/examples/howto/export-secret-key.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import os
+import os.path
+import sys
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+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 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_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
diff --git a/lang/python/examples/howto/export-secret-keys.py b/lang/python/examples/howto/export-secret-keys.py
new file mode 100755
index 00000000..f0a791ef
--- /dev/null
+++ b/lang/python/examples/howto/export-secret-keys.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import os
+import os.path
+import subprocess
+import sys
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+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 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
+
+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:
+ hd = subprocess.getoutput(gpgconfcmd)
+ 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
diff --git a/lang/python/examples/howto/groups.py b/lang/python/examples/howto/groups.py
index 5e7fdf60..b8317b69 100644
--- a/lang/python/examples/howto/groups.py
+++ b/lang/python/examples/howto/groups.py
@@ -24,6 +24,7 @@ from __future__ import absolute_import, division, unicode_literals
# <http://www.gnu.org/licenses/>.
import subprocess
+import sys
"""
Intended for use with other scripts.
@@ -31,7 +32,12 @@ Intended for use with other scripts.
Usage: from groups import group_lists
"""
-lines = subprocess.getoutput("gpgconf --list-options gpg").splitlines()
+if sys.platform == "win32":
+ gpgconfcmd = "gpgconf.exe --list-options gpg"
+else:
+ gpgconfcmd = "gpgconf --list-options gpg"
+
+lines = subprocess.getoutput(gpgconfcmd).splitlines()
for i in range(len(lines)):
if lines[i].startswith("group") is True:
@@ -41,10 +47,12 @@ for i in range(len(lines)):
groups = line.split(":")[-1].replace('"', '').split(',')
-group_lines = groups
-for i in range(len(group_lines)):
- group_lines[i] = group_lines[i].split("=")
+group_lines = []
+group_lists = []
+
+for i in range(len(groups)):
+ group_lines.append(groups[i].split("="))
+ group_lists.append(groups[i].split("="))
-group_lists = group_lines
for i in range(len(group_lists)):
group_lists[i][1] = group_lists[i][1].split()
diff --git a/lang/python/examples/howto/import-key.py b/lang/python/examples/howto/import-key.py
new file mode 100755
index 00000000..25913785
--- /dev/null
+++ b/lang/python/examples/howto/import-key.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import os.path
+import sys
+
+del absolute_import, division, unicode_literals
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+print("""
+This script imports one or more public keys from a single file.
+""")
+
+c = gpg.Context(armor=True)
+
+if len(sys.argv) >= 3:
+ keyfile = sys.argv[1]
+ homedir = sys.argv[2]
+elif len(sys.argv) == 2:
+ keyfile = sys.argv[1]
+ homedir = input("Enter the GPG configuration directory path (optional): ")
+else:
+ keyfile = input("Enter the path and filename to import the key(s) from: ")
+ 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
+
+if os.path.isfile(keyfile) is True:
+ with open(keyfile, "rb") as f:
+ incoming = f.read()
+ result = c.key_import(incoming)
+else:
+ result = None
+
+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("")
+elif result is None:
+ print("You must specify a key file to import.")
diff --git a/lang/python/examples/howto/import-keys.py b/lang/python/examples/howto/import-keys.py
new file mode 100755
index 00000000..bdc15a68
--- /dev/null
+++ b/lang/python/examples/howto/import-keys.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import os.path
+import requests
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+print("""
+This script imports one or more public keys from the SKS keyservers.
+""")
+
+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(result.imports[i].fpr)
+ print("")
+else:
+ pass
diff --git a/lang/python/examples/howto/mutt-groups.py b/lang/python/examples/howto/mutt-groups.py
new file mode 100755
index 00000000..c0b515a7
--- /dev/null
+++ b/lang/python/examples/howto/mutt-groups.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+import sys
+from groups import group_lists
+
+"""
+Uses the groups module to generate Mutt crypt-hooks from gpg.conf.
+
+"""
+
+if len(sys.argv) >= 2:
+ hook_file = sys.argv[1]
+else:
+ hook_file = input("Enter the filename to save the crypt-hooks in: ")
+
+with open(hook_file, "w") as f:
+ f.write("""# Change settings based upon message recipient
+#
+# send-hook [!]<pattern> <command>
+#
+# <command> is executed when sending mail to an address matching <pattern>
+#
+# crypt-hook regexp key-id
+# The crypt-hook command provides a method by which you can
+# specify the ID of the public key to be used when encrypting
+# messages to a certain recipient. The meaning of "key ID" is to
+# be taken broadly: This can be a different e-mail address, a
+# numerical key ID, or even just an arbitrary search string. You
+# may use multiple crypt-hooks with the same regexp; multiple
+# matching crypt-hooks result in the use of multiple key-ids for a
+# recipient.
+""")
+
+for n in range(len(group_lists)):
+ rule = group_lists[n][0].replace(".", "\\\\.")
+ with open(hook_file, "a") as f:
+ f.write("\n")
+ f.write("# {0}\n".format(group_lists[n][0]))
+ for i in range(len(group_lists[n][1])):
+ f.write("crypt-hook {0} {1}\n".format(rule, group_lists[n][1][i]))
diff --git a/lang/python/examples/howto/pmkey-import-alt.py b/lang/python/examples/howto/pmkey-import-alt.py
new file mode 100755
index 00000000..e9521b7f
--- /dev/null
+++ b/lang/python/examples/howto/pmkey-import-alt.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import os.path
+import requests
+import sys
+
+del absolute_import, division, unicode_literals
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+print("""
+This script searches the ProtonMail key server for the specified key and
+imports it. Optionally enables specifying a different GnuPG home directory.
+""")
+
+c = gpg.Context(armor=True)
+url = "https://api.protonmail.ch/pks/lookup"
+ksearch = []
+
+if len(sys.argv) >= 3:
+ keyterm = sys.argv[1]
+ homedir = sys.argv[2]
+elif len(sys.argv) == 2:
+ keyterm = sys.argv[1]
+ homedir = input("Enter the GPG configuration directory path (optional): ")
+else:
+ keyterm = input("Enter the key ID, UID or search string: ")
+ 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
+
+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)
diff --git a/lang/python/examples/howto/pmkey-import.py b/lang/python/examples/howto/pmkey-import.py
new file mode 100755
index 00000000..edbd18e8
--- /dev/null
+++ b/lang/python/examples/howto/pmkey-import.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import requests
+import sys
+
+del absolute_import, division, unicode_literals
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+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)
diff --git a/lang/python/examples/howto/symcrypt-file.py b/lang/python/examples/howto/symcrypt-file.py
new file mode 100755
index 00000000..785a4d04
--- /dev/null
+++ b/lang/python/examples/howto/symcrypt-file.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, unicode_literals
+
+import gpg
+import sys
+
+# Copyright (C) 2018 Ben McGinnes <[email protected]>
+#
+# This program 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.
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation; either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program 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 and the GNU
+# Lesser General Public Licensefor more details.
+#
+# You should have received a copy of the GNU General Public License and the GNU
+# Lesser General Public along with this program; if not, see
+# <http://www.gnu.org/licenses/>.
+
+"""
+Symmetrically encrypts a file. Passphrase will be prompted for via Pinentry.
+
+Will produce both an ASCII armoured and GPG binary format copy of the encrypted
+file.
+"""
+
+if len(sys.argv) > 2:
+ filename = " ".join(sys.argv[1:])
+elif len(sys.argv) == 2:
+ filename = sys.argv[1]
+else:
+ filename = input("Enter the path and filename to encrypt: ")
+
+with open(filename, "rb") as f:
+ text = f.read()
+
+with gpg.Context(armor=True) as ca:
+ try:
+ ciphertext, result, sign_result = ca.encrypt(text, passphrase=None,
+ sign=False)
+ with open("{0}.asc".format(filename), "wb") as fa:
+ fa.write(ciphertext)
+ except gpg.errors.GPGMEError as e:
+ print(e)
+
+with gpg.Context() as cg:
+ try:
+ ciphertext, result, sign_result = cg.encrypt(text, passphrase=None,
+ sign=False)
+ with open("{0}.gpg".format(filename), "wb") as fg:
+ fg.write(ciphertext)
+ except gpg.errors.GPGMEError as e:
+ print(e)
diff --git a/lang/python/examples/howto/temp-homedir-config.py b/lang/python/examples/howto/temp-homedir-config.py
index ddd79327..1111fe21 100755
--- a/lang/python/examples/howto/temp-homedir-config.py
+++ b/lang/python/examples/howto/temp-homedir-config.py
@@ -3,6 +3,10 @@
from __future__ import absolute_import, division, unicode_literals
+import os
+import os.path
+import sys
+
# Copyright (C) 2018 Ben McGinnes <[email protected]>
#
# This program is free software; you can redistribute it and/or modify it under
@@ -24,10 +28,6 @@ from __future__ import absolute_import, division, unicode_literals
# Lesser General Public along with this program; if not, see
# <http://www.gnu.org/licenses/>.
-import os
-import os.path
-import sys
-
intro = """
This script creates a temporary directory to use as a homedir for
testing key generation tasks with the correct permissions, along
@@ -54,6 +54,13 @@ message telling you to specify a new directory name. There is no
default directory name.
"""
+ciphers256 = "TWOFISH CAMELLIA256 AES256"
+ciphers192 = "CAMELLIA192 AES192"
+ciphers128 = "CAMELLIA128 AES"
+ciphersBad = "BLOWFISH IDEA CAST5 3DES"
+digests = "SHA512 SHA384 SHA256 SHA224 RIPEMD160 SHA1"
+compress = "ZLIB BZIP2 ZIP Uncompressed"
+
gpgconf = """# gpg.conf settings for key generation:
expert
allow-freeform-uid
@@ -63,11 +70,11 @@ tofu-default-policy unknown
enable-large-rsa
enable-dsa2
cert-digest-algo SHA512
-default-preference-list TWOFISH CAMELLIA256 AES256 CAMELLIA192 AES192 CAMELLIA128 AES BLOWFISH IDEA CAST5 3DES SHA512 SHA384 SHA256 SHA224 RIPEMD160 SHA1 ZLIB BZIP2 ZIP Uncompressed
-personal-cipher-preferences TWOFISH CAMELLIA256 AES256 CAMELLIA192 AES192 CAMELLIA128 AES BLOWFISH IDEA CAST5 3DES
-personal-digest-preferences SHA512 SHA384 SHA256 SHA224 RIPEMD160 SHA1
-personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed
-"""
+default-preference-list {0} {1} {2} {3} {4} {5}
+personal-cipher-preferences {0} {1} {2} {3}
+personal-digest-preferences {4}
+personal-compress-preferences {5}
+""".format(ciphers256, ciphers192, ciphers128, ciphersBad, digests, compress)
agentconf = """# gpg-agent.conf settings for key generation:
default-cache-ttl 300
@@ -84,17 +91,17 @@ else:
userdir = os.path.expanduser("~")
if new_homedir.startswith("~"):
- new_homdir.replace("~", "")
+ new_homedir.replace("~", "")
else:
pass
if new_homedir.startswith("/"):
- new_homdir.replace("/", "")
+ new_homedir.replace("/", "")
else:
pass
if new_homedir.startswith("."):
- new_homdir.replace(".", "_")
+ new_homedir.replace(".", "_")
else:
pass
diff --git a/lang/python/examples/inter-edit.py b/lang/python/examples/inter-edit.py
index ed0d8c42..5b58c97b 100644
--- a/lang/python/examples/inter-edit.py
+++ b/lang/python/examples/inter-edit.py
@@ -15,15 +15,15 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
-
"""Simple interactive editor to test editor scripts"""
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import gpg
+del absolute_import, print_function, unicode_literals
+
if len(sys.argv) != 2:
sys.exit("Usage: %s <Gpg key pattern>\n" % sys.argv[0])
@@ -40,10 +40,12 @@ with gpg.Context() as c:
print("Editing key {} ({}):".format(key.uids[0].uid, key.subkeys[0].fpr))
def edit_fnc(keyword, args):
- print("Status: {}, args: {} > ".format(
- keyword, args), end='', flush=True)
+ print(
+ "Status: {}, args: {} > ".format(keyword, args),
+ end='',
+ flush=True)
- if not 'GET' in keyword:
+ if 'GET' not in keyword:
# no prompt
print()
return None
diff --git a/lang/python/examples/low_level-encrypt_to_all.py b/lang/python/examples/low_level-encrypt_to_all.py
index bad4220c..5c10d3df 100755
--- a/lang/python/examples/low_level-encrypt_to_all.py
+++ b/lang/python/examples/low_level-encrypt_to_all.py
@@ -16,18 +16,18 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
-
"""
This program will try to encrypt a simple message to each key on your
keyring. If your keyring has any invalid keys on it, those keys will
be skipped and it will re-try the encryption."""
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import gpg
+del absolute_import, print_function, unicode_literals
+
with gpg.Context(armor=True) as c:
recipients = list()
for key in c.keylist():
@@ -40,14 +40,15 @@ with gpg.Context(armor=True) as c:
while not ciphertext:
print("Encrypting to %d recipients" % len(recipients))
try:
- ciphertext, _, _ = c.encrypt(b'This is my message.',
- recipients=recipients)
+ ciphertext, _, _ = c.encrypt(
+ b'This is my message.', recipients=recipients)
except gpg.errors.InvalidRecipients as e:
print("Encryption failed for these keys:\n{0!s}".format(e))
# filter out the bad keys
bad_keys = {bad.fpr for bad in e.recipients}
- recipients = [r for r in recipients
- if not r.subkeys[0].fpr in bad_keys]
+ recipients = [
+ r for r in recipients if not r.subkeys[0].fpr in bad_keys
+ ]
sys.stdout.buffer.write(ciphertext)
diff --git a/lang/python/examples/sign.py b/lang/python/examples/sign.py
index 16c2256a..5b90b4b8 100755
--- a/lang/python/examples/sign.py
+++ b/lang/python/examples/sign.py
@@ -17,12 +17,13 @@
# along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import gpg
from gpg.constants.sig import mode
+del absolute_import, print_function, unicode_literals
+
with gpg.Context() as c:
signed, _ = c.sign(b"Test message", mode=mode.CLEAR)
sys.stdout.buffer.write(signed)
diff --git a/lang/python/examples/signverify.py b/lang/python/examples/signverify.py
index 5870ca95..2df72758 100755
--- a/lang/python/examples/signverify.py
+++ b/lang/python/examples/signverify.py
@@ -20,12 +20,13 @@
# It uses keys for [email protected] generated by genkey.py script
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import gpg
from gpg.constants.sig import mode
+del absolute_import, print_function, unicode_literals
+
user = "joe+gpg"
with gpg.Context(pinentry_mode=gpg.constants.PINENTRY_MODE_LOOPBACK) as c:
diff --git a/lang/python/examples/simple.py b/lang/python/examples/simple.py
index 8f451d7c..17c3eba0 100755
--- a/lang/python/examples/simple.py
+++ b/lang/python/examples/simple.py
@@ -18,11 +18,12 @@
# along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import gpg
+del absolute_import, print_function, unicode_literals
+
with gpg.Context(armor=True) as c:
recipients = []
print("Enter name of your recipient(s), end with a blank line.")
@@ -40,8 +41,8 @@ with gpg.Context(armor=True) as c:
if not recipients:
sys.exit("No recipients.")
- print("Encrypting for {}.".format(", ".join(k.uids[0].name
- for k in recipients)))
+ print("Encrypting for {}.".format(", ".join(
+ k.uids[0].name for k in recipients)))
ciphertext, _, _ = c.encrypt(b"This is my message,", recipients)
sys.stdout.buffer.write(ciphertext)
diff --git a/lang/python/examples/testCMSgetkey.py b/lang/python/examples/testCMSgetkey.py
index d4c08840..f1cdb2ce 100644
--- a/lang/python/examples/testCMSgetkey.py
+++ b/lang/python/examples/testCMSgetkey.py
@@ -15,15 +15,15 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
-
"""A test applicaton for the CMS protocol."""
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import gpg
+del absolute_import, print_function, unicode_literals
+
if len(sys.argv) != 2:
sys.exit("fingerprint or unique key ID for gpgme_get_key()")
diff --git a/lang/python/examples/verifydetails.py b/lang/python/examples/verifydetails.py
index b3ca1339..dc0e7d38 100755
--- a/lang/python/examples/verifydetails.py
+++ b/lang/python/examples/verifydetails.py
@@ -18,11 +18,13 @@
# along with this program; if not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, print_function, unicode_literals
-del absolute_import, print_function, unicode_literals
import sys
import gpg
+del absolute_import, print_function, unicode_literals
+
+
def print_engine_infos():
print("gpgme version:", gpg.core.check_version(None))
print("engines:")
@@ -31,8 +33,9 @@ def print_engine_infos():
print(engine.file_name, engine.version)
for proto in [gpg.constants.protocol.OpenPGP, gpg.constants.protocol.CMS]:
- print("Have {}? {}".format(gpg.core.get_protocol_name(proto),
- gpg.core.engine_check_version(proto)))
+ print("Have {}? {}".format(
+ gpg.core.get_protocol_name(proto),
+ gpg.core.engine_check_version(proto)))
def verifyprintdetails(filename, detached_sig_filename=None):
@@ -40,9 +43,9 @@ def verifyprintdetails(filename, detached_sig_filename=None):
with gpg.Context() as c:
# Verify.
- data, result = c.verify(open(filename),
- open(detached_sig_filename)
- if detached_sig_filename else None)
+ data, result = c.verify(
+ open(filename),
+ open(detached_sig_filename) if detached_sig_filename else None)
# List results for all signatures. Status equal 0 means "Ok".
for index, sign in enumerate(result.signatures):
@@ -57,15 +60,15 @@ def verifyprintdetails(filename, detached_sig_filename=None):
if data:
sys.stdout.buffer.write(data)
+
def main():
print_engine_infos()
print()
argc = len(sys.argv)
if argc < 2 or argc > 3:
- sys.exit(
- "Usage: {} <filename>[ <detached_signature_filename>]".format(
- sys.argv[0]))
+ sys.exit("Usage: {} <filename>[ <detached_signature_filename>]".format(
+ sys.argv[0]))
if argc == 2:
print("trying to verify file {}.".format(sys.argv[1]))
@@ -74,5 +77,6 @@ def main():
print("trying to verify signature {1} for file {0}.".format(*sys.argv))
verifyprintdetails(sys.argv[1], sys.argv[2])
+
if __name__ == "__main__":
main()