使用pyCrypto在TypeError

时间:2016-08-13 18:31:06

标签: python hash encoding pycrypto

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

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

任何人都知道问题是什么?

2 个答案:

答案 0 :(得分:0)

使用&#39; abc&#39;上的.encode()功能运行散列函数之前的字符串。

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

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

答案 1 :(得分:0)

  

TypeError:必须在散列之前对Unicode对象进行编码

意味着你应该这样做:

from Crypto.Hash import SHA256

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