python-3.xsoliditysha-3remix

How to generate sh3_keccak256 for integer values as generated by Solidity?


I am trying to generate the same sha3.keccak_256 of integer values in Python that is generated by Solidity.

Here is what Solidity does:

pragma solidity ^0.4.18;

contract GenerateHash{
    function generateHashVal(int id, int date) pure public returns (bytes32){
        //Using values - (123,1522228250);
        return keccak256(id,date);
    }
}

The hash generated by this is 0xdf4ccab87521641ffc0a552aea55be3a0c583544dc761541784ec656668f4c5a

In Python3 though, I can't generate the same for integer values. If I type cast it to string then I am able to get some value but that does not match that of Solidity:

>>> s=sha3.keccak_256(repr(data).encode('utf-8')).hexdigest()
>>> print(s)
37aafdecdf8b7e9da212361dfbb20d96826ae5cc912ac972f315228c0cdc51c5
>>> print(data)
1231522228250

Any help is appreciated.


Solution

  • You need to build the right binary representation, which should be two 32-byte integers concatenated together. There are probably other ways of doing that, but here's a method that converts everything to hex with the right padding and then uses binascii.unhexlify to convert to a byte sequence:

    sha3.keccak_256(binascii.unhexlify('{:064x}{:064x}'.format(123, 1522228250))).hexdigest()
    
    # output: 'df4ccab87521641ffc0a552aea55be3a0c583544dc761541784ec656668f4c5a'