2

I have this solidity method:

function hashData(bytes32 data) public constant returns (bytes32) {
    var hash = keccak256(data, msg.sender);
    return hash;
  }

for a data = "0x707974686f6e62" and address = "0x4c5f885b9854ce17e5620098e53f3032be002fed"

I dont get the same result using web3.sha3(data,address)

maroodb
  • 1,111
  • 1
  • 10
  • 32

2 Answers2

3

In Solidity, sha3 and keccak256 are aliases, so their output will be identical.

web3.sha3 is a different function in a different programming language (I assume JavaScript). You would probably find web3.utils.soliditySha3 helpful because as it reproduces the packing that Solidity does.

ethereumjs-abi has a similar function in case you're not using web3.js 1.0.

user19510
  • 27,999
  • 2
  • 30
  • 48
  • 1
    I don't get why sha3 is alias for keccak256, being sha3-256 a different hash ... At least, yielding different results on https://emn178.github.io/online-tools/keccak_256.html and https://emn178.github.io/online-tools/sha3_256.html – Juan Ignacio Pérez Sacristán Nov 26 '18 at 12:53
  • 1
    That's why they renamed to keccak256. As I recall, at the time Ethereum was developed, sha3 had not yet been finalized, and it was then equivalent to keccak256. In the latest version of Solidity, sha3 had been removed in favor of keccak256. – user19510 Nov 26 '18 at 13:25
3

Try to use web3 1.0 and web3.utils.soliditySha3 to execute the sha3/keccak256 in the same way that Solidity would.

Will calculate the sha3 of given input parameters in the same way solidity would. This means arguments will be ABI converted and tightly packed before being hashed.

more info

qbsp
  • 4,367
  • 2
  • 15
  • 26
  • I need a solution for web3 0.20 – maroodb May 24 '18 at 11:23
  • there's not unless you use web3.sha3(hash, {encoding: 'hex'}); but web3.sha3 takes only one argument https://github.com/ethereum/web3.js/blob/develop/lib/utils/sha3.js#L26 https://github.com/ethereum/wiki/wiki/JavaScript-API#example-10 – qbsp May 24 '18 at 14:30