欢迎订阅专栏:3分钟Solidity--智能合约--Web3区块链技术必学
如需获取本内容的最新版本,请参见 Cyfrin.io 上的Hashing with Keccak256(代码示例)
keccak256计算输入的 Keccak-256 哈希值。
一些应用场景包括:
- 从输入生成确定性唯一ID
- 提交-揭示方案
- 紧凑型加密签名(通过对哈希值而非较大输入进行签名实现)
Solidity提供了两种数据编码方法:
-
abi.encode:- 将数据编码为带填充的字节
- 保留所有数据信息
- 处理动态类型时更安全
- 由于填充会产生更长的输出
-
abi.encodePacked:- 执行紧凑编码(压缩)
- 产生的输出比
abi.encode更短 - 更节省gas
- 动态类型存在哈希碰撞风险(
collision函数)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
contract HashFunction {
function hash(string memory _text, uint256 _num, address _addr)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_text, _num, _addr));
}
// 哈希碰撞示例
// 当向abi.encodePacked传递多个动态数据类型时
// 可能会发生哈希碰撞。在这种情况下,应改用abi.encode。
function collision(string memory _text, string memory _anotherText)
public
pure
returns (bytes32)
{
// encodePacked(AAA, BBB) -> AAABBB
// encodePacked(AA, ABBB) -> AAABBB
return keccak256(abi.encodePacked(_text, _anotherText));
}
}
contract GuessTheMagicWord {
bytes32 public answer =
0x60298f78cc0b47170ba79c10aa3851d7648bd96f2f8e46a19dbc777c36fb0c00;
// 魔法词是“Solidity”
function guess(string memory _word) public view returns (bool) {
return keccak256(abi.encodePacked(_word)) == answer;
}
}
Remix Lite 尝试一下
END