Crypto and Math functions in Solidity
An overview of the crypto functions and math functions that you can use in Solidity
Table of Contents for Crypto and Math functions in Solidity
Iβve written about using using dates/times in Solidity), but did you also know you can use built in crypto and math functions in Solidity.
keccak256
keccak256(bytes inputVal) returns (bytes32)
Returns the keccak256 hash of the bytes
input, returning a bytes32
value.
sha256
This is similar to keccak256().
sha256(bytes inputVal) returns (bytes32)
It returns the SHA256 hash value of the input bytes
ripemd160
ripemd160(bytes value) returns (bytes20)
Returns the ripemd160
hash value of the input
ecrecover
ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)
Recover an address from a elliptic curve signature. You can use this to validate a signed value. For details including important security issues to be aware of see this page
r
first 32 bytes of sigs
second 32 bytes of sigv
last byte of sig
addmod
addmod(uint x, uint y, uint k) returns (uint)
Returns (x + y) % k
. The addition part (x+y) is performed with arbitrary precision and does not wrap around at 2**256.
Assert k is != 0.
mulmod
mulmod(uint x, uint y, uint k) returns (uint)
Returns (x * y) %k)
, where the multiplication is performed with arbitrary precision and does not wrap around at 2**256.
further reading
Also see how to do floating point math in Solidity.
Spotted a typo or have a suggestion to make this crypto dev article better? Please let me know!
Next post
Previous post
π Solidity Auditing online quiz
Learn how to audit smart contracts by looking at some example code and trying to find the bugs
β½ Solidity Gas Optimizations Guide
How to optimize and reduce gas usage in your smart contracts in Solidity
π§ͺ Guide to testing with Foundry
Guide to adding testing for your Solidity contracts, using the Foundry and Forge tools
π Guide to UTXO
UTXO and the UTXO set (used by blockchains such as Bitcoin) explained
π Solidity Assembly Guide
Introduction guide to using assembly in your Solidity smart contracts
π¦ Ethereum EOF format explained
Information explaining what the upcoming Ethereum EOF format is all about