Search code examples
pythonhashencodingpycrypto

Using pyCrypto to hash results in a TypeError


I'm trying to use pycrypto for python 3.5.1 on win10
using this simple piece of code for has:

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

resulting this error:

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

Anyone know what the problem is?


Solution

  • Use the .encode() function on your 'abc' string before running the hashing function.

    For example, if you wish to use Unicode encoding:

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