[Ethereum] How does keccak256 concatenate values inside a Solidity smart contract

byteshashkeccaksha3solidity

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.

Best Answer

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.

Related Topic