Quantcast
Channel: CodeSection,代码区,网络安全 - CodeSec
Viewing all articles
Browse latest Browse all 12749

Solidity中的sha256/keccak256如何正确传参

$
0
0

今天遇到一个需求:用户传递一个字符串过来,跟当前的时间拼在一起取哈希值,作为唯一标识。

举个例子,假如用户传递的字符串是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/keccak256如何正确传参

嗯哼?结果好像不太对?于是取查了一下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); } }

我们再来运行一下:


Solidity中的sha256/keccak256如何正确传参

这回结果就对了,perfect~~

另外,如果你想测试其他的哈希算法比如keccak256,推荐用下面的网站验证结果,非常全:

http://emn178.github.io/online-tools/

更多文章欢迎关注“鑫鑫点灯”专栏: https://blog.csdn.net/turkeycock

或关注飞久微信公众号:
Solidity中的sha256/keccak256如何正确传参

Viewing all articles
Browse latest Browse all 12749

Latest Images

Trending Articles





Latest Images