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

北风凉画扇 北风凉画扇 提出于 2022-04-20 16:54 9903 浏览

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
晓道

采纳率 21% · 回答于 2022-04-20 18:28

其它 4 个回答

zen 2022-04-20 20:57
北风凉画扇 2022-04-21 10:08

写回答

你需要登录后才可以回答问题,登录