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.
Related:
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 Fernetdef 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.
Note: You need to keep this key in a safe place. If you lose the key, you won't be able to decrypt the data that was encrypted with this 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 Fernetdef 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 Fernetdef 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
As an enthusiast deeply versed in Python development and cryptography, I can confidently delve into the intricacies of the tutorial you've provided, showcasing my firsthand expertise in the subject matter.
The tutorial, dated May 4, 2020, demonstrates how to perform encryption and decryption of data in Python using the cryptography library. This is a crucial skill for any developer or security-conscious individual who wants to protect sensitive information.
The tutorial begins by emphasizing the importance of encryption as a means of encoding information to restrict access to authorized parties only. It specifically focuses on symmetric encryption, where the same key is used for both encryption and decryption processes. The cryptography library employed in this tutorial is built on the Advanced Encryption Standard (AES) algorithm, a widely recognized and secure encryption standard.
Let's break down the key concepts covered in the tutorial:
-
Installation of Cryptography Library: To start, the tutorial advises installing the cryptography library using the command
pip3 install cryptography
. This library is crucial for implementing encryption and decryption in Python. -
Key Generation and Storage: The tutorial then proceeds to generate a key using the
Fernet
class within the cryptography library. The generated key is saved in a file named "secret.key" using thegenerate_key()
method. It emphasizes the importance of securely storing this key, as losing it would result in the inability to decrypt previously encrypted data. -
Loading the Key: After generating the key, the tutorial demonstrates the need to load the key before performing encryption or decryption. The
load_key()
function reads the key from the "secret.key" file. -
Encrypting a Message: The encryption process involves encoding the message, initializing the
Fernet
class with the loaded key, and then passing the encoded message to theencrypt()
method. The result is a securely encrypted message. -
Decrypting a Message: To decrypt a message, the loaded key is again essential. The
decrypt()
method of theFernet
class is used to reverse the encryption process and obtain the original message. -
Full Code Example: The tutorial provides a complete Python script that encapsulates the entire process of key generation, loading, message encryption, and decryption. The script is well-structured and serves as a practical reference for anyone looking to implement encryption in Python.
In conclusion, the tutorial effectively guides the reader through the process of encrypting and decrypting messages in Python using the cryptography library, employing symmetric encryption with the AES algorithm. The provided code examples, coupled with explanations, make it a valuable resource for developers seeking to enhance the security of their applications.