如何在不解密的情况下将加密图像显示为图像

how to display encrypted image as an image without decrypting it

#encrypting an image using AES
import binascii
from Crypto.Cipher import AES


def pad(s):
  return s + b"[=10=]" * (AES.block_size - len(s) % AES.block_size)

filename = 'path to input_image.jpg'
with open(filename, 'rb') as f:
  content = f.read()

#converting the jpg to hex, trimming whitespaces and padding.
content = binascii.hexlify(content)
binascii.a2b_hex(content.replace(' ', ''))
content = pad(content)

#16 byte key and IV
#thank you whosebug.com
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
ciphertext = obj.encrypt(content)

#is it right to try and convert the garbled text to hex?
ciphertext = binascii.hexlify(ciphertext)
print ciphertext

#decryption

obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
plaintext = obj2.decrypt(ciphertext)
#content =  content.encode('utf-8')
print plaintext
#the plaintext here matches the original hex input file as it should


with open('path to - AESimageDecrypted.txt', 'wb') as g:
   g.write(plaintext)

我的问题有两个, 1) 我将如何将基本上是十六进制字符串文本文件的加密文件(在 hexlify 之前是乱码)转换回图像? 我希望输出可以在任何查看器上以 jpg 格式查看。

我已经尝试了一些东西,遇到了 Pillow,但我似乎无法理解它是否可以做我想做的事。

如有任何帮助,我们将不胜感激。

PS:我也想用其他密码试试这个。所以我认为如果有人能帮助弄清楚这种理解是否正确,那将会很有帮助:

jpg -> 转为binary/hex -> 加密 -> 乱码输出 -> 转为bin/hex -> 转为jpg

2) 以上可能吗?应该将它们转换为十六进制还是二进制?

这里的问题是如何在不解密的情况下将加密图像显示为图像。

加密内容不是图像,不能明确表示为图像。最好的办法是将其视为位图,即每个二进制值代表某个坐标处某种颜色的强度。

将数据视为每个像素 3 个字节似乎合乎逻辑:RGB RGB RGB...

图像是二维的,加密数据只是字节列表。同样,有几个选项是有效的。假设它是一个正方形图像(NxN 像素)。

要创建图像,我会使用 PIL / Pillow:

from PIL import Image

# calculate sizes
num_bytes = len(cyphertext)
num_pixels = int((num_bytes+2)/3)                     # 3 bytes per pixel
W = H = int(math.ceil(num_pixels ** 0.5))             # W=H, such that everything fits in

# fill the image with zeros, because probably len(imagedata) < needed W*H*3
imagedata = cyphertext + '[=10=]' * (W*H*3 - len(cyphertext))

image = Image.fromstring('RGB', (W, H), imagedata)         # create image
image.save('C:\Temp\image.bmp')                          # save to a file

顺便说一句,这完全可以用任何字节串来完成,而不仅仅是加密图像。