DEV Community

Cover image for Ethereum-Solidity Quiz Q30: What does keccak256() do?
MihaiHng
MihaiHng

Posted on

Ethereum-Solidity Quiz Q30: What does keccak256() do?

keccak256() is a cryptographic hash function, used for everything from generating addresses to verifying transaction integrity.

In short, you feed it any amount of data, and it generates a unique, fixed-size 32-byte "fingerprint" that can never be reversed.

1. Characteristics

Deterministic: The same input will always produce the exact same hash.

Fixed Output: No matter if you hash a single number or a 1GB file, the output is always 32 bytes (bytes32).

One-Way: It is computationally impossible to reconstruct the original data from the hash.

Collision Resistant: It is practically impossible to find two different inputs that produce the same hash.

2. Practical Use Cases in Your Smart Contracts

A. Comparing Strings

Solidity cannot compare strings directly using ==. Instead, we hash them and compare the results:

function compare(string memory _a, string memory _b) public pure returns (bool) {
    return keccak256(abi.encodePacked(_a)) == keccak256(abi.encodePacked(_b));
}
Enter fullscreen mode Exit fullscreen mode

B. Creating Unique Identifiers

You can combine multiple variables (like an address and a timestamp) to create a unique ID for a transaction or a user:

bytes32 uniqueId = keccak256(abi.encodePacked(msg.sender, block.timestamp));
Enter fullscreen mode Exit fullscreen mode

C. Computing Function Selectors

Ethereum uses keccak256 to identify which function to call. It takes the first 4 bytes of the hash of the function signature (e.g., transfer(address,uint256)).

3. Important: abi.encodePacked vs abi.encode

The keccak256 function only accepts a single bytes argument. To hash multiple values, you must "wrap" them first.

abi.encodePacked(...): Most common. It’s cheaper on gas because it doesn't add padding.

abi.encode(...): Safer for dynamic types (like two strings).

Top comments (0)