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 185

Figure 6.10: ECB security issue

Exploring a Simple CBC Mode Example

Now that you understand how to encrypt and decrypt using ECB block mode,

we will examine the CBC mode. One important difference between the two

modes is the use of an initialization vector (IV) and the specification of the block

mode, which in this case is AES.MODE _ CBC:

from Crypto.Cipher import AES

iv = "1111222233334444"

key = "aaaabbbbccccdddd"

cipher = AES.new(key, AES.MODE_CBC, iv)

# encrypt using CBC mode

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

byteblock = f.read()

pad = len(byteblock)%16 * -1

byteblock_trimmed = byteblock[64:pad]

ciphertext = cipher.encrypt(byteblock_trimmed)

ciphertext = byteblock[0:64] + ciphertext + byteblock[pad:]

with open("plane_cbc.bmp", "w") as f:

f.write(ciphertext)

# decrypt using the reverse process

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

Saved successfully!

Ooh no, something went wrong!