2016-10-08 27 views
0
#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)如何將我去變換它基本上是十六進制的文本文件中的加密文件(其hexlify之前亂碼)字符串,回到圖像? 我希望輸出可以在任何瀏覽器上以JPG格式顯示。如何顯示加密圖像作爲圖像而不解密它

我已經嘗試了幾件事,碰到枕頭,除了我似乎無法理解,如果它可以做我想做的事情。

任何幫助,將不勝感激謝謝。

PS:我想用其他密碼試一下。所以我覺得這是有益的,如果有人能幫助清除掉,如果這種認識是正確的:

JPG - >轉換爲二進制/六角 - >加密 - >亂碼輸出 - >轉換爲斌/六角 - >轉換爲jpg

2)是以上可能嗎?並且它們應該轉換爲十六進制還是二進制文件?

+0

要恢復hexlify +加密,應用解密+ unhexlify? – zvone

+0

@zvone是否有辦法以 hexlify + encrypt - >轉換爲jpg? 爲了更清楚,我想知道是否有辦法將亂碼加密,並將其轉換爲圖像? – baconSoda

+0

當然有一種方法,但我仍然不明白問題是什麼。首先,你爲什麼將JPG轉換爲十六進制?其次,它看起來像除了將十六進制轉換爲原始數據之外,您已擁有一切。你有這個:http://stackoverflow.com/q/9641440/389289 – zvone

回答

2

這裏的問題是如何在不解密的情況下將加密圖像顯示爲圖像。

加密內容不是圖像,不能明確表示爲圖像。可以做的最好的事情就是將其視爲位圖,即每個二進制值表示某個座標處某種顏色的強度。

這似乎是合乎邏輯數據視爲每像素3個字節:RGB三原色RGB ...

圖像是二維和加密的數據僅僅是字節的列表。再次,幾個選項是有效的。假設它是一個正方形圖像(N×N像素)。

創造的形象,我會用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 + '\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 

順便說一句,這可以用字節絕對任意字符串,而不僅僅是加密圖像來完成。

+0

這有助於解決問題。我檢查了DES和AES之間的差異。我想檢查一下是否與caeser密碼相同。位圖是否背叛任何類型的數據。 謝謝你一噸zvone。 – baconSoda