使用pycrypro的AES加密JPG文件失败 [英] Encryption of a JPG file using pycrypro's AES failing
本文介绍了使用pycrypro的AES加密JPG文件失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面给出的是我用python与pycrypto模块加密和解密文件的代码(还未完成)。
Given below is the code(not complete yet) I have written to encrypt and decrypt files using python with the pycrypto module.
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
import getpass
class ED(object):
def getfromuser(self,choice):
if choice=='key':
key=getpass.getpass('Enter AES Key (minimum 16 characters): ')
if len(key)<16:
print 'Key entered too short. Please try again.'
self.getfromuser(choice)
key=key+str(8-len(key)%8)*(8-len(key)%8)
return key
if choice=='IV':
IV_seed=raw_input('Enter a seed for the IV: ')
IV=SHA256.new()
IV.update(IV_seed)
IV.digest()
return str(IV)[0:16]
def AESEncrypt(self,key,IV,source,dest):
f=open(source,"r")
fstream=f.read()
f.close()
AES_stream=AES.new(key,AES.MODE_CBC,IV)
AES_encrypted=AES_stream.encrypt(fstream)
with open(dest,"w") as write_file:
write_file.write(AES_encrypted)
def AESDecrypt(self,key,IV,source,dest):
f=open(source,"r")
fstream=f.read()
f.close()
AES_stream=AES.new(key,AES.MODE_CBC,IV)
AES_decrypted=AES_stream.decrypt(fstream)
with open(dest,"w") as write_file:
write_file.write(AES_decrypted)
当我尝试加密一个JPG文件使用这个我得到以下错误:
When I tried to encrypt a JPG file using this I got the following error:
AES_encrypted=AES_stream.encrypt(fstream)
ValueError: Input strings must be a multiple of 16 in length
我尝试了一个mp4文件,它工作正常:加密和解密。
I tried it on an mp4 file and it worked fine: the encryption and the decryption too.
这个错误的原因是什么,如何解决?
What is the cause of this error and how do I fix it?
推荐答案
我发现解。如果不希望填充麻烦,可以使用 CFB(密码反馈) 模式如下:
I found the solution. If one does not want the hassle of padding, one can use the CFB (Cipher feedback) mode as follows:
AES_stream = AES.new(key,AES.MODE_CFB,IV)
这篇关于使用pycrypro的AES加密JPG文件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文