From 7221bb67642eb01a07957d66d0cbcd4ef8aadbf8 Mon Sep 17 00:00:00 2001 From: Ben McGinnes Date: Tue, 20 Mar 2018 09:53:27 +1100 Subject: [PATCH] example: encrypt file * Nested encryption in try/except statement in case recipient key is untrusted or invalid. --- lang/python/examples/howto/encrypt-file.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/lang/python/examples/howto/encrypt-file.py b/lang/python/examples/howto/encrypt-file.py index 8aee52ad..017a3421 100755 --- a/lang/python/examples/howto/encrypt-file.py +++ b/lang/python/examples/howto/encrypt-file.py @@ -52,13 +52,19 @@ with open(filename, "rb") as f: text = f.read() with gpg.Context(armor=True) as ca: - ciphertext, result, sign_result = ca.encrypt(text, recipients=rkey, - sign=False) - with open("{0}.asc".format(filename), "wb") as fa: - fa.write(ciphertext) + try: + ciphertext, result, sign_result = ca.encrypt(text, recipients=rkey, + sign=False) + with open("{0}.asc".format(filename), "wb") as fa: + fa.write(ciphertext) + except gpg.errors.InvalidRecipients as e: + print(e) with gpg.Context() as cg: - ciphertext, result, sign_result = cg.encrypt(text, recipients=rkey, - sign=False) - with open("{0}.gpg".format(filename), "wb") as fg: - fg.write(ciphertext) + try: + ciphertext, result, sign_result = cg.encrypt(text, recipients=rkey, + sign=False) + with open("{0}.gpg".format(filename), "wb") as fg: + fg.write(ciphertext) + except gpg.errors.InvalidRecipients as e: + print(e)