python-2.7cryptographykeccak

How can I find keccak 256 hash in Python


I am using Python 2.7 and need to find keccak hash for solidity events. However I don't see a default lib for the same.

I installed sha3 but it doesn't seem to provide this functionality. Tried pysha3 with below code

  import sha3
  k = sha3.keccak_512()
  k.update('age')
  k.hexdigest()

But got the error

AttributeError: 'module' object has no attribute 'keccak_512'

sha3 doesn't have this module indeed

>>> dir(sha3)
['SHA3224', 'SHA3256', 'SHA3384', 'SHA3512', 'SHAKE128', 'SHAKE256', '_SHA3Base', '_SHAKEBase', '__all__', '__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_sha3', 'binascii', 'copy', 'hashlib', 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'shake128', 'shake256']

Solution

    1. pycryptodome pip install pycryptodome

       from Crypto.Hash import keccak
       k = keccak.new(digest_bits=256)
       k.update('age')
       print k.hexdigest()
      
    2. pysha3 pip install pysha3

      import sha3
      k = sha3.keccak_256()
      k.update('age')
      print k.hexdigest()
      

    Please note:

    1. For python3 the strings need to be passed in binary k.update(b'age')
    2. If you want to find a new hash you need to initialize k again otherwise it will update the value on top of the existing one.

    If you have both sha3 and pysha3, it won't work, since import sha3 will default to sha3 lib.

    Online handy tool