August 23, 2014

How to Sign Text Using Python

An important tenet of any asymmetric encryption system is that a public key must be distributed far and wide -- it is used to encrypt information -- while the corresponding private key must be kept, well, private. The code below shows how to sign some text with your public key in python:

def sign(message):
    gpg = gnupg.GPG(gnupghome='{}/.gnupg'.format(os.path.expanduser('~')))
    gpg.encoding = 'utf-8'
    gpg.secret_keyring=['secring.gpg']
    gpg.public_keyring=['pubring.gpg']
    signed = gpg.sign(message)
    return str(signed)
Since python-gnupg can take a list for both public and private keys, both filenames go in as a list. Message is a string of plaintext, whose return value's str method returns a cleartext signature as well as the message itself.

No comments:

Post a Comment