【问题标题】:Python encryption unicode error when converting from Python 2 to python 3从 Python 2 转换为 python 3 时出现 Python 加密 unicode 错误
【发布时间】:2018-07-15 17:12:48
【问题描述】:

我找到了一些我想合并到我的 Python 加密程序中的代码。它应该加密代码同一目录中的文件,我希望它以一个目录为目标。但是,它是用 Python 2 编写的,当我更改一些代码以适应 Python 3 时,我收到以下错误:

Traceback (most recent call last):
  File "/home/pi/Desktop/Projects/FyleCript/Dev Files/encryption.py", line 77, in <module>
    encrypt(SHA256.new(password).digest(), str(Tfiles))
  File "/usr/lib/python3/dist-packages/Crypto/Hash/SHA256.py", line 88, in new
    return SHA256Hash().new(data)
  File "/usr/lib/python3/dist-packages/Crypto/Hash/SHA256.py", line 75, in new
    return SHA256Hash(data)
  File "/usr/lib/python3/dist-packages/Crypto/Hash/SHA256.py", line 72, in __init__
    HashAlgo.__init__(self, hashFactory, data)
  File "/usr/lib/python3/dist-packages/Crypto/Hash/hashalgo.py", line 51, in __init__
    self.update(data)
  File "/usr/lib/python3/dist-packages/Crypto/Hash/hashalgo.py", line 69, in update
    return self._hash.update(data)
TypeError: Unicode-objects must be encoded before hashing

但该代码在 Python 2 中完美运行。我尝试在 SO 和谷歌搜索上寻找类似的问题,但没有帮助。


代码:

def encrypt(key, filename):
        chunksize = 64 * 1024
        outFile = os.path.join(os.path.dirname(filename), "(encrypted)"+os.path.basename(filename))
        filesize = str(os.path.getsize(filename)).zfill(16)
        IV = ''
 
        for i in range(16):
                IV += chr(random.randint(0, 0xFF))
       
        encryptor = AES.new(key, AES.MODE_CBC, IV)
 
        with open(filename, "rb") as infile:
                with open(outFile, "wb") as outfile:
                        outfile.write(filesize)
                        outfile.write(IV)
                        while True:
                                chunk = infile.read(chunksize)
                               
                                if len(chunk) == 0:
                                        break
 
                                elif len(chunk) % 16 !=0:
                                        chunk += ' ' *  (16 - (len(chunk) % 16))
 
                                outfile.write(encryptor.encrypt(chunk))
 
 
def decrypt(key, filename):
        outFile = os.path.join(os.path.dirname(filename), os.path.basename(filename[11:]))
        chunksize = 64 * 1024
        with open(filename, "rb") as infile:
                filesize = infile.read(16)
                IV = infile.read(16)
 
                decryptor = AES.new(key, AES.MODE_CBC, IV)
               
                with open(outFile, "wb") as outfile:
                        while True:
                                chunk = infile.read(chunksize)
                                if len(chunk) == 0:
                                        break
 
                                outfile.write(decryptor.decrypt(chunk))
 
                        outfile.truncate(int(filesize))
       
def allfiles():
        allFiles = []
        for root, subfiles, files in os.walk(os.getcwd()):
                for names in files:
                        allFiles.append(os.path.join(root, names))
 
        return allFiles
 
       
choice = input("Do you want to (E)ncrypt or (D)ecrypt? ")
password = input("Enter the password: ") 

encFiles = allfiles()
 
if choice == "E" or 'e':
        for Tfiles in encFiles:
                if os.path.basename(Tfiles).startswith("(encrypted)"):
                        print("%s is already encrypted" %str(Tfiles))
                        pass
 
                elif Tfiles == os.path.join(os.getcwd(), sys.argv[0]):
                        pass
                else:
                        encrypt(SHA256.new(password).digest(), str(Tfiles))
                        print("Done encrypting %s" %str(Tfiles))
                        os.remove(Tfiles)
 
 
elif choice == "D" or 'd':
        filename = input("Enter the filename to decrypt: ")
        if not os.path.exists(filename):
                print("The file does not exist")
                sys.exit()
        elif not filename.startswith("(encrypted)"):
                print("%s is already not encrypted" %filename)
                sys.exit()
        else:
                decrypt(SHA256.new(password).digest(), filename)
                print("Done decrypting %s" %filename)
                os.remove(filename)
 
else:
        print("Please choose a valid command.")
        sys.exit()

谁能帮我解决这个问题?我用过 Python 2 到 3 的工具,但还是不行。

另外,你能解决目录问题吗?没必要,但我想要。


编辑:我已将str 替换为bytesbytearray,但它返回相同的错误。

【问题讨论】:

  • 你试过用bytes代替str吗? Python 2 字符串只是字节数组; Python 3 字符串是 Unicode,正如错误消息所说,在进行加密等二进制操作之前,需要将它们编码为字节。
  • @TomZych 所以,用bytes 替换所有str
  • 您的示例似乎不符合最低可验证标准。
  • 你也有隐式字符串,例如IV。我的电脑上没有这个包,不能轻易试验。我建议您查看文档并确保您将有效类型传递给 encrypt 以及其他任何给出错误的内容,然后向后工作,直到所有类型都正确。注意bytes 是不可变的;当你需要一些可变的东西时使用bytearray
  • 不,谢谢,我对你的问题没那么投入。

标签: python python-3.x python-2.7 pycrypto python-unicode


【解决方案1】:

您的“密码”变量是一个字符串,但 SHA256.new 需要字节(例如,允许使用 unicode)。 Crypto.Hash.SHA256 documentation 中列出了您需要的字节。

解决方案是在散列之前将密码编码为字节。这几乎就是错误消息所说的内容(如果您知道 python 3 中的所有字符串都是 unicode 对象):

TypeError: Unicode-objects must be encoded before hashing

解决方案例如使用 utf8 进行编码:

SHA256.new(password.encode('utf8')).digest()

【讨论】:

  • 这可行,但有一个新错误:ValueError: IV must be 16 bytes long
  • 如果您想问这个问题,请开始一个新问题,并确保您提供详细信息并展示您已经尝试过的内容。
猜你喜欢
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 2018-01-24
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多