Symmetric encryption with Python using Fernet (AES)




The third-party cryptography package in Python provides tools to encrypt byte using a key. The same key that encrypts is used to decrypt, which is why they call it symmetric encryption. Fernet is an encryption spec that utilizes AES-128 under the hood with HMAC and some other additions. If you need to encrypt and decrypt some data using Python, this is a very easy way to do it.

Install cryptography package

Check out the cryptography documentation for more details, but all you need to do is run pip install:

python -m pip install cryptography

Encrypt and decrypt

The example below demonstrates how to:

  • Generate a key with static method Fernet.generate_key()
  • Instantiate an instance of the cryptography.fernet.Fernet class
  • Encrypt data with encrypt() method
  • Decrypt data with decrypt() method

Be sure to store the key and keep it secure. You can not generate the same key again and if you do not save it after generating it, you will lose it forever. Also keep it secure since anyone who has access to it can decrypt your data.

# pip install cryptography
from cryptography.fernet import Fernet

Important things remember:

- Save the key!
- Protect the key!
- Only share the key with people who should have access to the data!
- Only share the key using secure methods! (if you need to share it at all)

# Encrypt
key = Fernet.generate_key()  # Keep this secret!
print(type(key))  # bytes
print(key)  # base64 encoded 32 bytes
my_fernet = Fernet(key)
encrypted_bytes = my_fernet.encrypt(b"Hello, world!")

# Decrypt
clear_text = my_fernet.decrypt(encrypted_bytes)

Here is the output from an example run in the interpreter:

$ python
Python 3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from cryptography.fernet import Fernet
>>> # Encrypt
>>> key = Fernet.generate_key()  # Need a key first
>>> print(type(key))  # bytes
<class 'bytes'>
>>> print(key)  # DO NOT SHARE THIS NORMALLY
>>> my_fernet = Fernet(key)
>>> encrypted_bytes = my_fernet.encrypt(b"Hello, world!")
>>> print(encrypted_bytes)
>>> # Decrypt
>>> clear_text = my_fernet.decrypt(encrypted_bytes)
>>> print(clear_text)
b'Hello, world!'


After following this guide you should know how to symmetrically encrypt data in Python using the Fernet (AES) encryption.