Skip to content

Instantly share code, notes, and snippets.

@spang
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spang/4da283fbfb27c16f9175 to your computer and use it in GitHub Desktop.
Save spang/4da283fbfb27c16f9175 to your computer and use it in GitHub Desktop.
gpg key signature importer
import os
import glob
import getpass
import tempfile
import click
import gnupg
from inbox import APIClient
def download_signature_attachments(outdir, fpr, api_token, api_url=None):
c = APIClient(None, None, api_token, api_url)
n = c.namespaces.first()
print "using namespace {}".format(n['namespace_id'])
# We can't just use the files API endpoint with a filename='msg.asc'
# filter because the files endpoint filters out inline attachments.
file_ids = []
for m in n.messages.where(
subject='Your signed PGP key 0x{}'.format(fpr)):
for f in m.files:
if f['filename'] == 'msg.asc':
file_ids.append(f['id'])
print "{} signatures to download".format(len(file_ids))
for i, id_ in enumerate(file_ids):
f = n.files.find(id_)
outfile = os.path.join(outdir, '{}.asc'.format(i))
with open(outfile, 'w') as fd:
print >>fd, f.download()
def import_keys(d, keyserver):
gpg_home = os.path.join(os.getenv('HOME'), '.gnupg')
gpg = gnupg.GPG(gnupghome=gpg_home)
gpg.encoding = 'utf-8'
gpg_passphrase = getpass.getpass("What's your GPG passphrase?")
imported_keys = set([])
for f in glob.glob(os.path.join(d, '*.asc')):
print "importing key in '{}'".format(f)
with open(f, 'r') as fd:
key_data = unicode(
gpg.decrypt_file(fd, passphrase=gpg_passphrase).data,
encoding='utf-8').encode('utf-8')
import_result = gpg.import_keys(key_data)
for k in import_result.fingerprints:
imported_keys.add(k)
print "imported sigs on {} keys".format(len(imported_keys))
print "sending to server..."
for k in imported_keys:
gpg.send_keys(keyserver, k)
print "done"
@click.command()
@click.option('--api-token', '-t')
@click.option('--fingerprint', '-f', required=True)
@click.option('--api-url', '-u', default=None)
@click.option('--keyserver', '-k', default='pgp.mit.edu')
def main(api_token, fingerprint, api_url, keyserver):
d = tempfile.mkdtemp()
download_signature_attachments(d, fingerprint, api_token=api_token,
api_url=api_url)
import_keys(d, keyserver)
# TODO: clean up tmpdir, archive messages in inbox (important so we can
# find messages we *didn't* process)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment