Two Easy Ways to Encrypt and Decrypt Python Strings

Today I gave a service consultant access to one of my AWS servers. I have a few files on the server that I was reluctant to share with the service consultant because these files contain sensitive personal data. Python is my default way to solve these types of problems. Naturally, I wondered how to encrypt this data using Python — and decrypt it again after the consultant is done? In this article, I’ll share my learnings! πŸ‘‡

πŸ” Question: Given a Python string. How to encrypt the Python string using a password or otherwise and decrypt the encrypted phrase to obtain the initial cleartext again?

There are several ways to encrypt and decrypt Python strings. I decided to share only the top two ways (my personal preference is Method 1):

Method 1: Cryptography Library Fernet

To encrypt and decrypt a Python string, install and import the cryptography library, generate a Fernet key, and create a Fernet object with it. You can then encrypt the string using the Fernet.encrypt() method and decrypt the encrypted string using the Fernet.decrypt() method.

If you haven’t already, you must first install the cryptography library using the pip install cryptography shell command or variants thereof. πŸ‘‰ See more here.

Here’s a minimal example where I’ve highlighted the encryption and decryption calls:

# Import the cryptography library
from cryptography.fernet import Fernet

# Generate a Fernet key
key = Fernet.generate_key()

# Create a Fernet object with that key
f = Fernet(key)

# Input string to be encrypted
input_string = "Hello World!"

# Encrypt the string
encrypted_string = f.encrypt(input_string.encode())

# Decrypt the encrypted string
decrypted_string = f.decrypt(encrypted_string)

# Print the original and decrypted strings
print("Original String:", input_string)
print("Decrypted String:", decrypted_string.decode())

This small script first imports the Fernet class from the cryptography library that provides high-level cryptographic primitives and algorithms such as

  • symmetric encryption,
  • public-key encryption,
  • hashing, and
  • digital signatures.

A Fernet key is then generated and used to create a Fernet object. The input string to be encrypted is then provided as an argument to the encrypt() method of the Fernet object. This method encrypts the string using the Fernet key and returns an encrypted string.

The encrypted string is then provided as an argument to the decrypt() method of the Fernet object. This method decrypts the encrypted string using the Fernet key and returns a decrypted string.

Finally, the original string and the decrypted string are printed to the console.

The output is as follows:

Original String: Hello World!
Decrypted String: Hello World!

Try it yourself in our Jupyter Notebook:

Method 2: PyCrypto Cipher

Install and import the PyCrypto library to encrypt and decrypt a string. As preparation, you need to make sure to pad the input string to 32 characters using string.rjust(32) to make sure it is the correct length. Then, define a secret key, i.e., a “password”. Finally, encrypt the string using the AES algorithm, which is a type of symmetric-key encryption.

You can then decrypt the encrypted string again by using the same key.

Here’s a small example:

# Import the PyCrypto library
import Crypto

# Input string to be encrypted (padding to adjust length)
input_string = "Hello World!".rjust(32)

# Secret key (pw)
key = b'1234567890123456'

# Encrypt the string
cipher = Crypto.Cipher.AES.new(key)
encrypted_string = cipher.encrypt(input_string.encode())

# Decrypt the encrypted string
decrypted_string = cipher.decrypt(encrypted_string)

# Print the original and decrypted strings
print("Original String:", input_string)
print("Decrypted String:", decrypted_string.decode())

This code imports the PyCrypto library and uses it to encrypt and decrypt a string.

The input string is "Hello World!", which is padded to 32 characters to make sure it is the correct length.

Then, a secret key (password) is defined.

The string is encrypted using the AES algorithm, which is a type of symmetric-key encryption.

The encrypted string is then decrypted using the same key and the original and decrypted strings are printed. Here’s the output:

Original String:                     Hello World!
Decrypted String:                     Hello World!

Try it yourself in our Jupyter Notebook:

Thanks for Visiting! β™₯️

To keep learning Python in practical coding projects, check out our free email academy — we have cheat sheets too! πŸ”₯