[Ethereum] Different hash values for keccak256 functions

keccaknodejssolidity

In solidity i used the following command:

keccak256(firstName, lastName, studentId);
->0x157effbe0a2f53d887ad79b0dc3e9eb6084c3025ae0114a253b8f94f83c1462d

And, in NodeJS i used the following command:

keccak_256(firstName, lastName, studentId);
->488e3bd05d8d3fa46e2ef71387dafdc2341c603a60972da583206f39920c6350

I am getting different values for the same parameters passed in the same function, but in solidity and one in nodeJs. I need the exact same output for both the versions. What should i do?

Best Answer

In your NodeJS you have to fix the input you are passing to its keccak function. The fix might simply be: keccak_256(firstName+lastName+ studentId); but you have to check your NodeJS library as well as the types you're passing in.

Solidity docs:

keccak256(...) returns (bytes32): compute the Ethereum-SHA-3 (Keccak-256) hash of the (tightly packed) arguments

In the above, “tightly packed” means that the arguments are concatenated without padding. This means that the following are all identical:

keccak256("ab", "c")
keccak256("abc")
keccak256(0x616263)
keccak256(6382179)
keccak256(97, 98, 99)
If padding is needed, explicit type conversions can be used: keccak256("\x00\x12") is the same as keccak256(uint16(0x12)).

Note that constants will be packed using the minimum number of bytes required to store them. This means that, for example, keccak256(0) == keccak256(uint8(0)) and keccak256(0x12345678) == keccak256(uint32(0x12345678)).

Above are all equivalent results in Solidity for keccak256("a", "b", "c") and can help you match your NodeJS results against.

How does Solidity's sha3 / keccak256 hash uints? might also help. (keccak256 and sha3 produce identical results.)