New to blockchain software development? Read my beginners guide here

Crypto and Math functions in Solidity

Created on August 2022 β€’ Tags: ethereumsolidityguides

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 sig
  • s second 32 bytes of sig
  • v 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!

See all posts (70+ more)

See all posts (70+ more)

Was this post helpful? πŸ“§

If you liked this content and want to receive emails about future posts like this, enter your email. I'll never spam you.

Or follow me on @CryptoGuide_Dev on twitter

By using this site, you agree that you have read and understand its Privacy Policy and Terms of Use.
Use any information on this site at your own risk, I take no responsibility for the accuracy of safety of the information on this site.