How can I encode string variable to keccak in python?

261 views Asked by At

I want encode block_string variable to keccak.

This is my current function. In this code I use sha256 (hashlib library) for encode block_string value but I want to use keccak instead of sha256:

def hash(block):
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()
1

There are 1 answers

4
Samson On

It needs to be a byte literal. Try: a = b'some date'

Alternatively you could do a=a.encode('UTF-8') to achieve the same purpose.

Full corrected code:

from Crypto.Hash import keccak
a = b'some date'
# Alternatively
# a = 'some date'
# a = a.encode('UTF-8')
keccak_hash = keccak.new(digest_bits=512)
keccak_hash.update(a)
print (keccak_hash.hexdigest())