Keccak is nice that it has arbitrary inputs and an infinite input space. This enables one to "make a hash" of a super large file where each input causes the internal state to scramble up some more. The hash should entirely change if a single bit of data in the source is different - unlike say a CRC32, or a checksum. It means your password could be a million chars long maybe. It's stored on disk as a hash, much smaller in size.
Regarding Keccak, it uses a "Sponge Construction" lord knows what that is read up on it here:
https://keccak.team/keccak_specs_summary.html If I understand it's a permutation chosen from a set of seven Keccak permutations, denoted I assume by reference to their bit depths as b∈{25,50,100,200,400,800,1600}.
The state is organized as an array of 5×5 lanes, each of length w∈{1,2,4,8,16,32,64} and 25 cells deep. When implemented on a 64-bit processor, a lane of Keccak can be represented as a tidy 64-bit CPU word.
Finally, to even entertain the thought of similar input causing collisions, you have to imagine this data traversing from base 25, through base 50, up to 1600 and back. Smart money is on this being quite very resistant to collisions (it's design goal?).
web3.sha3()
takes an encoding parameter to specify that you are passing in a hex address:
address_string = '0x5b2063246f2191f18f2675cedb8b28102e957458';
web3.sha3(address_string, {encoding: 'hex'});
As a general side-note: you have to pay gas costs to do any custom work in Solidity so, when possible, you are best off working on the javascript side.
Best Answer
Jehan's answer is great, but we need to explain one more thing: Why does
sha3(1)
in solidity produceb10e2d...fa0cf6
?This is because solidity's sha3 function hashes its inputs based on the argument types. Thus the value
1
will generate a different hash if it is stored asbytes8
,bytes16
,bytes32
, etc. Sincesha3(1)
is being passed1
as a number literal, it is converted into the smallest necessary type,uint8
1.8 bits fit into 2 hex characters, so if you pad your input to 2 characters you will get the same result in web3:
Javascript:
Likewise, you can cast the number on the solidity side:
Solidity:
Javascript:
A note about
BigNumber
types:They don't work automatically with
web3.sha3
. You have to convert them to hex first.Solidity:
Javascript:
EDIT:
I wrote a small lib that provides a version of
web3.sha3
that exactly matches the behavior ofsha3
in Solidity. Hopefully this clears up all your hashing woes :). https://github.com/raineorshine/solidity-sha3