Cryptography can be intimidating. Fortunately, there are a number of excellent, tested, full-featured libraries that make cryptographic features relatively easy to add to your project. For Python, PyCrypto is one of those excellent libraries. It supports multiple ciphers and hashing algorithms; and the compute-intensive routines are implemented in native code. In this article, I provide a simple, somewhat-practical example of how to implement encryption using PyCrypto.

Install PyCrypto

If you have pip, you can install PyCrypto with:

$ pip install pycrypto

Demo

To demonstrate how to use PyCrypto, I made a simple tool for encrypting and decrypting streams of data using the Advanced Encryption Standard (AES).

Encrypting

First, we need something to encrypt:

$ echo "Shhh... This is a secret." > secret.txt

Now, just use the stream-redirection features of your shell to stream in the top-secret file.

$ ./pycrypto-aes-demo.py < secret.txt \
                         > encrypted
Encryption Key: EAwE5Aha1t1wJHLW32NK5w==

Because we did not supply a key to encrypt the data with, one was randomly generated for us. The Base64-encoded key is EAwE5Aha1t1wJHLW32NK5w==. If we already had a key that we wanted to use, we could have supplied it using the --key flag.

It's worth mentioning here that we are encrypting using AES, which employs a symmetric key algorithm. This means that the same key is used for both encryption and decryption. Because transmitting the key along with the encrypted message could be intercepted, the key should be transmitted by some out-of-band mechanism (e.g. written on a piece of paper) or the key should be encrypted using an asymmetric key algorithm.

Decrypting

Decryption works basically the same way, just pass in the --decrypt flag and supply the key. This time, the input is the encrypted file, and output is just written to the terminal.

$ ./pycrypto-aes-demo.py --decrypt --key EAwE5Aha1t1wJHLW32NK5w== < encrypted
Shhh... This is a secret.

Source Code