How to Encrypt and Decrypt Data in Python using Cryptography Library (2024)

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:

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:

  1. 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.

  2. 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 the generate_key() method. It emphasizes the importance of securely storing this key, as losing it would result in the inability to decrypt previously encrypted data.

  3. 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.

  4. 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 the encrypt() method. The result is a securely encrypted message.

  5. Decrypting a Message: To decrypt a message, the loaded key is again essential. The decrypt() method of the Fernet class is used to reverse the encryption process and obtain the original message.

  6. 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.

How to Encrypt and Decrypt Data in Python using Cryptography Library (2024)

FAQs

How to encrypt and decrypt data in Python using cryptography library? ›

Steps:
  1. Import Fernet.
  2. Then generate an encryption key, that can be used for encryption and decryption.
  3. Convert the string to a byte string, so that it can be encrypted.
  4. Instance the Fernet class with the encryption key.
  5. Then encrypt the string with the Fernet instance.
Jun 8, 2022

How to encrypt and decrypt in cryptography? ›

Public key encryption uses a pair of complementary keys (a public key and a private key) to encrypt and decrypt messages, as shown in the following figure. The two keys are mathematically related such that a message encoded with one key can only be decoded with the other key.

Which algorithm is best for encryption and decryption in Python? ›

Some of the most common and widely used algorithms are AES, RSA, and Fernet. AES is a symmetric algorithm that uses the same key for encryption and decryption, and it is fast and efficient for large data.

How to decrypt the encrypted data in Python? ›

Decrypt the encrypted file
  1. Initialize the Fernet object and store it in the fernet variable.
  2. Read the encrypted file.
  3. Decrypt the file and store it into an object.
  4. Then write the decrypted data into the same file nba. csv.
Jun 3, 2022

How to encrypt data using cryptography? ›

Encryption uses complex mathematical algorithms and digital keys to encrypt data. An encryption algorithm (cipher) and an encryption key encode data into ciphertext. Once the ciphertext is transmitted to the recipient, the same or different key (cipher) is used to decode the ciphertext back into the original value.

How to encrypt and decrypt data? ›

With public-key/asymmetric encryption, the sender uses a publicly known key to encrypt the data. The receiver has the private key that forms the other half of the public/private key pair. The receiver can decrypt the data by using the private key in combination with the public key.

How to encrypt data in Python? ›

In order to encrypt data from the above key, you must use the encrypt method. encrypted_data = f. encrypt(b"This message is being encrypted and cannot be seen!") And that's it, the above sentence has been encrypted.

What is the algorithm to encrypt and decrypt data? ›

Four common algorithms, used by OpenEdge, are:
  • DES — Data Encryption Standard.
  • DES3 — Triple DES.
  • AES — Advanced Encryption Standard.
  • RC4 — Also known as ARC4.

How to use cryptography in Python? ›

Algorithm for Cryptography with Python
  1. Make a list of all the alphabet.
  2. Create a function that takes the text and a number as a parameter.
  3. Move through each element.
  4. If it's a space add it to the new list as it is.
  5. Take out the position of the character it should replace with.
  6. Join.
  7. Display the encrypted text.

Which Python library is best for encryption? ›

Best Python Cryptography Libraries for Secure Data Encryption
  • Table of Contents.
  • PyCryptodome. A self-contained cryptographic library, PyCryptodome is a popular choice for developers who want to implement encryption algorithms in Python. ...
  • Cryptography. ...
  • PyNaCl. ...
  • PyOpenSSL. ...
  • Fernet. ...
  • Keyczar. ...
  • M2Crypto.
Apr 22, 2023

What is encryption and decryption with example in Python? ›

It is a process of converting information into some form of a code to hide its true content. The only way to access the file information then is to decrypt it. The process of encryption/decryption is called cryptography. Let's see how we can encrypt and decrypt some of our files using Python.

How do I encrypt and decrypt using AES? ›

AES uses 128-, 192- or 256-bit keys to encrypt and decrypt data. AES is a symmetric encryption algorithm and a block cipher. The former means that it uses the same key to encrypt and decrypt data. The sender and the receiver must both know -- and use -- the same secret encryption key.

How do you decrypt AES file in Python? ›

The file will be encrypted or in other words, it is changed into a non readable form. To decrypt the file, run the python file again, and this time choose decrypte(D). Enter the full name of the encrypted file and enter the same password that was used for encryption. You will see that the file is now decrypted.

What is cryptography library in Python? ›

cryptography is an actively developed library that provides cryptographic recipes and primitives. It supports Python 2.6-2.7, Python 3.3+, and PyPy. cryptography is divided into two layers of recipes and hazardous materials (hazmat).

Which Python module can be used to encrypt data? ›

PyNaCl, pronounced as „Py-Na-Cl,” is a Python binding for the renowned NaCl (Networking and Cryptography) library. It delivers a simple interface for implementing secure communication using public-key cryptography. With a focus on ease-of-use, PyNaCl provides encryption, decryption, signing, and verification features.

What is the data encryption standard library in Python? ›

DES (Data Encryption Standard) is a symmetric block cipher standardized in FIPS 46-3 (now withdrawn). It has a fixed data block size of 8 bytes. Its keys are 64 bits long, even though 8 bits were used for integrity (now they are ignored) and do not contribute to security.

Top Articles
Latest Posts
Article information

Author: Arielle Torp

Last Updated:

Views: 6450

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.