Skip to content

Commit

Permalink
Also normalize the output of keccak_256.
Browse files Browse the repository at this point in the history
  • Loading branch information
sifislag committed Jun 11, 2024
1 parent f5796f6 commit 9fd6d8c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 6 additions & 5 deletions keccak256.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ extern "C"
Keccak_HashUpdate(&hi, (const unsigned char*)input, strlen(input) * 8);
Keccak_HashFinal(&hi, (unsigned char*)out);

for (int i = 0; i < 32; ++i) {
unsigned char c = out[i];
out_str[2 + 2*i] = num_to_hex(c >> 4);
out_str[2 + 2*i + 1] = num_to_hex(c & 0x0f);
}
// this part is needed to normalize the hexadecimal output
string str_result;
boost::algorithm::hex(out, out + 32, std::back_inserter(str_result));
transform(str_result.begin(), str_result.end(), str_result.begin(), ::tolower);
str_result.erase(0, str_result.find_first_not_of('0'));
strcpy(out_str+2, str_result.c_str());;

return out_str;
}
Expand Down
10 changes: 10 additions & 0 deletions keccak256_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ BOOST_AUTO_TEST_CASE(test_hash_signature) {
);
}

// output has leading zeros, we normalize that
BOOST_AUTO_TEST_CASE(test_hash_signature_needs_normalization) {
BOOST_TEST(
keccak_256("approve(address,uint256)")
==
"0x95ea7b334ae44009aa867bfb386f5c3b4b443ac6f0ee573fa91c4608fbadfba"
);
}

BOOST_AUTO_TEST_CASE(test_hex_to_str) {
BOOST_TEST(
hex_to_str("0x72656365697665417070726f76616c28616464726573732c75696e743235362c616464726573732c627974657329")
Expand Down Expand Up @@ -59,6 +68,7 @@ BOOST_AUTO_TEST_CASE(test_hash_hex_keccak_256_two_bytes) {
);
}

// output has leading zeros, we normalize that
BOOST_AUTO_TEST_CASE(test_hash_hex_keccak_256_needs_normalization) {
BOOST_TEST(
hex_keccak_256("0x0000000000000000000000000000000000000000000000000000000000000005")
Expand Down

0 comments on commit 9fd6d8c

Please sign in to comment.