Blame lang/python/examples/encrypt-to-all.py

Packit d7e8d0
#!/usr/bin/env python
Packit d7e8d0
#
Packit d7e8d0
# Copyright (C) 2016 g10 Code GmbH
Packit d7e8d0
# Copyright (C) 2008 Igor Belyi <belyi@users.sourceforge.net>
Packit d7e8d0
# Copyright (C) 2002 John Goerzen <jgoerzen@complete.org>
Packit d7e8d0
#
Packit d7e8d0
# This program is free software; you can redistribute it and/or modify
Packit d7e8d0
# it under the terms of the GNU General Public License as published by
Packit d7e8d0
# the Free Software Foundation; either version 2 of the License, or
Packit d7e8d0
# (at your option) any later version.
Packit d7e8d0
#
Packit d7e8d0
# This program is distributed in the hope that it will be useful, but
Packit d7e8d0
# WITHOUT ANY WARRANTY; without even the implied warranty of
Packit d7e8d0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit d7e8d0
# General Public License for more details.
Packit d7e8d0
#
Packit d7e8d0
# You should have received a copy of the GNU General Public License
Packit d7e8d0
# along with this program; if not, see <http://www.gnu.org/licenses/>.
Packit d7e8d0
Packit d7e8d0
"""
Packit d7e8d0
This program will try to encrypt a simple message to each key on your
Packit d7e8d0
keyring.  If your keyring has any invalid keys on it, those keys will
Packit d7e8d0
be skipped and it will re-try the encryption."""
Packit d7e8d0
Packit d7e8d0
from __future__ import absolute_import, print_function, unicode_literals
Packit d7e8d0
del absolute_import, print_function, unicode_literals
Packit d7e8d0
Packit d7e8d0
import sys
Packit d7e8d0
import gpg
Packit d7e8d0
Packit d7e8d0
with gpg.Context(armor=True) as c:
Packit d7e8d0
    recipients = list()
Packit d7e8d0
    for key in c.keylist():
Packit d7e8d0
        valid = 0
Packit d7e8d0
        if any(sk.can_encrypt for sk in key.subkeys):
Packit d7e8d0
            recipients.append(key)
Packit d7e8d0
            print("Adding recipient {0}.".format(key.uids[0].uid))
Packit d7e8d0
Packit d7e8d0
    ciphertext = None
Packit d7e8d0
    while not ciphertext:
Packit d7e8d0
        print("Encrypting to %d recipients" % len(recipients))
Packit d7e8d0
        try:
Packit d7e8d0
            ciphertext, _, _ = c.encrypt(b'This is my message.',
Packit d7e8d0
                                         recipients=recipients)
Packit d7e8d0
        except gpg.errors.InvalidRecipients as e:
Packit d7e8d0
            print("Encryption failed for these keys:\n{0!s}".format(e))
Packit d7e8d0
Packit d7e8d0
            # filter out the bad keys
Packit d7e8d0
            bad_keys = {bad.fpr for bad in e.recipients}
Packit d7e8d0
            recipients = [r for r in recipients
Packit d7e8d0
                          if not r.subkeys[0].fpr in bad_keys]
Packit d7e8d0
Packit d7e8d0
    sys.stdout.buffer.write(ciphertext)