07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

172 Chapter 6 ■ Using Cryptography with Images

In the following example and the subsequent ones in this chapter, we will be

encrypting the original image and then saving it with an e in front of the name.

When we decrypt the image, we save it with a d in front of the name. The reason

we’re doing this is to be able to compare the original image with the decrypted

image to see if there is any apparent data loss.

Figure 6.1 shows the original image we will use. Feel free to create your own

for this exercise. It is a fairly small file, which is fine until we get to the end of

the chapter. For hiding blob data, you may need a much larger file. Time for a

little code.

Figure 6.1: Original ch6_secret_image.jpg file

print('The program is looking for a file named: ch6_secret_image.jpg')

fo = open("Chapter6\ch6_secret_image.jpg", "rb")

image = fo.read()

fo.close()

print()

print("The secret key is 42.")

image = bytearray(image)

key = 42

for index, value in enumerate(image):

image[index] = value^key

print()

print('The image has been encrypted. Review e_ch6_secret_image.jpg')

fo = open("Chapter6\e_ch6_secret_image.jpg", "wb")

fo.write(image)

fo.close()

image = bytearray(image)

for index, value in enumerate(image):

image[index] = key^value

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

Saved successfully!

Ooh no, something went wrong!