Solidity SHA256 Function – Understanding Arguments for Cryptographic Hashing

contract-developmentcryptographyhash-algorithmsolidity

In Solidity, I find that the sha256 function can be used like this a = sha256(uint b, string c, bool d, ......) (the arguments can be a combination of different types, and the other types can also be included.)

What does sha256 do with the arguments of different types?

Best Answer

Solidity docs say that sha256 (and sha3, ripemd160) arguments are tightly packed:

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

sha3("ab", "c")

sha3("abc")

sha3(0x616263)

sha3(6382179)

sha3(97, 98, 99)

Using the question's example of a = sha256(uint b, string c, bool d),

  • if we assign some values like b is 31415, c is "abc", and d is false,

  • then a would equal sha256(31415, 6382179, 0), which is same as sha256(0x7ab761626300).


For completeness, the docs mention that:

If padding is needed, explicit type conversions can be used: sha3(“x00x12”) is the same as sha3(uint16(0x12)).

Related Topic