Solidity Keccak – Reasons for Different keccak256 Hashes of the Same String

keccaksolidity

What is the reason that when i try to get the keccak256 values for the same string (which is "0x0000000000000000000000000000000000000000000000000000000000000001" or simply value of 1 in bytes32 representation) with web3 and Solidity I get two different values.

  1. When I use the following code :

    await web3.utils.keccak256("0x0000000000000000000000000000000000000000000000000000000000000001")

The output is : 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6

  1. When I type run the same thing in solidity:

     function getBytes32() public pure returns (bytes32) 
     {
        return keccak256("0x0000000000000000000000000000000000000000000000000000000000000001");
     }
    

The output is: 0xcb371be217faa47dab94e0d0ff0840c6cbf41645f0dc1a6ae3f34447155a76f3

P.S. There is a similar question here but there the issue was with padding. I have used the exact same string. Both are 32 bytes long (i.e.. 64 chars) and two chars for "0x".

Best Answer

in the first case the output is based on the Hex value, on the second one is based on the string value.

return keccak256(abi.encode(0x0000000000000000000000000000000000000000000000000000000000000001));

it returns the value that you're expecting

0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6