What is Hash in Blockchain: Explanation and Solidity Example
hash is a fixed-size string generated by a hash function that uniquely represents data. It acts like a digital fingerprint, ensuring data integrity and linking blocks securely. In Solidity, keccak256 is the common hash function used to create these hashes.How It Works
A hash in blockchain works like a unique digital fingerprint for data. Imagine you have a special stamp that creates a unique pattern for every document you stamp. Even a tiny change in the document will create a completely different pattern. This is how hashing ensures data cannot be changed without detection.
In blockchain, each block contains data and the hash of the previous block. This linking creates a secure chain. If someone tries to change data in one block, its hash changes, breaking the chain and alerting the network.
Hash functions take any input data and produce a fixed-length output string. This output looks random but is always the same for the same input. Solidity uses keccak256, a cryptographic hash function, to generate these hashes.
Example
This Solidity example shows how to hash a string using keccak256. The function getHash returns the hash of the input string.
pragma solidity ^0.8.0; contract HashExample { function getHash(string memory input) public pure returns (bytes32) { return keccak256(abi.encodePacked(input)); } }
When to Use
Hashes are used in blockchain to secure data, verify transactions, and link blocks. They help detect any tampering because even a small change alters the hash drastically.
In Solidity smart contracts, hashing is useful for storing passwords securely, verifying data integrity, and creating unique identifiers. For example, you can hash user inputs to compare without revealing the original data.
Key Points
- A hash is a fixed-size unique string representing data.
- It ensures data integrity by detecting changes.
- Blocks in blockchain are linked by hashes.
- Solidity uses
keccak256for hashing. - Hashes are essential for security and verification in smart contracts.