Next in our series of Python modules you should know
is PyGPGME. This package lets you sign, verify, encrypt and decrypt messages
using the OpenPGP format. It is built on top of the GNU Privacy Guard and the
GPGME library.

Exporting a key

This is similar to running the following command:

gpg --export [UID]

importosimportgpgmefromioimportBytesIO# set the environment to custom gpg directorygpghome=os.path.expanduser('~/gpghome')os.environ['GNUPGHOME']=gpghome# create a contextctx=gpgme.Context()ctx.armor=Truekeydata=BytesIO()[key]=ctx.keylist()ctx.export(key.subkeys[0].keyid,keydata)printkeydata.getvalue()

Importing a key

This is similar to running the following command:

gpg --import [Filename]

importosimportgpgmeimporturllib2# set the environment to custom gpg directorygpghome=os.path.expanduser('~/gpghome')os.environ['GNUPGHOME']=gpghome# create a contextctx=gpgme.Context()# Download a public keyhandle=urllib2.urlopen('http://repo.baruwa.org/RPM-GPG-KEY-BARUWA')# Import the key_=ctx.import_(handle)# Get key and print out keyIDkey=ctx.get_key('4BA17AC7')print"Imported key ID: ",key.uids[0].uid

Delete a key

This is similar to running the following command:

gpg --delete-key UID

importosimportgpgme# set the environment to custom gpg directorygpghome=os.path.expanduser('~/gpghome')os.environ['GNUPGHOME']=gpghome# create a contextctx=gpgme.Context()# Get the public key we just importedkey=ctx.get_key('4BA17AC7')# Delete the keyctx.delete(key)