Cryptography with Python using Fernet

Harry Schiller

September 18th, 2021

462 words

3 min read

Let us look at how to encrypt text and files using Python. For this we are going to be using Fernet which is a part of python's cryptography package

So let us get right into it

Ok firstly we need to downloaded the cryptography package using pip

On Windows:

pip install cryptography

On Linux/macOS:

pip3 install cryptography

After we have executed the command in the terminal, we are ready to start coding.

You might want to use your favourite code editor (vscode, sublime text, atom etc...) or any IDE.

Now let us first import the required library

from cryptography.fernet import Fernet

Then we are going to define a function that will write the key to a file

def write_key():
    key = Fernet.generate_key() # Generates the key
    with open("key.key", "wb") as key_file: # Opens the file the key is to be written to
        key_file.write(key) # Writes the key

We will also write down a function that will help with reading and loading the key into a variable

def load_key():
    return open("key.key", "rb").read() #Opens the file, reads and returns the key stored in the file

Now let us take the message we are going to encode as user input and encode it to bytes because that is how fernet works

message = input("Message: ").encode() # Takes the message as user input and encodes it

Now we need to write are top secret key to the key file. We are going to run this only once and then comment the line out because we don't want it to write a new key down every time the code is run.

write_key() # Writes the key to the key file

Now we need to load the key i.e. read the key from the key file and store it in a variable called as key though you can name it whatever you want

key = load_key() # Loads the key and stores it in a variable

Now we need to initialize the fernet object by passing in the key we just loaded

f = Fernet(key)

Now let us get to the main part, encrypting the message Also let us print it out

encrypted_message = f.encrypt(message)
print(encrypted_message)

You see that the encrypted message cannot be understood by anyone so it is safe now and will be the same unless decrypted with the same key

To decrypt, it is a very similar process

decrypted_message = f.decrypt(encrypred_message)
print(decrypted_message)

So here, first the message is encrypted and is printed out and then we decrypt it and print it in the next line. If the initial message and the decrypted message are the exact same, our code has worked!!!