4

I'm developing a smart contract in Solidity in which I need to evaluate the hash of two concatenated bytes32. I don't have to concatenate the bytes32 since the sha3 function supports more than one parameters and I'm using it as:

sha3(first, second);

Where first and second are bytes32. I'd like to know how the concatenation is performed in order to replicate the same hash result locally, or using an online evaluator of the keccak-256 hash function.

1 Answer 1

7

The arguments are expressed as bytes, left-padded with zeroes to the maximum length of the data type you've passed in, and concatenated without any kind of delimiter.

In Python, given two hex-encoded bytes32s prepended with a 0x called first and second, it looks something like:

# keccak, change before upgrading pysha >= 3.10
from sha3 import sha3_256 
from rlp.utils import decode_hex

my_hash = "0x" + sha3_256(
   decode_hex(first[2:].zfill(64)) + 
   decode_hex(second[2:].zfill(64))
).hexdigest()

The decode_hex there is turning hex into an array of bytes.

PS the modern versions of Solidity and pysha, and probably the relevant library in whatever language you're using, now have versions of keccak called keccak or keccak256, so it's probably better to standardize on those.

2
  • "filled out" means left-padding with zeroes (for those who may have needed to lookup zfill).
    – eth
    Commented Mar 31, 2017 at 4:14
  • Sorry for the delay and thank you very much for the answer :)
    – gatb27
    Commented Apr 11, 2017 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.