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.

182 Chapter 6 ■ Using Cryptography with Images

The next step is to file read the plane.bmp image; we will store the binary file

into a variable named byteblock:

>>> with open("plane.bmp", "rb") as f:

>>> byteblock = f.read()

The byteblock will need to be in multiples of 16 bytes. If not, it will result in

an error that states: Input strings must be a multiple of 16 in length. The byteblock

value will depend on the size of the image. To examine the byteblock, you can

examine the length of the variable:

>>> print (len(byteblock))

261654

Since the input string must be a multiple of 16, we will need to examine how

many bytes are left over when we take the modulo. In this case, it is 6:

>>> print (len(byteblock)%16)

6

Our goal is now to move the bytes that are multiples of 16 into a variable that

we can use to isolate the block while subtracting the overflow. Here, we will

store the value in byteblock_trimmed:

byteblock_trimmed = byteblock[64:-6]

>>> print (len(byteblock_trimmed))

261584

>>> print (len(byteblock_trimmed)%16)

0

To ensure that the image can be encrypted and decrypted without a data loss,

you will need to combine the two sets of byte blocks:

# byteblock_trimmed must not have extra bytes or an error will occur

ciphertext = cipher.encrypt(byteblock_trimmed)

ciphertext = byteblock[0:64] + ciphertext + byteblock[-6:]

Now, all that is needed for the image is to save it using the ciphertext:

with open("plane_ecb.jpg", "w") as f:

f.write(ciphertext)

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

Saved successfully!

Ooh no, something went wrong!