How to Encrypt and Decrypt Data in Python using Cryptography Library

In this tutorial you will learn how to encrypt and decrypt data, e.g. a string of text using the cryptography library in Python.

Encryption is the process of encoding information in such a way that only authorized parties can access it. It allows us to securely protect data which we don’t want just anyone to see or access.

In this example, we will be using symmetric encryption, which means the same key we used to encrypt data, is also usable for decryption.

The cryptography library that we use here is built on top of AES algorithm.

Encrypt Data in Python

First, we need to install the cryptography library:

pip3 install cryptography

From the cryptography library, we need to import Fernet and start generating a key - this key is required for symmetric encryption/decryption.

Generate Key

To generate a key, we call the generate_key() method:

from cryptography.fernet import Fernet

def generate_key():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

We only need to execute the above method once to generate a key.

Load the Key

Once we have generated a key, we need to load the key in our method in order to encrypt data:

def load_key():
    """
    Loads the key named `secret.key` from the current directory.
    """
    return open("secret.key", "rb").read()

Encrypt a Message

Now, we are ready to encrypt a message. This is a three step process:

  • 1 - encode the message
  • 2 - initialize the Fernet class
  • 3 - pass the encoded message to encrypt() method

encode the message:

message = "message I want to encrypt".encode()

initialize the Fernet class:

f = Fernet(key)

encrypt the message:

encrypted_message = f.encrypt(message)

Full Code Example

Below is a full working example of encrypting a message in python:

from cryptography.fernet import Fernet

def generate_key():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

def load_key():
    """
    Load the previously generated key
    """
    return open("secret.key", "rb").read()

def encrypt_message(message):
    """
    Encrypts a message
    """
    key = load_key()
    encoded_message = message.encode()
    f = Fernet(key)
    encrypted_message = f.encrypt(encoded_message)

    print(encrypted_message)

if __name__ == "__main__":
    encrypt_message("encrypt this message")

Output:

b'gAAAAABesCUIAcM8M-_Ik_-I1-JD0AzLZU8A8-AJITYCp9Mc33JaHMnYmRedtwC8LLcYk9zpTqYSaDaqFUgfz-tcHZ2TQjAgKKnIWJ2ae9GDoea6tw8XeJ4='

Decrypt Data in Python

To decrypt the message, we just call the decrypt() method from the Fernet library. Remember, we also need to load the key as well, because the key is needed to decrypt the message.

from cryptography.fernet import Fernet

def load_key():
    """
    Load the previously generated key
    """
    return open("secret.key", "rb").read()

def decrypt_message(encrypted_message):
    """
    Decrypts an encrypted message
    """
    key = load_key()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_message)

    print(decrypted_message.decode())

if __name__ == "__main__":
    decrypt_message(b'gAAAAABesCUIAcM8M-_Ik_-I1-JD0AzLZU8A8-AJITYCp9Mc33JaHMnYmRedtwC8LLcYk9zpTqYSaDaqFUgfz-tcHZ2TQjAgKKnIWJ2ae9GDoea6tw8XeJ4=')

Output:

encrypt this message