6
votes

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']
1
Did you even check the official website of Keccak (spelling!)? - sascha
was a typo due to touch type. - garg10may
Did you install a native sha3 library and expect it to just work? If so, please take a look at the python wrapper pysha3. - KompjoeFriek
installed pysha3 but it doesn't seem to work. Gives error AttributeError: 'module' object has no attribute 'keccak_512' - garg10may
pysha3 is working, sha3 was overriding it. Original implementer should give a different import name. - garg10may

1 Answers

19
votes
  1. pycryptodome

     from Crypto.Hash import keccak
     k = keccak.new(digest_bits=256)
     k.update('age')
     print k.hexdigest()
    
  2. 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