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

Visio Stencils Pack for Azure and Microsoft Integration (v5.0.0)

First off, I'd like to send a big shout out to Sandro Pereira who's been managing the vision stencils pack. Essentially, I'm re-posting his information here, because I had a really hard time finding the latest Visio pack for Azure, that wasn't a bunch of SVG's. My thought is that if more people re-post, maybe the search engines of the internet will have an easier time propagating the information... Sandero's Blog (the original post around the new stencils): https://blog.sandro-pereira.com/2019/10/18/microsoft-integration-and-azure-stencils-pack-for-visio-new-major-version-available-v5-0-0/ Sandero's GitHub: https://github.com/sandroasp/Microsoft-Integration-and-Azure-Stencils-Pack-for-Visio Microsoft TechNet Download: https://gallery.technet.microsoft.com/Collection-of-Integration-e6a3f4d0 I will say, and maybe it's just because I'm using Visio 2013, each icon has a boarder that needs to be removed when putting it on the page... Likely it

Keto Kickin' Choffle

Alight, first recipe on the blog... If you've had a chance to reach the "About" section, you will have seen that, rather than spinning up multiple blogs, I'm just going to combine my passions for tech, food, health, and music into this one space. If you're not a fan, then too bad. I really just don't want to manage more than one blog.... With that, here goes nothing... So I recently came across the choffle. This is a really great, and fast to make replacement for buns. I'm also a huge fan of spicy foods. Well, I got the great idea to combine the heat with the choffle. And let me tell you, it turned out really good. I like to use this for a bun replacement when I'm in the mood for that extra kick, but not the extra toppings. Why? Because the extra toppings are now combined in the choffle. Thus removing the need for the additional toppings on my burgers. Enjoy. Kickin' choffle The choffle mix with a kick! Author: Larry L. Preparation Time: 3

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