Modular Arithmetic Library
modular_math
is a Rust library designed for high-performance modular arithmetic operations on 256-bit integers (U256
). This library provides robust functionalities such as
- Modular Arithmetic
- addition
- subtraction
- multiplication
- exponentiation
- inverse
- divide
- square
- square root (tonelli shanks algorithm)
- equivalent (congruent)
- Elliptical Curves
- Point addition
- Point doubling
- Scalar multiplication
- Scalar multiplication with Generator Point
- BN128 Curve
- Secp256k1 Curve
- Galois Fields (Work in Progress)
- Polynomial
under a specified modulus, specifically optimized for cryptographic and zero knowledge applications where such operations are frequently required.
Features
- Comprehensive Modular Arithmetic and Elliptical Curves: Offers all the necessary modular arithmetic operations on
U256
and BN128 and Secp256k1 elliptic curves. - Safe Overflow Management: Utilizes
U512
for intermediate results to prevent overflows. - Flexible Type Support: Features
IntoU256
trait to convert various integer and string types toU256
. - High Performance: Optimized for performance without compromising on accuracy, especially suitable for cryptographic and zero knowledge applications.
- Ease of Use Macros : Provides macros for easy usage of number under a modulus.
Structure
The workspace is organized as follows:
- src/curves/: Contains the implementation of elliptic curves and points on the curve.
- src/galois_field/: Contains the implementation of Galois fields, which are used in the elliptic curve operations.
- src/mod_math/: Contains modular arithmetic functions.
- src/num_mod/: Contains the implementation of a number modulo some modulus.
Usage
First, add this to your Cargo.toml
:
[]
= "0.1.6"
ModMath
use ModMath;
use U256;
let modulus = "101";
let mod_math = new;
// Addition
let sum = mod_math.add;
assert_eq!;
// Subtraction
let sub = mod_math.sub;
assert_eq!;
// Multiplication
let mul = mod_math.mul;
assert_eq!;
// Multiplicative Inverse
let inv = mod_math.inv;
assert_eq!;
// Exponentiation
let exp = mod_math.exp;
assert_eq!;
// FromStr
let mod_math = new;
let div = mod_math.div;
assert_eq!;
Elliptic Curves
Create an Elliptic Curve
use U256;
use ;
BN128 Usage
use BN128;
use U256;
let bn128 = BN128;
let G = bn128.G;
// Scalar Multiplication
let double_G = bn128.point_multiplication_scalar;
// Point Addition
let triple_G = bn128.point_addition;
// Point Doubling
let quad_G = bn128.point_doubling;
Number Under Modulus
use NumberUnderMod as NM;
use U256;
use num_mod;
// Add
let a = num_mod!;
let b = num_mod!;
let sum = a + b;
assert_eq!;
// Sub
let sub = a - b;
assert_eq!;
// Mul
let mul = a * b;
assert_eq!;
// Div
let div = a / b;
assert_eq!;
// Neg
let neg = -a;
assert_eq!;
let c = num_mod!;
assert!;
Todo
- Square root under modulus
- Additive Inverse
- BigNumber Tests
- Elliptic Curves
- Galois Field
- Bilinear Pairing
License
This project is licensed under the MIT License - see the LICENSE file for details.