[Ethereum] Web3js and keccak different values

keccaksolidity

In solidity there is the keccak256 function which hashes its arguments.
I use the keccak256 to compute and use the result to check if some entries exist in my array.

I want to compute the same value in javascript and check if the entry exists on the blockchain, although the web3.sha gives different value than the keccak256.

How can I compute the same value for the same arguments?

In console I run this:

web3.sha3("test1");

and my contract:

function hashVal(bytes32 val) public returns(bytes32) {
     return keccak256(val);
 }

Best Answer

Try this:

web3.sha3(web3.padRight(web3.fromAscii("test1"), 66), { encoding: 'hex' });

Explanation:

A bytes32 representation of "test1" is 32 bytes long, while "test1" is only 5 bytes long.

web3.fromAscii("test1") converts the string to its hexadecimal representation with a leading "0x": 0x7465737431.

web3.padRight pads the value with zeros on the right-hand side, like the conversion to bytes32 does. 32 bytes is 64 hexadecimal characters, but to take into account the leading "0x", I'm padding to 66 characters. This producets 0x7465737431000000000000000000000000000000000000000000000000000000, which is a bytes32 representation of the string.

Finally, we pass this value to web3.sha3 and specify the { encoding: 'hex' } option so sha3 interprets the value passed in as hexadecimal rather than ASCII.

Related Topic