

Initializing the Fernet class with that key: # initialize the Fernet classĮncrypting the message: # encrypt the messageį.encrypt() method encrypts the data passed. Since strings have the type of str in Python, we need to encode them and convert them to bytes to be suitable for encryption, the encode() method encodes that string using the utf-8 codec.

Some message: message = "some secret message".encode() Let's load that key: # load the previously generated key Generating and writing the key to a file: # generate and write a new key Now that we know how to generate, save and load the key, let's start by encrypting string objects, just to make you familiar with it first. Return open("key.key", "rb").read() Text Encryption Loads the key from the current directory named `key.key` Since this key is unique, we won't be generating the key each time we encrypt anything, so we need a function to load that key for us: def load_key():

If you lose the key, you will no longer be able to decrypt data that was encrypted with this key. The Fernet.generate_key() function generates a fresh fernet key, you really need to keep this in a safe place. Open up a new Python file, and let's get started: from cryptography.fernet import Fernet Generating the Keyįernet is an implementation of symmetric authenticated cryptography let's start by generating that key and writing it to a file: def write_key(): Let's start off by installing cryptography: pip3 install cryptography RELATED: How to Extract and Decrypt Chrome Cookies in Python. In encryption, you can retrieve the original data once you have the key, wherein hashing functions, you cannot that's why they're called one-way encryption. Note: It is important to understand the difference between encryption and hashing algorithms. The library we gonna use is built on top of the AES algorithm. There are a lot of encryption algorithms out there. We will be using symmetric encryption, which means the same key we used to encrypt data, is also usable for decryption. In this tutorial, you will learn how to use Python to encrypt files or any byte object (also string objects) using the cryptography library. It is critically important because it allows you to securely protect data that you don't want anyone to see or access. Disclosure: This post may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.Įncryption is the process of encoding a piece of information in such a way that only authorized parties can access it.
