内容简介:今天遇到一个需求:用户传递一个字符串过来,跟当前的时间拼在一起取哈希值,作为唯一标识。举个例子,假如用户传递的字符串是abc,当前时间是123,我们来看看标准答案:看起来很简单,就写了下面这段测试代码:
今天遇到一个需求:用户传递一个字符串过来,跟当前的时间拼在一起取哈希值,作为唯一标识。
举个例子,假如用户传递的字符串是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-3 (Keccak-256) hash of the (tightly packed) arguments
In the above, “tightly packed” means that the arguments are concatenated without padding. This means that the following are all identical:
keccak256("ab", "c")
keccak256("abc")
keccak256(0x616263)
keccak256(6382179)
keccak256(97, 98, 99)
我们想计算abc123的哈希,实际上就是要计算0x616263313233的哈希,而上面的代码计算的则是0x6162637B的哈希(123=0x7B)。
知道了问题所在,也就好解决了,把时间转换成对应的ASCII码不就行了:
pragma solidity ^0.4.24;
contract Sha256Test {
uint256 time = 123;
event hashResult(bytes32);
function calcSha256(string input) public {
bytes32 id = sha256(input, toAscii(time));
emit hashResult(id);
}
function toAscii(uint256 x) private pure returns (string) {
bytes memory b = new bytes(32);
for(uint256 i = 0; x > 0; i++) {
b[i] = byte((x % 10) + 0x30);
x /= 10;
}
bytes memory r = new bytes(i--);
for(uint j = 0; j < r.length; j++) {
r[j] = b[i--];
}
return string(r);
}
}
我们再来运行一下:
这回结果就对了,perfect~~
另外,如果你想测试其他的哈希算法比如keccak256,推荐用下面的网站验证结果,非常全:
http://emn178.github.io/online-tools/
更多文章欢迎关注“鑫鑫点灯”专栏: https://blog.csdn.net/turkeycock
或关注飞久微信公众号:以上所述就是小编给大家介绍的《Solidity中的sha256/keccak256如何正确传参》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Learning PHP, MySQL, JavaScript, and CSS
Robin Nixon / O'Reilly Media / 2012-9-3 / USD 39.99
If you're familiar with HTML, you can quickly learn how to build interactive, data-driven websites with the powerful combination of PHP, MySQL, and JavaScript - the top technologies for creating moder......一起来看看 《Learning PHP, MySQL, JavaScript, and CSS》 这本书的介绍吧!