#encrypting an image using AES
import binascii
from Crypto.Cipher import AES
def pad(s):
return s + b"\0" * (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 stackoverflow.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)如何将加密的文件(在十六进制之前被混淆)(基本上是一个十六进制字符串文本文件)转换回图像?我希望输出可以作为一个jpg在任何观众上查看。
我尝试了一些事情,偶然发现枕头,除了我似乎无法理解它是否能做我想做的事。
如有任何帮助,将不胜感激。
PS:我也想和其他密码一起试试这个。因此,我认为如果这一理解是正确的,任何人都能帮助澄清,这将是有帮助的:
jpg ->转换为二进制/十六进制->加密->错误输出->转换为bin/十六进制->转换为jpg
( 2)是否可能出现上述情况?他们应该被转换成妖术还是垃圾桶?
发布于 2016-10-08 21:51:11
这里的问题是如何在不解密的情况下将加密的图像显示为图像。
加密的内容不是图像,不能明确表示为图像。最好的方法就是把它当作位图来处理,即每个二进制值表示某种颜色在某个坐标下的强度。
将数据视为每像素3个字节似乎是合乎逻辑的: RGB .
图像是2D的,加密的数据只是一个字节列表。同样,有几个选项是有效的。假设它是一个方形图像(NxN像素)。
要创建映像,我将使用PIL /枕头
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 + '\0' * (W*H*3 - len(cyphertext))
image = Image.fromstring('RGB', (W, H), imagedata) # create image
image.save('C:\\Temp\\image.bmp') # save to a file
顺便说一句,这完全可以用任何字节字符串来完成,而不仅仅是加密的图像。
https://stackoverflow.com/questions/39936706
复制相似问题