#!/usr/bin/env python2.2
# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
#
#    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 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 for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""
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 removed
and it will re-try the encryption."""

from pyme.core import Data, Context, Recipients
from pyme.constants import attr, validity

plain = Data('This is my message.')

c = Context()
c.set_armor(1)

def sendto(namelist):
    r = Recipients()
    cipher = Data()
    for name in namelist:
        r.add(name, validity.FULL)
    c.op_encrypt(r, plain, cipher)
    return cipher.read()

names = []
for key in c.op_keylist_start():
    print " *** Found key for %s" % key.get_string_attr(attr.USERID, None, 0)
    index = 0
    valid = 0
    while 1:
        keyid = key.get_string_attr(attr.KEYID, None, index)
        if keyid == None:
            break
        can_encrypt = key.get_ulong_attr(attr.CAN_ENCRYPT, None, index)
        valid += can_encrypt
        print "     Subkey %s: encryption %s" % \
              (keyid, can_encrypt and "enabled" or "disabled")
        index += 1
    
    if valid:
        names.append(key.get_string_attr(attr.KEYID, None, 0))
    else:
        print "     This key cannot be used for encryption; skipping."

passno = 0

print "Encrypting to %d recipients" % len(names)
print sendto(names)


