Is there any implementation of HMAC-SHA1 or HMAC-SHA256 or any other hashing algorithms for solidity? I found this but it's not working.
2 Answers
Solidity has the primitives you would need for some HMAC functions, namely several hashing functions. As you pointed out, other hashing functions could be implemented, but hashing in the Ethereum VM will generally be expensive in terms of gas.
Depending on the problem you're trying to solve, you may find that computing HMAC signatures off-chain and storing them on-chain is more practical. This could be signed with an Ethereum private key, which could be verified by the contract.
-
Thank you. I'm working on my own private network so the gas consumption is not a limitation for this case. Dec 29, 2018 at 8:23
After some searching I found KeyDeriv library which contains the HMAC-Sha256 implementation. Here is the link in case of someone else needed this. This is the hmac-sha256 function code:
function _hmacsha256(bytes memory key, bytes memory message) internal pure returns (bytes32) {
bytes32 keyl;
bytes32 keyr;
uint i;
if (key.length > 64) {
keyl = sha256(key);
} else {
for (i = 0; i < key.length && i < 32; i++)
keyl |= bytes32(uint(key[i]) * 2 ** (8 * (31 - i)));
for (i = 32; i < key.length && i < 64; i++)
keyr |= bytes32(uint(key[i]) * 2 ** (8 * (63 - i)));
}
bytes32 threesix = 0x3636363636363636363636363636363636363636363636363636363636363636;
bytes32 fivec = 0x5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c;
return sha256(fivec ^ keyl, fivec ^ keyr, sha256(threesix ^ keyl, threesix ^ keyr, message));
}