1

Assume you have a string of hex data you want to hash.

In Ethers:

ethers.utils.keccak256("0x1234");

// "0x56570de287d73cd1cb6092bb8fdee6173974955fdef345ae579ee9f475ea7432"

In Solidity:

function hasher() external pure returns(bytes32) {
  return keccak256('1234');
}

// "0x387a8233c96e1fc0ad5e284353276177af2186e7afa85296f106336e376669f7"

function hasher() external pure returns(bytes32) {
  return keccak256('0x1234');
}

// "0x1ac7d1b81b7ba1025b36ccb86723da6ee5a87259f1c2fd5abe69d3200b512ec8"

Why aren't these hashing to the same value?

1 Answer 1

2

As pointed out by Sush, the Solidity values being passed are a string, not a hexadecimal value. As a result, what's being hashed in the question is the string of the characters 1234 or 0x1234 above, not the hexadecimal value 0x1234. If you wanted to hash the value 0x1234, you could use hex'1234':

function hasher() external pure returns(bytes32) {
  return keccak256(hex'1234');
}

// 0x56570de287d73cd1cb6092bb8fdee6173974955fdef345ae579ee9f475ea7432

If this isn't a case where you're able to hardcode the literals, pass them in as bytes:

function hasher(bytes memory value) external pure returns(bytes32) {
  return keccak256(bytes(value));
}

// hasher("0x1234") = "0x56570de287d73cd1cb6092bb8fdee6173974955fdef345ae579ee9f475ea7432"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.