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

栏目: 编程工具 · 发布时间: 7年前

内容简介:今天遇到一个需求:用户传递一个字符串过来,跟当前的时间拼在一起取哈希值,作为唯一标识。举个例子,假如用户传递的字符串是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/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如何正确传参

以上所述就是小编给大家介绍的《Solidity中的sha256/keccak256如何正确传参》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Chinese Authoritarianism in the Information Age

Chinese Authoritarianism in the Information Age

Routledge / 2018-2-13 / GBP 115.00

This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

MD5 加密
MD5 加密

MD5 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具