What is Hashing with Keccak256 in Solidity?

Overview

A cryptographic hash function is an algorithm that accepts any amount of data and outputs a fixed size enciphered text. The tiniest alteration in the data causes an entire shift in the output.

What is Keccak256?

keccak256 is used to process the Keccak-256 hash of the data input and can be used for the following:

  • To create a deterministic, one-of-a-kind ID from a set of data.

  • Commit-reveal scheme

  • Cryptographic signature with a small size (by signing the hash instead of a larger input)

Example

// pragma version
pragma solidity ^0.5.12;
// Creating a contract
contract fellowCoders
{
uint hashDigits = 8;
// Equivalent to 10^8 = 8
uint hashModulus = 10 ** hashDigits;
// Function to generate the hash value
function _generateRandom(string memory _str)
public view returns (uint)
{
uint random =
uint(keccak256(abi.encodePacked(_str)));
// Returning the generated hash value
return random % hashModulus;
}
}

Explanation

  • Line 5: We create a contract.

  • Line 11: We are using a 6 digit hash. So, we store 10^6, which is used to extract the first 6 digits.

  • Line 14: We create a function to generate the hash value.

  • Lines 17: We pack the string into bytes and apply the hash function. Next, we typecast it into uint.

  • In line 21 We return the generated hash value.