I met a question when I encrypt a PNG image file. I tried to encrypt the file by AES. But when I decrypted it by generator-like methods, it does not work. I thought it should have too many EOF(0x1A in hex). here is my result: my result picturehere is my code:
import sys
from io import BytesIO
import cStringIO
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
class prpcrypt():
def __init__(self, key):
self.key = key
self.mode = AES.MODE_CFB
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
length = 16
count = len(text)
if(count % length != 0):
add = length - (count % length)
else:
add = 0
text = text + ('\0' * add)
self.ciphertext = cryptor.encrypt(text)
return self.ciphertext
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
plain_text = cryptor.decrypt(text)
return plain_text.rstrip('\0')
if __name__ == '__main__':
with open('nb.png', 'r+') as f:
fd = cStringIO.StringIO(f.read())
fd.seek(0)
pc = prpcrypt('keyskeyskeyskeys')
e = pc.encrypt(fd.read())
fd = cStringIO.StringIO(e)
fp = cStringIO.StringIO()
cnt = 1
while True:
data = fd.read(524288)
if not data:
break
cnt += 1
data = pc.decrypt(data)
fp.write(data)
print cnt
fp.seek(0)
with open('ret.png', 'wb+') as r:
r.write(fp.getvalue())