Back to homepage

The keccak256 hashing method explained

Published

What is keccak256?

The keccak256() method is a hasing function built-in in Ethereum that receives a input and returns the a random 256-bit hexadecimal number.

If we call this function with the same input, the result will always be the equal, but the smallest change in the input will cause the result to be completely different.

Hash functions like keccak256 are useful for many purposes in Ethereum like, for example, to generate pseudo-random numbers.

Check out this article to learn how to use keccak256 to generate pseudo-random numbers.

keccak256 example

Here is the keccak256 specification:

  • keccak256 input: a single parameter of type bytes.
  • keccak256 response: a 256-bit hexadecimal number.

As the keccak256 method expects a single parameter of type bytes, we'd need to use the abi.encodePack() method to cast any data type we want to hash, into the bytes data type. For example:

Example:

//6e91ec6b618bb462a4a6ee5aa2cb0e9cf30f7a052bb467b0ba58b8748c00d2e5
keccak256(abi.encodePacked('aaaab'));
//b1f078126895a1424524de5321b339ab00408010b7cf0e6ed451514981e58aa9
keccak256(abi.encodePacked('aaaac'));

As you can see, we're using abi.encodePack to transform the strings to the bytes data type. The results are completely different, even though the inputs are very similar.

TAGS

If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Buy Me A Coffee