使用 pyCrypto 对 TypeError 中的结果进行哈希处理

Using pyCrypto to hash results in a TypeError

我正在尝试在 win10
上为 python 3.5.1 使用 pycrypto 使用这段简单的代码有:

from Crypto.Hash import SHA256  
SHA256.new('abc').hexdigest()

导致此错误:

Traceback (most recent call last):  
  File "E:/Python/C.py", line 2, in <module>  
    SHA256.new('abc').hexdigest()  
  File "E:\Python\lib\site-packages\Crypto\Hash\SHA256.py", line 88, in new
    return SHA256Hash().new(data)
  File "E:\Python\lib\site-packages\Crypto\Hash\SHA256.py", line 75, in new
    return SHA256Hash(data)
  File "E:\Python\lib\site-packages\Crypto\Hash\SHA256.py", line 72, in __init__
    HashAlgo.__init__(self, hashFactory, data)
  File "E:\Python\lib\site-packages\Crypto\Hash\hashalgo.py", line 51, in __init__
    self.update(data)
  File "E:\Python\lib\site-packages\Crypto\Hash\hashalgo.py", line 69, in update
    return self._hash.update(data)
TypeError: Unicode-objects must be encoded before hashing

有人知道问题出在哪里吗?

在 运行 散列函数之前对 'abc' 字符串使用 .encode() 函数。

例如,如果您希望使用 Unicode 编码:

'abc'.encode('utf-8')

TypeError: Unicode-objects must be encoded before hashing

意味着你应该这样做:

from Crypto.Hash import SHA256

print(SHA256.new('abc'.encode('utf-8')).hexdigest())