07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6 ■ Using Cryptography with Images 177

Next, we will load a file with plaintext data and then encrypt the data using

the encrypt() method. The file is then saved to storage:

filename = “sometextfile.txt”

f = Fernet(key)

with open(filename, "rb") as file:

# read all file data

file_data = file.read()

# encrypt data

encrypted_data = f.encrypt(file_data)

# write the encrypted file

with open(filename, "wb") as file:

file.write(encrypted_data)

The decryption process is almost identical, but we use the decrypt() function

of the Fernet object:

$filename = “sometextfile.txt”

f = Fernet(key)

with open(filename, "rb") as file:

# read the encrypted data

encrypted_data = file.read()

# decrypt data

decrypted_data = f.decrypt(encrypted_data)

# write the original file

with open(filename, "wb") as file:

file.write(decrypted_data)

Now that you have the concepts, you can wrap all these snippets up into

something a little more flexible. The following Python code accepts a key, a file,

and either a decryption or encryption flag:

from cryptography.fernet import Fernet

import os

def write_key():

# Generates a key and save it into a file

key = Fernet.generate_key()

with open("ch6.key", "wb") as key_file:

key_file.write(key)

def load_key():

#Loads the key from the current directory named 'ch6.key'

return open("ch6.key", "rb").read()

def encrypt(filename, key):

# encrypts the file and writes it using filename and key

f = Fernet(key)

with open(filename, "rb") as file:

# read all file data

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!