Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does abi.encodePacked(...) and sha256(..) work in Solidity?

I'm trying to implement a signature in a Solidity contract and I'm having problems when it comes to comparing hashes. I calculate the hash with the following code in solidity:

sha256(abi.encodePacked(param1, ...., paramN);

Where:

abi.encodePacked(param1, ..., paramN) = [bytes: 0x0102030405060701]

and

sha255(abi.encodePacked(param1, ..., paramN)) = [bytes32: 0x245138c905599c8579ab186fbdbd6e62396aac35a98a6568f8803eed049d1251]

The main problem I'm having is that by using python sha256 on 0102030405060701 the result I'm getting is 5bc31e3decf480124c79c114744d111ec82b62e466a097c3ced6fe76cbace9a5.

What am I doing wrong?

like image 794
Jordi Estapé Canal Avatar asked Nov 08 '22 02:11

Jordi Estapé Canal


1 Answers

The issue is that you're hashing the string "0102030405060701", but you should be hashing the bytes that hexadecimal value represents:

>>> import hashlib
>>> import binascii
>>> hashlib.sha256(b'0102030405060701').hexdigest()
'5bc31e3decf480124c79c114744d111ec82b62e466a097c3ced6fe76cbace9a5'
>>> hashlib.sha256(binascii.unhexlify('0102030405060701')).hexdigest()
'245138c905599c8579ab186fbdbd6e62396aac35a98a6568f8803eed049d1251'

Note that hashing the string yields the same (incorrect) value you mentioned in your question, but first converting to binary via unhexlify yields the correct result, matching what you got in Solidity.

like image 114
user94559 Avatar answered Nov 14 '22 03:11

user94559