【发布时间】:2018-12-09 22:26:03
【问题描述】:
我正在尝试创建一个简单的密码,该密码与位图图像进行异或密钥。
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")
但是当我运行脚本时出现以下错误:
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
如何将字节数组转换回位图图像? 任何帮助将不胜感激。
【问题讨论】:
-
您的
xor函数返回一个列表,因此您不能将encrypted_image和decrypted_image作为参数传递给io.BytesIO()。也许将xor函数更改为return bytearray([ a ^ b for a,b in zip(x,cycle(y))])可能会有所帮助。 -
感谢 myrmica。当我将解密的字节数组转换为位图图像时,您的建议有所帮助。但是,我无法将加密的字节数组转换为位图图像。我希望得到一张白噪声图像,并且能够将白噪声图像解密回原始位图。知道该怎么做吗?
-
BMP 文件的标头包含您不得使用密码修改的信息。
xor函数中应该有类似return x[:54] + bytearray([a^b for a, b in zip(x[54:], cycle(y))])的内容。但实际偏移量可能会有所不同,因为有different versions of BMP。
标签: python arrays bitmapimage