3.11 ENCRYPTING AN IMAGE
EXERCISE 3.11: ENCRYPTING AN IMAGE
Encrypt the image that you encrypted with ECB mode earlier. What does the encrypted image look like now? Don’t forget to leave the first 54 bytes untouched!
I created the following bmp file using GIMP:
Then I wrote the following code to encrypt the above bmp file in both ECB and CBC mode.
# ex3_11.py
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
= "top-secret.bmp"
ifile
= os.urandom(16) # we are using AES-128
key = os.urandom(16)
iv
# first encrypt using ECB
def encryptUsingECB():
= "top-secret-ecb.bmp"
ofile with open(ifile, "rb") as reader:
with open(ofile, "wb") as writer:
= reader.read()
image_data = image_data[:54], image_data[54:]
header, body
# now encrypt the body
= Cipher(
encryptor =algorithms.AES(key),
algorithm=modes.ECB(),
mode=default_backend()
backend
).encryptor()
# padding the body.
+= b"\x00"*(16 - (len(body)%16))
body
+ encryptor.update(body))
writer.write(header
# then encrypt using CBC
def encryptUsingCBC():
= "top-secret-cbc.bmp"
ofile with open(ifile, "rb") as reader:
with open(ofile, "wb") as writer:
= reader.read()
image_data = image_data[:54], image_data[54:]
header, body
# now encrypt the body
= Cipher(
encryptor =algorithms.AES(key),
algorithm=modes.CBC(iv),
mode=default_backend()
backend
).encryptor()
# padding the body.
+= b"\x00"*(16 - (len(body)%16))
body
+ encryptor.update(body))
writer.write(header
if __name__ == '__main__':
encryptUsingECB() encryptUsingCBC()
Running the above code will generate two files as shown below:
The following shows the encrypted versions of the above bmp file: