Keccak256 – How Does keccak256 with abi.encodePacked Work Internally?

keccaksolidityweb3js

I have two uint256 values -> 2 and 0

When performing:
keccak256(abi.encodePacked(uint(2), uint(0)))

I got the correct result:

0xabbb5caa7dda850e60932de0934eb1f9d0f59695050f761dc64e443e5030a569

What I am confused about is when I am trying to use solely keccak256 on the value:
0x00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000
which is the result of abi.encodePacked(uint(2), uint(0))

In that case with keccak256 I am getting: 0x608133906c7feb1802e3582d4a7765ca241f9618f3eabaa89a6a14fdea761d9d

What am I missing here? I would expect that I will get the same results.

To sum it up. Why am I getting different results with functions A and B? What raw value do I need to provide to keccak256 of testB to get the same results as testA ?

function testEncode() public pure returns(bytes memory) {
  return abi.encodePacked(uint(2), uint(0)); 
  // returns 0x00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000
}

function testA() public pure returns(bytes32) {
  return keccak256(abi.encodePacked(uint(2), uint(0)));
  // returns 0xabbb5caa7dda850e60932de0934eb1f9d0f59695050f761dc64e443e5030a569
}

function testB() public pure returns(bytes32) {
  // abi.encodePacked(uint(2), uint(0)) // 0x00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000
  return keccak256("0x00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000"); 
  // returns 0x608133906c7feb1802e3582d4a7765ca241f9618f3eabaa89a6a14fdea761d9d
}

I will be really thankful for your assistance. I am looking into this for hours. I am just trying to understand how it's working internally.

Cheers,

Best Answer

The issue is how you are passing the result of abi.encodePacked to the keccak256 function. keccak256 takes a hex argument and not a string as you did in your testB().

using an online tool i was able to get the correct result by passing a hex input type without the 0x at the start of the input. for your case here passing just the hex directly without the string quotes ("") will do the job.

Related Topic