How to Encrypt and Decrypt Data in Python

09/16/2021

Contents

In this article, you will learn how to encrypt and decrypt data in Python.

Encrypt and decrypt data

Python provides several libraries for encryption and decryption of data. One of the most popular libraries for encryption and decryption is the “cryptography” library.

Here’s an example of how to use the “cryptography” library to encrypt and decrypt data in Python:

from cryptography.fernet import Fernet

# generate a key
key = Fernet.generate_key()

# create a Fernet object with the key
fernet = Fernet(key)

# message to encrypt
message = b"Hello, World!"

# encrypt the message
encrypted_message = fernet.encrypt(message)

# print the encrypted message
print(encrypted_message)

# decrypt the message
decrypted_message = fernet.decrypt(encrypted_message)

# print the decrypted message
print(decrypted_message)

In this example, we first generate a key using the Fernet.generate_key() method. We then create a Fernet object with the key. We can then use the encrypt() method of the Fernet object to encrypt a message. Finally, we can use the decrypt() method of the Fernet object to decrypt the message.

Note that the message must be converted to bytes before encryption (using the b prefix). The encrypted message and decrypted message are also in bytes format, so we may need to decode them into strings using the decode() method.

Also, it’s important to keep the key secure as it’s needed to decrypt the message.