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.

176 Chapter 6 ■ Using Cryptography with Images

File Cryptography Using Fernet

In this section, we will explore image cryptography using Fernet, which is an

implementation of symmetric authenticated cryptography. Symmetric encryption,

which you may remember is synonymous for “same key,” means that we

use the same key to both encrypt and decrypt. You will begin by generating

a key and then saving it to a file. The generate_key() function will generate a

new Fernet key each time it is called; if you lose this key, you will not be able

to decrypt any data that you encrypted with this key. Therefore, once the key

gets generated, you will save it to disk. Each time you have the system generate

a key for you, you should save it; the alternative is to create your own key.

The Python code to generate the key and store it looks like the following:

key = Fernet.generate_key()

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

key_file.write(key)

To load the key file once it is stored, you can use the following Python code:

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

Once you have an encryption system and a key, you should be ready to

encrypt your message. Do not forget to encode your message; this will convert

the string to bytes suitable for encrypting. Your message assignment should

look like the following:

plaintext = "I have a secret I want to share but only if you have the

key.".encode()

From here, we are ready to start our encryption process:

f = Fernet(key)

ciphertext = f.encrypt(plaintext)

print (ciphertext)

Assuming you are playing along, you should have something similar to

Figure 6.5.

Figure 6.5: Python output for Fernet

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

Saved successfully!

Ooh no, something went wrong!