使用pycrypro的AES加密JPG文件失败

2024-04-25 22:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我用python和pycrypto模块编写的用来加密和解密文件的代码(尚未完成)。在

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文件时,我得到了以下错误:

^{pr2}$

我在一个mp4文件上尝试过,它运行得很好:加密和解密也是如此。在

这个错误的原因是什么?我如何修复它?在


Tags: 文件keyimportselfsourcestreamopenfile