[Ethereum] Python and Solidity keccak256 function gives different results

encodingkeccakpythonsha3solidity

I am working on implementing a smart contract application in which, on and off chain calculations will exist. I will have to calculate the Hash Function of multiple integers with Python and Solidity. But Solidity and Python give different results respectively as shown bellow.

Solidity Code:

The Output for (a=1, b=2, c=3) is: 49776295142305522338649292811956300178326541500117443588869412604416814650524

Python Code:

The Output for (a=1, b=2, c=3) is: 45637690538541992090000098772847886457082422231295691457910964509567538102535

I need to understand how Solidity encodes the input integers and pass them to the hash function, How this could be done in Python?

Best Answer

I would check out the Web3.py library, specifically the function Web3.soliditySha3

This will work for computing the hash you need:

from web3 import Web3

print(int(Web3.soliditySha3(['uint256', 'uint256', 'uint256'], [1 ,2, 3]), 16))