/* LibTomMath, multiple-precision integer library -- Tom St Denis1*2* LibTomMath is a library that provides multiple-precision3* integer arithmetic as well as number theoretic functionality.4*5* The library was designed directly after the MPI library by6* Michael Fromberger but has been written from scratch with7* additional optimizations in place.8*9* SPDX-License-Identifier: Unlicense10*/11#ifndef BN_H_12#define BN_H_1314#include <stdlib.h>15#include <stdint.h>16#include <limits.h>1718#define LTM_NO_FILE1920#ifdef __cplusplus21extern "C" {22#endif2324/* MS Visual C++ doesn't have a 128bit type for words, so fall back to 32bit MPI's (where words are 64bit) */25#if defined(_MSC_VER) || defined(__LLP64__) || defined(__e2k__) || defined(__LCC__)26# define MP_32BIT27#endif2829/* detect 64-bit mode if possible */30#if defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) || \31defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) || \32defined(__s390x__) || defined(__arch64__) || defined(__aarch64__) || \33defined(__sparcv9) || defined(__sparc_v9__) || defined(__sparc64__) || \34defined(__ia64) || defined(__ia64__) || defined(__itanium__) || defined(_M_IA64) || \35defined(__LP64__) || defined(_LP64) || defined(__64BIT__)36# if !(defined(MP_32BIT) || defined(MP_16BIT) || defined(MP_8BIT))37# if defined(__GNUC__)38/* we support 128bit integers only via: __attribute__((mode(TI))) */39# define MP_64BIT40# else41/* otherwise we fall back to MP_32BIT even on 64bit platforms */42# define MP_32BIT43# endif44# endif45#endif4647/* some default configurations.48*49* A "mp_digit" must be able to hold DIGIT_BIT + 1 bits50* A "mp_word" must be able to hold 2*DIGIT_BIT + 1 bits51*52* At the very least a mp_digit must be able to hold 7 bits53* [any size beyond that is ok provided it doesn't overflow the data type]54*/55#ifdef MP_8BIT56typedef uint8_t mp_digit;57typedef uint16_t mp_word;58# define MP_SIZEOF_MP_DIGIT 159# ifdef DIGIT_BIT60# error You must not define DIGIT_BIT when using MP_8BIT61# endif62#elif defined(MP_16BIT)63typedef uint16_t mp_digit;64typedef uint32_t mp_word;65# define MP_SIZEOF_MP_DIGIT 266# ifdef DIGIT_BIT67# error You must not define DIGIT_BIT when using MP_16BIT68# endif69#elif defined(MP_64BIT)70/* for GCC only on supported platforms */71typedef uint64_t mp_digit;72typedef unsigned long mp_word __attribute__((mode(TI)));73# define DIGIT_BIT 6074#else75/* this is the default case, 28-bit digits */7677/* this is to make porting into LibTomCrypt easier :-) */78typedef uint32_t mp_digit;79typedef uint64_t mp_word;8081# ifdef MP_31BIT82/* this is an extension that uses 31-bit digits */83# define DIGIT_BIT 3184# else85/* default case is 28-bit digits, defines MP_28BIT as a handy macro to test */86# define DIGIT_BIT 2887# define MP_28BIT88# endif89#endif9091/* otherwise the bits per digit is calculated automatically from the size of a mp_digit */92#ifndef DIGIT_BIT93# define DIGIT_BIT (((CHAR_BIT * MP_SIZEOF_MP_DIGIT) - 1)) /* bits per digit */94typedef uint_least32_t mp_min_u32;95#else96typedef mp_digit mp_min_u32;97#endif9899#define MP_DIGIT_BIT DIGIT_BIT100#define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))101#define MP_DIGIT_MAX MP_MASK102103/* equalities */104#define MP_LT -1 /* less than */105#define MP_EQ 0 /* equal to */106#define MP_GT 1 /* greater than */107108#define MP_ZPOS 0 /* positive integer */109#define MP_NEG 1 /* negative */110111#define MP_OKAY 0 /* ok result */112#define MP_MEM -2 /* out of mem */113#define MP_VAL -3 /* invalid input */114#define MP_RANGE MP_VAL115#define MP_ITER -4 /* Max. iterations reached */116117#define MP_YES 1 /* yes response */118#define MP_NO 0 /* no response */119120/* Primality generation flags */121#define LTM_PRIME_BBS 0x0001 /* BBS style prime */122#define LTM_PRIME_SAFE 0x0002 /* Safe prime (p-1)/2 == prime */123#define LTM_PRIME_2MSB_ON 0x0008 /* force 2nd MSB to 1 */124125typedef int mp_err;126127/* you'll have to tune these... */128extern int KARATSUBA_MUL_CUTOFF,129KARATSUBA_SQR_CUTOFF,130TOOM_MUL_CUTOFF,131TOOM_SQR_CUTOFF;132133/* define this to use lower memory usage routines (exptmods mostly) */134/* #define MP_LOW_MEM */135136/* default precision */137#ifndef MP_PREC138# ifndef MP_LOW_MEM139# define MP_PREC 32 /* default digits of precision */140# else141# define MP_PREC 8 /* default digits of precision */142# endif143#endif144145/* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */146#define MP_WARRAY (1u << (((sizeof(mp_word) * CHAR_BIT) - (2 * DIGIT_BIT)) + 1))147148/* the infamous mp_int structure */149typedef struct {150int used, alloc, sign;151mp_digit *dp;152} mp_int;153154/* callback for mp_prime_random, should fill dst with random bytes and return how many read [upto len] */155typedef int ltm_prime_callback(unsigned char *dst, int len, void *dat);156157158#define USED(m) ((m)->used)159#define DIGIT(m, k) ((m)->dp[(k)])160#define SIGN(m) ((m)->sign)161162/* error code to char* string */163const char *mp_error_to_string(int code);164165/* ---> init and deinit bignum functions <--- */166/* init a bignum */167int mp_init(mp_int *a);168169/* free a bignum */170void mp_clear(mp_int *a);171172/* init a null terminated series of arguments */173int mp_init_multi(mp_int *mp, ...);174175/* clear a null terminated series of arguments */176void mp_clear_multi(mp_int *mp, ...);177178/* exchange two ints */179void mp_exch(mp_int *a, mp_int *b);180181/* shrink ram required for a bignum */182int mp_shrink(mp_int *a);183184/* grow an int to a given size */185int mp_grow(mp_int *a, int size);186187/* init to a given number of digits */188int mp_init_size(mp_int *a, int size);189190/* ---> Basic Manipulations <--- */191#define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)192#define mp_iseven(a) ((((a)->used == 0) || (((a)->dp[0] & 1u) == 0u)) ? MP_YES : MP_NO)193#define mp_isodd(a) ((((a)->used > 0) && (((a)->dp[0] & 1u) == 1u)) ? MP_YES : MP_NO)194#define mp_isneg(a) (((a)->sign != MP_ZPOS) ? MP_YES : MP_NO)195196/* set to zero */197void mp_zero(mp_int *a);198199/* set to a digit */200void mp_set(mp_int *a, mp_digit b);201202/* set a double */203int mp_set_double(mp_int *a, double b);204205/* set a 32-bit const */206int mp_set_int(mp_int *a, unsigned long b);207208/* set a platform dependent unsigned long value */209int mp_set_long(mp_int *a, unsigned long b);210211/* set a platform dependent unsigned long long value */212int mp_set_long_long(mp_int *a, unsigned long long b);213214/* get a double */215double mp_get_double(const mp_int *a);216217/* get a 32-bit value */218unsigned long mp_get_int(const mp_int *a);219220/* get a platform dependent unsigned long value */221unsigned long mp_get_long(const mp_int *a);222223/* get a platform dependent unsigned long long value */224unsigned long long mp_get_long_long(const mp_int *a);225226/* initialize and set a digit */227int mp_init_set(mp_int *a, mp_digit b);228229/* initialize and set 32-bit value */230int mp_init_set_int(mp_int *a, unsigned long b);231232/* copy, b = a */233int mp_copy(const mp_int *a, mp_int *b);234235/* inits and copies, a = b */236int mp_init_copy(mp_int *a, const mp_int *b);237238/* trim unused digits */239void mp_clamp(mp_int *a);240241/* import binary data */242int mp_import(mp_int *rop, size_t count, int order, size_t size, int endian, size_t nails, const void *op);243244/* export binary data */245int mp_export(void *rop, size_t *countp, int order, size_t size, int endian, size_t nails, const mp_int *op);246247/* ---> digit manipulation <--- */248249/* right shift by "b" digits */250void mp_rshd(mp_int *a, int b);251252/* left shift by "b" digits */253int mp_lshd(mp_int *a, int b);254255/* c = a / 2**b, implemented as c = a >> b */256int mp_div_2d(const mp_int *a, int b, mp_int *c, mp_int *d);257258/* b = a/2 */259int mp_div_2(const mp_int *a, mp_int *b);260261/* c = a * 2**b, implemented as c = a << b */262int mp_mul_2d(const mp_int *a, int b, mp_int *c);263264/* b = a*2 */265int mp_mul_2(const mp_int *a, mp_int *b);266267/* c = a mod 2**b */268int mp_mod_2d(const mp_int *a, int b, mp_int *c);269270/* computes a = 2**b */271int mp_2expt(mp_int *a, int b);272273/* Counts the number of lsbs which are zero before the first zero bit */274int mp_cnt_lsb(const mp_int *a);275276/* I Love Earth! */277278/* makes a pseudo-random mp_int of a given size */279int mp_rand(mp_int *a, int digits);280/* makes a pseudo-random small int of a given size */281int mp_rand_digit(mp_digit *r);282283#ifdef MP_PRNG_ENABLE_LTM_RNG284/* A last resort to provide random data on systems without any of the other285* implemented ways to gather entropy.286* It is compatible with `rng_get_bytes()` from libtomcrypt so you could287* provide that one and then set `ltm_rng = rng_get_bytes;` */288extern unsigned long (*ltm_rng)(unsigned char *out, unsigned long outlen, void (*callback)(void));289extern void (*ltm_rng_callback)(void);290#endif291292/* ---> binary operations <--- */293/* c = a XOR b */294int mp_xor(const mp_int *a, const mp_int *b, mp_int *c);295296/* c = a OR b */297int mp_or(const mp_int *a, const mp_int *b, mp_int *c);298299/* c = a AND b */300int mp_and(const mp_int *a, const mp_int *b, mp_int *c);301302/* Checks the bit at position b and returns MP_YES303if the bit is 1, MP_NO if it is 0 and MP_VAL304in case of error */305int mp_get_bit(const mp_int *a, int b);306307/* c = a XOR b (two complement) */308int mp_tc_xor(const mp_int *a, const mp_int *b, mp_int *c);309310/* c = a OR b (two complement) */311int mp_tc_or(const mp_int *a, const mp_int *b, mp_int *c);312313/* c = a AND b (two complement) */314int mp_tc_and(const mp_int *a, const mp_int *b, mp_int *c);315316/* right shift (two complement) */317int mp_tc_div_2d(const mp_int *a, int b, mp_int *c);318319/* ---> Basic arithmetic <--- */320321/* b = ~a */322int mp_complement(const mp_int *a, mp_int *b);323324/* b = -a */325int mp_neg(const mp_int *a, mp_int *b);326327/* b = |a| */328int mp_abs(const mp_int *a, mp_int *b);329330/* compare a to b */331int mp_cmp(const mp_int *a, const mp_int *b);332333/* compare |a| to |b| */334int mp_cmp_mag(const mp_int *a, const mp_int *b);335336/* c = a + b */337int mp_add(const mp_int *a, const mp_int *b, mp_int *c);338339/* c = a - b */340int mp_sub(const mp_int *a, const mp_int *b, mp_int *c);341342/* c = a * b */343int mp_mul(const mp_int *a, const mp_int *b, mp_int *c);344345/* b = a*a */346int mp_sqr(const mp_int *a, mp_int *b);347348/* a/b => cb + d == a */349int mp_div(const mp_int *a, const mp_int *b, mp_int *c, mp_int *d);350351/* c = a mod b, 0 <= c < b */352int mp_mod(const mp_int *a, const mp_int *b, mp_int *c);353354/* ---> single digit functions <--- */355356/* compare against a single digit */357int mp_cmp_d(const mp_int *a, mp_digit b);358359/* c = a + b */360int mp_add_d(const mp_int *a, mp_digit b, mp_int *c);361362/* c = a - b */363int mp_sub_d(const mp_int *a, mp_digit b, mp_int *c);364365/* c = a * b */366int mp_mul_d(const mp_int *a, mp_digit b, mp_int *c);367368/* a/b => cb + d == a */369int mp_div_d(const mp_int *a, mp_digit b, mp_int *c, mp_digit *d);370371/* a/3 => 3c + d == a */372int mp_div_3(const mp_int *a, mp_int *c, mp_digit *d);373374/* c = a**b */375int mp_expt_d(const mp_int *a, mp_digit b, mp_int *c);376int mp_expt_d_ex(const mp_int *a, mp_digit b, mp_int *c, int fast);377378/* c = a mod b, 0 <= c < b */379int mp_mod_d(const mp_int *a, mp_digit b, mp_digit *c);380381/* ---> number theory <--- */382383/* d = a + b (mod c) */384int mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);385386/* d = a - b (mod c) */387int mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);388389/* d = a * b (mod c) */390int mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d);391392/* c = a * a (mod b) */393int mp_sqrmod(const mp_int *a, const mp_int *b, mp_int *c);394395/* c = 1/a (mod b) */396int mp_invmod(const mp_int *a, const mp_int *b, mp_int *c);397398/* c = (a, b) */399int mp_gcd(const mp_int *a, const mp_int *b, mp_int *c);400401/* produces value such that U1*a + U2*b = U3 */402int mp_exteuclid(const mp_int *a, const mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3);403404/* c = [a, b] or (a*b)/(a, b) */405int mp_lcm(const mp_int *a, const mp_int *b, mp_int *c);406407/* finds one of the b'th root of a, such that |c|**b <= |a|408*409* returns error if a < 0 and b is even410*/411int mp_n_root(const mp_int *a, mp_digit b, mp_int *c);412int mp_n_root_ex(const mp_int *a, mp_digit b, mp_int *c, int fast);413414/* special sqrt algo */415int mp_sqrt(const mp_int *arg, mp_int *ret);416417/* special sqrt (mod prime) */418int mp_sqrtmod_prime(const mp_int *n, const mp_int *prime, mp_int *ret);419420/* is number a square? */421int mp_is_square(const mp_int *arg, int *ret);422423/* computes the jacobi c = (a | n) (or Legendre if b is prime) */424int mp_jacobi(const mp_int *a, const mp_int *n, int *c);425426/* computes the Kronecker symbol c = (a | p) (like jacobi() but with {a,p} in Z */427int mp_kronecker(const mp_int *a, const mp_int *p, int *c);428429/* used to setup the Barrett reduction for a given modulus b */430int mp_reduce_setup(mp_int *a, const mp_int *b);431432/* Barrett Reduction, computes a (mod b) with a precomputed value c433*434* Assumes that 0 < x <= m*m, note if 0 > x > -(m*m) then you can merely435* compute the reduction as -1 * mp_reduce(mp_abs(x)) [pseudo code].436*/437int mp_reduce(mp_int *x, const mp_int *m, const mp_int *mu);438439/* setups the montgomery reduction */440int mp_montgomery_setup(const mp_int *n, mp_digit *rho);441442/* computes a = B**n mod b without division or multiplication useful for443* normalizing numbers in a Montgomery system.444*/445int mp_montgomery_calc_normalization(mp_int *a, const mp_int *b);446447/* computes x/R == x (mod N) via Montgomery Reduction */448int mp_montgomery_reduce(mp_int *x, const mp_int *n, mp_digit rho);449450/* returns 1 if a is a valid DR modulus */451int mp_dr_is_modulus(const mp_int *a);452453/* sets the value of "d" required for mp_dr_reduce */454void mp_dr_setup(const mp_int *a, mp_digit *d);455456/* reduces a modulo n using the Diminished Radix method */457int mp_dr_reduce(mp_int *x, const mp_int *n, mp_digit k);458459/* returns true if a can be reduced with mp_reduce_2k */460int mp_reduce_is_2k(const mp_int *a);461462/* determines k value for 2k reduction */463int mp_reduce_2k_setup(const mp_int *a, mp_digit *d);464465/* reduces a modulo b where b is of the form 2**p - k [0 <= a] */466int mp_reduce_2k(mp_int *a, const mp_int *n, mp_digit d);467468/* returns true if a can be reduced with mp_reduce_2k_l */469int mp_reduce_is_2k_l(const mp_int *a);470471/* determines k value for 2k reduction */472int mp_reduce_2k_setup_l(const mp_int *a, mp_int *d);473474/* reduces a modulo b where b is of the form 2**p - k [0 <= a] */475int mp_reduce_2k_l(mp_int *a, const mp_int *n, const mp_int *d);476477/* Y = G**X (mod P) */478int mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y);479480/* ---> Primes <--- */481482/* number of primes */483#ifdef MP_8BIT484# define PRIME_SIZE 31485#else486# define PRIME_SIZE 256487#endif488489/* table of first PRIME_SIZE primes */490extern const mp_digit ltm_prime_tab[PRIME_SIZE];491492/* result=1 if a is divisible by one of the first PRIME_SIZE primes */493int mp_prime_is_divisible(const mp_int *a, int *result);494495/* performs one Fermat test of "a" using base "b".496* Sets result to 0 if composite or 1 if probable prime497*/498int mp_prime_fermat(const mp_int *a, const mp_int *b, int *result);499500/* performs one Miller-Rabin test of "a" using base "b".501* Sets result to 0 if composite or 1 if probable prime502*/503int mp_prime_miller_rabin(const mp_int *a, const mp_int *b, int *result);504505/* This gives [for a given bit size] the number of trials required506* such that Miller-Rabin gives a prob of failure lower than 2^-96507*/508int mp_prime_rabin_miller_trials(int size);509510/* performs one strong Lucas-Selfridge test of "a".511* Sets result to 0 if composite or 1 if probable prime512*/513int mp_prime_strong_lucas_selfridge(const mp_int *a, int *result);514515/* performs one Frobenius test of "a" as described by Paul Underwood.516* Sets result to 0 if composite or 1 if probable prime517*/518int mp_prime_frobenius_underwood(const mp_int *N, int *result);519520/* performs t random rounds of Miller-Rabin on "a" additional to521* bases 2 and 3. Also performs an initial sieve of trial522* division. Determines if "a" is prime with probability523* of error no more than (1/4)**t.524* Both a strong Lucas-Selfridge to complete the BPSW test525* and a separate Frobenius test are available at compile time.526* With t<0 a deterministic test is run for primes up to527* 318665857834031151167461. With t<13 (abs(t)-13) additional528* tests with sequential small primes are run starting at 43.529* Is Fips 186.4 compliant if called with t as computed by530* mp_prime_rabin_miller_trials();531*532* Sets result to 1 if probably prime, 0 otherwise533*/534int mp_prime_is_prime(const mp_int *a, int t, int *result);535536/* finds the next prime after the number "a" using "t" trials537* of Miller-Rabin.538*539* bbs_style = 1 means the prime must be congruent to 3 mod 4540*/541int mp_prime_next_prime(mp_int *a, int t, int bbs_style);542543/* makes a truly random prime of a given size (bytes),544* call with bbs = 1 if you want it to be congruent to 3 mod 4545*546* You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can547* have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself548* so it can be NULL549*550* The prime generated will be larger than 2^(8*size).551*/552#define mp_prime_random(a, t, size, bbs, cb, dat) mp_prime_random_ex(a, t, ((size) * 8) + 1, (bbs==1)?LTM_PRIME_BBS:0, cb, dat)553554/* makes a truly random prime of a given size (bits),555*556* Flags are as follows:557*558* LTM_PRIME_BBS - make prime congruent to 3 mod 4559* LTM_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies LTM_PRIME_BBS)560* LTM_PRIME_2MSB_ON - make the 2nd highest bit one561*562* You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can563* have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself564* so it can be NULL565*566*/567int mp_prime_random_ex(mp_int *a, int t, int size, int flags, ltm_prime_callback cb, void *dat);568569/* ---> radix conversion <--- */570int mp_count_bits(const mp_int *a);571572int mp_unsigned_bin_size(const mp_int *a);573int mp_read_unsigned_bin(mp_int *a, const unsigned char *b, int c);574int mp_to_unsigned_bin(const mp_int *a, unsigned char *b);575int mp_to_unsigned_bin_n(const mp_int *a, unsigned char *b, unsigned long *outlen);576577int mp_signed_bin_size(const mp_int *a);578int mp_read_signed_bin(mp_int *a, const unsigned char *b, int c);579int mp_to_signed_bin(const mp_int *a, unsigned char *b);580int mp_to_signed_bin_n(const mp_int *a, unsigned char *b, unsigned long *outlen);581582int mp_read_radix(mp_int *a, const char *str, int radix);583int mp_toradix(const mp_int *a, char *str, int radix);584int mp_toradix_n(const mp_int *a, char *str, int radix, int maxlen);585int mp_radix_size(const mp_int *a, int radix, int *size);586587#ifndef LTM_NO_FILE588int mp_fread(mp_int *a, int radix, FILE *stream);589int mp_fwrite(const mp_int *a, int radix, FILE *stream);590#endif591592#define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len))593#define mp_raw_size(mp) mp_signed_bin_size(mp)594#define mp_toraw(mp, str) mp_to_signed_bin((mp), (str))595#define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len))596#define mp_mag_size(mp) mp_unsigned_bin_size(mp)597#define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str))598599#define mp_tobinary(M, S) mp_toradix((M), (S), 2)600#define mp_tooctal(M, S) mp_toradix((M), (S), 8)601#define mp_todecimal(M, S) mp_toradix((M), (S), 10)602#define mp_tohex(M, S) mp_toradix((M), (S), 16)603604#ifdef __cplusplus605}606#endif607608#endif609610611