Skip to main content

Using Python for GPG/PGP File Encryption - Part 1

So, this will be the start of a series that will build a python script for GPG/PGP file encryption. In this post, we'll look at installing gnupg for python and using python to setup the keystore, create a private key, exporting the associated public key, and importing a public key. Now everything done here can be done with simple gnupg commands, but learning how to do this with python will help in understanding the script we'll be building to complete file encryption. I will be covering non-python gnupg commands in a future post. Additionally, the folks at the python-gnupg site over at pythonhosted.org have done a really great job at documenting everything (link to their site at the bottom). The stuff I'll be going over will be more of a start-to-finish for anyone that may get lost in the muck of doing stuff with python.

Full Disclosure #1: Any key identifier throughout the series of posts is FICTITIOUS and DOES NOT represent any real key, either associated with myself or anyone else. If you would like my public key to send me an encrypted file/message, just ask for it.

Full Disclosure #2: I'm not a python expert. If, going through my code, someone has any suggestions please contact me. I am fully open to leaning or making changes to my scripts to get them to run better/look cleaner. I have just been lucky enough to figure out how to get things to operate the way I want them to, and I'm learning by trial and error. If it works more than once, then I'm going with it until other suggestions change my ways. Additionally, I like to set everything as a variable. That way, if I fat-finger something, I can easily quit and start over without committing anything.

Full Disclosure #3: I've done everything in Linux. Sorry Windows folks, it's just easier that way. However, if you have python installed on a Windows box, with pip setup, you should be in good shape and have no issues following along.

Initial Setup
Now, any additional information about python-gnupg can be found from their site on pythonhosted.org HERE. I highly recommend reading through their site for the details, as I will only be covering the high level stuffs. The install is very easy and straight forward. Simply install with PIP:
$ sudo pip install python-gnupg
Launch the python shell and make sure it works by issuing:
>>>import gnupg
Creating a Private Key
Now, if that's working, let's move on to the initial setup. The default keystore for gnupg is '/home/USER/.gnupg'. You can either use this directory or you can create a different one. First off, whatever directory want to you make sure it's actually there! If not, then simply create it first. Once that is done, you can go ahead and create your first private key. Let's jump into the python shell and do that:
>>> import os
>>> import gnupg
>>> key_home = '/home/USER/.gnupg'
>>> gpg = gnupg.GPG(gnupghome=key_home)
>>> key_name = 'YourNameHere'
>>> key_email = 'SomeEmail@SomeDomain.com'
>>> rsa_default = 'RSA'
>>> key_type = '2048'
>>> key_information = gpg.gen_key_input(name_real=key_name, name_email=key_email, key_type=rsa_default, key_length=key_type)
>>> gpg.gen_key(key_information)

After hammering through the above, you can verify that the key was created by issuing the following:
>>>gpg.list_keys(True)
That command will list only Private keys. To list public keys, issue the same command without the 'True' statement. Right now, you should only see one private key and one public key. You can tell the difference in the output. You will look for an option called 'type'. See my example here (I've highlighted the option in RED):

Private Key:
[{'dummy': u'', 'keyid': u'2C4767E2017CBD48', 'expires': u'', 'subkeys': [], 'length': u'2048', 'ownertrust': u'', 'algo': u'1', 'fingerprint': u'BE4E5DC1AA3DF69CF405D2292C4767E2017CD48', 'date': u'1440187947', 'trust': u'', 'type': u'sec', 'uids': [u'YourNameHere <SomeEmail@SomeDomain.com>']}]

Public Key:
[{'dummy': u'', 'keyid': u'2C4767E2017CBD48', 'expires': u'', 'subkeys': [], 'length': u'2048', 'ownertrust': u'u', 'algo': u'1', 'fingerprint': u'BE4E5DC1AA3DF69CF405D2292C4767E2017CD48', 'date': u'1440187947', 'trust': u'u', 'type': u'pub', 'uids': [u'YourNameHere <SomeEmail@SomeDomain.com>']}]
Exporting the Public Key
From time to time, you will need to export the public key to share out to other folks in order to allow them to send you encrypted files/messages. Let's take a look at exporting the Public key for the one we just created above. One thing you will need is a key identifier. This can either be the 'keyid' or 'fingerprint'. I'm using the 'keyid' below. Launch your python shell and start hammering through the following:
>>> import os
>>> import gnupg
>>> key_home = '/home/USER/.gnupg'
>>> gpg = gnupg.GPG(gnupghome=key_home)
>>> keyids = '2C4767E2017CBD48'
>>> ascii_armored_public_keys = gpg.export_keys(keyids)

Don't exit yet! I'm going to show two things here. First, I'm going to print the variable 'ascii_armored_public_keys' to show the key file. From there you could just copy and paste the key file. After the print command, I'm going to show writing the public key to a file on the system. Here we go:
>>> print ascii_armored_public_keys
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v2.0.14 (GNU/Linux)
mQENBFXXhisBCADAA6x2zwEKiqdUbMsblMaQQ/3lfPNinkdwvFlwT/qSBBfUBR6Z
4V6OumUF8Oszhro0fjozZ5qm87BAbxHN82djK3xWHbVzPDlPjgUSZ2YQJxA5t/pC
MrOIJScFGFBf+cXRxiqAwuszA4srKzymSshh715LjsdlBaPVqMv65XT0vyip/O/q
0EFhIuxwDyZ2OdKcJ4M8FynQEYJh54k1uZ9MuowsIw/Pv2Htyzn8p8JzRkvFPYUe
OXdi7Tw8PMkEPme7t3oEfPxqdRQOMjKcX/syjzeHbsGYNZqB3qRemDvpXewsZQs6
+2BLp+fUbgtuoWTOcv7JFnVTxlGscugmvhR7ABEBAAG0HmxhcnJ5IDxsbHViaW5z
a2lAYWxpeHBhcnQuY29tPokBOAQTAQIAIgUCVdeGKwIbLwYLCQgHAwIGFQgCCQoL
BBYCAwECHgECF4AACgkQLEdn4gF8vUjAwwgApDwYtcs1IFDKiVqE1FvlDFLNjB28
xErW7Vn8dr3HHspCEkMjyl0EzXhONXbet5+UnkgAXoBATF+OnhpZ5hxXcR7iC1+9
4nG9/KaPsUyVX4nXeeawNUcdnWKzPFO+q6BweKFxE+xbrm5qyU2KuJvVebAc7FYu
kHCVkwr7exNaFJp9GdlKbRFiQKuxstYGPGPvlGeIK5hh9ZIy+W2ozZd0zakV0ssF
XeGmJGmjncTcMvem+L11qr/ezBFKyZdFqjDhLpyOKXDL896btqJiv3481yzupfzB
65HqZW6K7xjxjuAFZUaRtbIXFQiALLPvIAGpWl21r4MT+W29UNrxFwChwg==
=WH4A
-----END PGP PUBLIC KEY BLOCK-----
>>> f = open('PublicKeyName.pub', 'w')
>>> f.write(ascii_armored_public_keys)
>>> f.close()
>>>exit()
From here, you should now have a file called 'PublicKeyName.pub' with the above key information. You can now share that key out with anyone that will need to send you an encrypted file and/or message.

 Importing a Public Key
Finally, let's look at importing a public key. This is a key component to sending people encrypted files or messages. This can also be used to verify that a file or message was from a specific individual. Without having the public key of a particular individual or business, you won't be able to send them a properly encrypted file. With all that being said, let's get it done.

You've got the public key from 'Person B' sitting at the root of your home directory. Open your python shell and let's import it:
>>> import os
>>> import gnupg
>>> key_home = '/home/USER/.gnupg'
>>> gpg = gnupg.GPG(gnupghome=key_home)
>>>key_to_import = /home/USER/PersonB-PublicKey.pub
>>>key_data = open(key_to_import).read()
>>>import_result = gpg.import_keys(key_data)
Don't quit yet. Let's verify that the key was imported with the following command:
>>>gpg.list_keys()

Now, that should do it. You should be all set to get started with encrypting and decrypting files. Stay tuned for the continuation of the series!

Further Reading
Gnupg: https://www.gnupg.org/
Python Gnupg Website: https://pythonhosted.org/python-gnupg/

Comments

Post a Comment

Popular posts from this blog

Windows Server 2008: Log on as batch job

From time to time, I have to set up some scheduled tasks that required a dedicated account to run. And when doing so, I'll usually forget that the dedicated account usually isn't given any more permissions than what it needs to complete the task at hand. So, after setting up the task, Windows will usually yell at me and say "The account needs batch job rights". So here's how to grant batch job permissions on your server. Go to your start menu, and start searching for Local Security Policy In the left pane of the MMC that opens up, expand Local Policies, and highlight User Rights Assignment. Now, in the left right pane, locate "Log on as a batch job" and double click it. In the properties window that opens up, add the user or group that needs this permission. I find that if you have multiple service accounts running different tasks on the same server, it's easier to just add a group verses the individual a...

Replacing rsyslog with syslog-ng on RHEL 6.5

So...I had a piece of monitoring software that didn't play nice with the RHEL default rsyslog for log collection. The software was developed to only work with syslog-ng. I'll be going over the steps that I took, that worked for me, in replacing rsyslog with syslog-ng. I would imagine that these same steps should work for any Linux system similar to RHEL (Fedora, CentOS, etc.). For others (like Debein based distributions), I would need to look into that (coming in a future update to this post). First, remove rsyslog. You will need to keep the dependencies as they will be needed for syslog-ng: sudo rpm -e --nodeps rsyslog Next we will need to add the EPEL repository (more info can be found HERE ): wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm sudo rpm -ivh epel-release-6-8.rpm sudo yum repolist That last command will list all the installed repositories. You are simply verifying that the EPEL package has been installed. Now that we fi...