I created a solidity function with bytes32 array
function addHashes(bytes32[] memory _hashes){
}
to store SHA256 strings into ethereum blockchain. initially, I used string[] in place of bytes32[] since string[] is an experimental feature. so I changed it to bytes32[].
to create sha256 hashes i am using crypto-js nodejs library.
var hash = CryptoJS.SHA256("Message");
​
hash.toString(CryptoJS.enc.Hex)
> "2f77668a9dfbf8d5848b9eeb4a7145ca94c6ed9236e4a773f6dcafa5132b2f91";
and to connect with blockchain and interact with deployed contract i am using ethers.js.
When i convert this hash to byte32. i am getting below error
> ethers.utils.formatBytes32String("2f77668a9dfbf8d5848b9eeb4a7145ca94c6ed9236e4a773f6dcafa5132b2f91")
Uncaught Error: bytes32 string must be less than 32 bytes
at Object.formatBytes32String (/home/node_modules/ethers/utils/utf8.js:164:15)
I know the error says the hash should be 32 length string. But SHA-256 is 256-bit (32-byte)
How can i resolve this issue .
Thanks
The formatBytes32String function is for converting strings to non-prefixed binary data representation, it shouldn’t have anything to do with a hash.
The hash itself is already a bytes32, you can just use it. Coming from crypto you will need to prefix it with a “0x” though, or you could use ethers.utils.sha256(ethers.utils.toUtf8Bytes(“message”)) which produces the “0x”-prefixed hash.
Make sense? :)
Thanks a lot . it works !! .
Most helpful comment
The formatBytes32String function is for converting strings to non-prefixed binary data representation, it shouldn’t have anything to do with a hash.
The hash itself is already a bytes32, you can just use it. Coming from crypto you will need to prefix it with a “0x” though, or you could use ethers.utils.sha256(ethers.utils.toUtf8Bytes(“message”)) which produces the “0x”-prefixed hash.
Make sense? :)