I am trying to test create a simple cipher that xor key with a bitmap image.
import os, io, hashlib
from PIL import Image
from array import array
from itertools import cycle
key = "aaaabbbb"
def generate_keys(key):
round_keys = hashlib.md5(key).digest()
return bytearray(round_keys)
def readimage(path):
with open(path, "rb") as f:
return bytearray(f.read())
def generate_output_image(input_image, filename_out):
output_image = Image.open(io.BytesIO(input_image))
output_image.save(filename_out)
def xor(x,y):
return [ a ^ b for a,b in zip(x,cycle(y))]
round_keys = generate_keys(key)
input_image = readimage("lena512.bmp")
encrypted_image = xor(input_image, round_keys)
generate_output_image(encrypted_image, "lena_encrypted.bmp")
input_image = readimage("lena_encrypted.bmp");
decrypted_image = xor(input_image, round_keys)
generate_output_image(decrypted_image, "lena_decrypted.bmp")
But I'm getting the following error when I run the script:
Traceback (most recent call last):
File "test.py", line 26, in <module>
generate_output_image(encrypted_image, "lena_encrypted.bmp")
File "test.py", line 17, in generate_output_image
output_image = Image.open(io.BytesIO(input_image))
TypeError: 'list' does not have the buffer interface
How do I convert the byte array back into bitmap image? Any help would be appreciated thanks.
xorfunction returns a list, so you can't passencrypted_imageanddecrypted_imageas an argument toio.BytesIO(). Maybe changing thexorfunction toreturn bytearray([ a ^ b for a,b in zip(x,cycle(y))])could help.return x[:54] + bytearray([a^b for a, b in zip(x[54:], cycle(y))])in thexorfunction. The actual offset may differ though, as there are different versions of BMP.