Image encryption and decryption using Pycrypto

user7500581 picture user7500581 · Feb 1, 2017 · Viewed 11k times · Source

How can I encrypt images using the Pycrypto python library? I found some text encrypting examples on internet, but I didn't find the same with images. Can anyone help me?

Answer

Kubuntuer82 picture Kubuntuer82 · Apr 25, 2018

It is just the same as encrypting or decrypting text.

Example

First import some modules:

from Crypto.Cipher import AES
from Crypto import Random

After that, let us generate a key and an initialisation vector.

key = Random.new().read(AES.block_size)
iv = Random.new().read(AES.block_size)

Encryption

Now the code below loads an input file input.jpg and encrypts it, and afterwards it saves the encrypted data on a file encrypted.enc. In this example, the AES block cipher is used with the CFB mode of operation.

input_file = open("input.jpg")
input_data = input_file.read()
input_file.close()

cfb_cipher = AES.new(key, AES.MODE_CFB, iv)
enc_data = cfb_cipher.encrypt(input_data)

enc_file = open("encrypted.enc", "w")
enc_file.write(enc_data)
enc_file.close()

Decryption

Finally, the code below loads the encrypted file encrypted.enc and decrypts it, and afterwards it saves the decrypted data on a file output.jpg.

enc_file2 = open("encrypted.enc")
enc_data2 = enc_file2.read()
enc_file2.close()

cfb_decipher = AES.new(key, AES.MODE_CFB, iv)
plain_data = cfb_decipher.decrypt(enc_data2)

output_file = open("output.jpg", "w")
output_file.write(plain_data)
output_file.close()

Note

For simplicity, the encryption and the decryption have been done in the same Python session, so the variables key and iv have been reused immediately, and to test this solution you have to do encryption and decryption in the same Python session. Of course, if you want to decrypt later in a separate session you will need to save key and iv and to reload them when you need to decrypt.

Testing the solution

Now you can open the output.jpg file and you should see an image which is identical to the one in input.jpg.