I am wondering what the best way to store a SHA-256 hash is in solidity. The SHA-256 output is a 64 byte hex string when I pass the hash from my web app to my contract. The issue I run into is that I start getting errors such as inaccessible dynamic type when I use strings - since strings are actually just dynamically sized arrays. Any ideas?

  • SHA 256 should normally be giving you 32 bytes of output, represented by 64 hex characters. This will fit in a single standard bytes32 slot. Are you sure you're getting a 64 bytes hash? – Edmund Edgar Mar 11 '18 at 3:22

I would chop it up into two bytes32 client-side and re-assemble it client-side. The simplest form might be:

bytes32 part1;
bytes32 part2;

This is as economical as it gets, and can be passed around between contracts if needed.

Hope it helps.

p.s. If you don't need to recall them and only need to validate their existence (from some other off-chain source or claim), hashing them into a single bytes32 would provide enough precision and 50% gas reduction.


As Edmund Edgar mentioned: SHA-256 is a 32-byte hex-string, rather than 64-byte hex-string like SHA-512...

with that in mind, you CAN store a SHA-256 value in a single bytes32 variable in solidity.

Things to consider: (I assume you're using web3.js in your web-app)

  • usually SHA-256 generates ready-made 32-byte hex-strings (64 hex characters)

  • that means you should not transform your hash into hex again with web3.fromascii(...), that would treat your hex-hash as an ascii-string and stretch it to 64 bytes (since one ascii-char is represented by 2 hex-chars. If you try to import the 64-byte-string to solidity, it won't fit into a bytes32 variable and solidity will crop it to 32 bytes.

  • so to actually get your 32-byte-hash into solidity you simply prepend "0x" to your 32-byte-hex-hash, which means, that solidity will recognize it as hex; you can then define a solidity function á la importHash(bytes32 someHash) that will accept your 32-byte hash. then store it in a bytes32 state variable or use it as mapping key.

  • of course, in case you actually use SHA-512, then Rob Hitchens B9lab's option is probably your best option.

Your Answer

