Imported Upstream version 1.8.0
[platform/upstream/gpgme.git] / lang / python / examples / encrypt-to-all.py
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2016 g10 Code GmbH
4 # Copyright (C) 2008 Igor Belyi <belyi@users.sourceforge.net>
5 # Copyright (C) 2002 John Goerzen <jgoerzen@complete.org>
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, see <http://www.gnu.org/licenses/>.
19
20 """
21 This program will try to encrypt a simple message to each key on your
22 keyring.  If your keyring has any invalid keys on it, those keys will
23 be skipped and it will re-try the encryption."""
24
25 from __future__ import absolute_import, print_function, unicode_literals
26 del absolute_import, print_function, unicode_literals
27
28 import sys
29 import gpg
30
31 with gpg.Context(armor=True) as c:
32     recipients = list()
33     for key in c.keylist():
34         valid = 0
35         if any(sk.can_encrypt for sk in key.subkeys):
36             recipients.append(key)
37             print("Adding recipient {0}.".format(key.uids[0].uid))
38
39     ciphertext = None
40     while not ciphertext:
41         print("Encrypting to %d recipients" % len(recipients))
42         try:
43             ciphertext, _, _ = c.encrypt(b'This is my message.',
44                                          recipients=recipients)
45         except gpg.errors.InvalidRecipients as e:
46             print("Encryption failed for these keys:\n{0!s}".format(e))
47
48             # filter out the bad keys
49             bad_keys = {bad.fpr for bad in e.recipients}
50             recipients = [r for r in recipients
51                           if not r.subkeys[0].fpr in bad_keys]
52
53     sys.stdout.buffer.write(ciphertext)