今天遇到一个需求:用户传递一个字符串过来,跟当前的时间拼在一起取哈希值,作为唯一标识。
举个例子,假如用户传递的字符串是abc,当前时间是123,我们来看看标准答案:
$ echo -n 'abc123' | shasum -a 256
6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090
看起来很简单,就写了下面这段测试代码:
pragma solidity ^0.4.24;
contract Sha256Test {
uint256 time = 123;
event hashResult(bytes32);
function calcSha256(string input) public {
bytes32 id = sha256(input, time);
emit hashResult(id);
}
}
我们来运行一下:
嗯哼?结果好像不太对?于是取查了一下Solidity的文档,有这么一段描述:
sha256(...) returns (bytes32)
:
compute the SHA-256 hash of the (tightly packed) arguments
keccak256(...) returns (bytes32)
:
compute the Ethereum-SHA