The problem occurs when generating a sha256 inside contract. This works fine:
function SimpleHash(string memory val) public returns (bytes32) {
bytes32 h = sha256(abi.encodePacked(val));
return h;
}
the h
value returned is correctly answered, and I checked it with this piece of code:
const result = await instance.SimpleHash.call('A');
console.log('function return',result);
hash = SHA256('A');
console.log('hash outside the contract', hash.toString(CryptoJS.enc.Hex));
I sent the stirng 'A'
to the contract function, and it returned:
0x559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd
Very similar to the return of the function outside the contract:
559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd
Just a single 0x
added in the beginning.
However, if I change the function to receive bytes32
as param, like this:
function SimpleHash(bytes32 val) public returns (bytes32) {
bytes32 h = sha256(abi.encodePacked(val));
return h;
}
And then change my javacript code to:
segredo = web3.utils.toHex("A");
const result = await instance.SimpleHash.call(segredo);
console.log('function return',result);
hash = SHA256('A');
console.log('hash outside the contract', hash.toString(CryptoJS.enc.Hex));
Suddenly, the sha256 values are different.
In the case above, the hash returned from the contract now is 0x037371bf62c8a2c23f8134fc2c7049fbe698860b888c98b955644c4b8f8f3155
And the correct hash is the same as the ones before.
How do I get the correct hash for the string 'A' sending it as bytes32 param? I'm sure there is something I'm mistaking when sending the param. Maybe it is related to big endian and little endian enconding? Not sure how I would change that in nodeJS thogh.