50 我想用java代码实现 keccak256(abi.encode(test))功能,但是我的实现和solidity计算的结果不一致。请大神指点一下

solidity代码实现

function getTest2 (string memory test) public pure returns(bytes32){
    return keccak256(abi.encode(test));
}

java代码实现

public void test() {
        String string = "1";

        //等价于abi.encode(string)
        StringBuilder encodeString = new StringBuilder();
        encodeString.append(TypeEncoder.encode(new Utf8String(string)));
        System.out.println(encodeString.toString());

        //等价于keccak256(abi.encode(string))
        byte[] decodeByte = Hex.decode(encodeString.toString());
        byte[] reshash = Hash.sha3(decodeByte);
        System.out.println("keccStr:"+ new String(Hex.encode(reshash)));

//      String reshash3 = Hash.sha3(encodeString.toString());
//      System.out.println(reshash3);
    }
请先 登录 后评论

最佳答案 2022-04-21 09:57

来了,写法有问题 java

String h2 = Hex.toHexString("1".getBytes(StandardCharsets.UTF_8));
        System.out.println(h2); //"31"
        h2 = "0x"+h2;
        String d5 = Hash.sha3(h2);
        System.out.println(d5); //0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6

solidity

bytes memory tt = abi.encodePacked("1");
        emit log_named_bytes("abi", tt); //0x31
        bytes32  kk = keccak256(tt);
        emit log_named_bytes32("keccak256", kk); //0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6
bytes memory tt = abi.encode("1");
        emit log_named_bytes("abi", tt); // 0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000013100000000000000000000000000000000000000000000000000000000000000
        bytes32  kk = keccak256(tt);
        emit log_named_bytes32("keccak256", kk); //0xc586dcbfc973643dc5f885bf1a38e054d2675b03fe283a5b7337d70dda9f7171
String inputstr = TypeEncoder.encode( new DynamicStruct((new Utf8String("1"))));
        String hashstr = Hash.sha3String(inputstr);
        inputstr = "0x"+ inputstr;
        String  h1 = Hash.sha3(inputstr);
        System.out.println(h1); //0xc586dcbfc973643dc5f885bf1a38e054d2675b03fe283a5b7337d70dda9f7171
请先 登录 后评论

其它 4 个回答

zen
请先 登录 后评论
北风凉画扇
请先 登录 后评论
北风凉画扇
请先 登录 后评论
晓道
请先 登录 后评论
  • 2 关注
  • 0 收藏,7086 浏览
  • 北风凉画扇 提出于 2022-04-20 16:54