We can encrypt and decrypt an image easily using the PyCryptodome module in Python. In this article, we would use the AES encryption algorithm in the CBC mode to encrypt an image. We would generate the key and the Initialization Vector (IV) randomly. And then, we would use the AES algorithm to encrypt and decrypt an image using the key and the IV.
We are here encrypting an image named “arrow.png” We are using the AES encryption algorithm with a block size of 16 bytes and the key size is also 16 bytes. We are firstly generating the key and the IV randomly.
def getKey(keysize): key = os.urandom(keysize) return key def getIV(blocksize): iv = os.urandom(blocksize) return iv
The os.urandom() function generates a cryptographically secure pseudorandom number that can be used for cryptographic purposes.
Now, we would encrypt the image using the generated key and the IV.
KEYSIZE = 16 BLOCKSIZE = 16 filename = "arrow.png" key = getKey(KEYSIZE) iv = getIV(BLOCKSIZE) encrypted_filename = encrypt_image(filename, key, iv) decrypted_filename = decrypt_image(encrypted_filename, key, iv)
The encrypt_image() method looks like the following:
def encrypt_image(filename, key, iv): BLOCKSIZE = 16 encrypted_filename = "encrypted_" + filename with open(filename, "rb") as file1: data = file1.read() cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(data, BLOCKSIZE)) with open(encrypted_filename, "wb") as file2: file2.write(ciphertext) return encrypted_filename
0 Comments