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>
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.
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.
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/>.
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."""
25 from __future__ import absolute_import, print_function, unicode_literals
26 del absolute_import, print_function, unicode_literals
31 with gpg.Context(armor=True) as c:
33 for key in c.keylist():
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))
41 print("Encrypting to %d recipients" % len(recipients))
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))
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]
53 sys.stdout.buffer.write(ciphertext)