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 179

if encrypt_ and decrypt_:

raise TypeError("Please specify whether you want to encrypt the

file or decrypt it.")

elif encrypt_:

encrypt(file, key)

elif decrypt_:

decrypt(file, key)

else:

raise TypeError("Please specify whether you want to encrypt the

file or decrypt it.")

Image Cryptography Using Fernet

Using our previous example, you can now write a solution that will allow you

to specify the original image and change the encrypted file to a specific name;

in this case, the ch6_secret_image.jpg file will be encrypted as e_ch6_secret_

im age.jpg and then immediately decrypted to d_ch6_secret_image.jpg. The

image resolution between the original file and the decrypted file is identical

as the Fernet algorithm operates on the file itself and does not alter the pixels

of the image.

In the following example, I removed the reading and writing key since the

encryption and decryption are happening in the same process. The encryption

process here is not specific to just images and can be used on a variety of data

types. The takeaway from this program should be the full encryption at the file

level and not the pixel level:

def encrypt(filename, newfile, key):

"""

Given a plain image (str), the new file name, and key (bytes), it

encrypts the file and write it

"""

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(newfile, "wb") as file:

file.write(encrypted_data)

def decrypt(filename, newfile, key):

"""

Given a encrypted file (str), the new file name, and key (bytes), it

decrypts the file and write it

"""

f = Fernet(key)

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

Saved successfully!

Ooh no, something went wrong!