1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
3 * LibTomMath is a library that provides multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
6 * The library was designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
10 * The library is free for all purposes without any express
13 * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
18 #include "tclTomMathDecls.h"
20 #define MODULE_SCOPE extern
26 # define MIN(x,y) ((x)<(y)?(x):(y))
30 # define MAX(x,y) ((x)>(y)?(x):(y))
36 /* C++ compilers don't like assigning void * to mp_digit * */
37 #define OPT_CAST(x) (x *)
41 /* C on the other hand doesn't care */
47 /* detect 64-bit mode if possible */
48 #if defined(NEVER) /* 128-bit ints fail in too many places */
49 # if !(defined(MP_64BIT) && defined(MP_16BIT) && defined(MP_8BIT))
54 /* some default configurations.
56 * A "mp_digit" must be able to hold DIGIT_BIT + 1 bits
57 * A "mp_word" must be able to hold 2*DIGIT_BIT + 1 bits
59 * At the very least a mp_digit must be able to hold 7 bits
60 * [any size beyond that is ok provided it doesn't overflow the data type]
63 #ifndef MP_DIGIT_DECLARED
64 typedef unsigned char mp_digit;
65 #define MP_DIGIT_DECLARED
67 typedef unsigned short mp_word;
68 #elif defined(MP_16BIT)
69 #ifndef MP_DIGIT_DECLARED
70 typedef unsigned short mp_digit;
71 #define MP_DIGIT_DECLARED
73 typedef unsigned long mp_word;
74 #elif defined(MP_64BIT)
75 /* for GCC only on supported platforms */
77 typedef unsigned long long ulong64;
78 typedef signed long long long64;
81 #ifndef MP_DIGIT_DECLARED
82 typedef unsigned long mp_digit;
83 #define MP_DIGIT_DECLARED
85 typedef unsigned long mp_word __attribute__ ((mode(TI)));
89 /* this is the default case, 28-bit digits */
91 /* this is to make porting into LibTomCrypt easier :-) */
93 # if defined(_MSC_VER) || defined(__BORLANDC__)
94 typedef unsigned __int64 ulong64;
95 typedef signed __int64 long64;
97 typedef unsigned long long ulong64;
98 typedef signed long long long64;
102 #ifndef MP_DIGIT_DECLARED
103 typedef unsigned int mp_digit;
104 #define MP_DIGIT_DECLARED
106 typedef ulong64 mp_word;
109 /* this is an extension that uses 31-bit digits */
110 # define DIGIT_BIT 31
112 /* default case is 28-bit digits, defines MP_28BIT as a handy macro to test */
113 # define DIGIT_BIT 28
118 /* define heap macros */
119 #if 0 /* these are macros in tclTomMathDecls.h */
121 /* default to libc stuff */
123 # define XMALLOC malloc
125 # define XREALLOC realloc
126 # define XCALLOC calloc
128 /* prototypes for our heap functions */
129 extern void *XMALLOC(size_t n);
130 extern void *XREALLOC(void *p, size_t n);
131 extern void *XCALLOC(size_t n, size_t s);
132 extern void XFREE(void *p);
138 /* otherwise the bits per digit is calculated automatically from the size of a mp_digit */
140 # define DIGIT_BIT ((int)((CHAR_BIT * sizeof(mp_digit) - 1))) /* bits per digit */
143 #define MP_DIGIT_BIT DIGIT_BIT
144 #define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))
145 #define MP_DIGIT_MAX MP_MASK
148 #define MP_LT -1 /* less than */
149 #define MP_EQ 0 /* equal to */
150 #define MP_GT 1 /* greater than */
152 #define MP_ZPOS 0 /* positive integer */
153 #define MP_NEG 1 /* negative */
155 #define MP_OKAY 0 /* ok result */
156 #define MP_MEM -2 /* out of mem */
157 #define MP_VAL -3 /* invalid input */
158 #define MP_RANGE MP_VAL
160 #define MP_YES 1 /* yes response */
161 #define MP_NO 0 /* no response */
163 /* Primality generation flags */
164 #define LTM_PRIME_BBS 0x0001 /* BBS style prime */
165 #define LTM_PRIME_SAFE 0x0002 /* Safe prime (p-1)/2 == prime */
166 #define LTM_PRIME_2MSB_ON 0x0008 /* force 2nd MSB to 1 */
170 /* you'll have to tune these... */
171 #if defined(BUILD_tcl) || !defined(_WIN32)
172 MODULE_SCOPE int KARATSUBA_MUL_CUTOFF,
173 KARATSUBA_SQR_CUTOFF,
178 /* define this to use lower memory usage routines (exptmods mostly) */
179 /* #define MP_LOW_MEM */
181 /* default precision */
184 # define MP_PREC 32 /* default digits of precision */
186 # define MP_PREC 8 /* default digits of precision */
190 /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
191 #define MP_WARRAY (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1))
193 /* the infamous mp_int structure */
194 #ifndef MP_INT_DECLARED
195 #define MP_INT_DECLARED
196 typedef struct mp_int mp_int;
199 int used, alloc, sign;
203 /* callback for mp_prime_random, should fill dst with random bytes and return how many read [upto len] */
204 typedef int ltm_prime_callback(unsigned char *dst, int len, void *dat);
207 #define USED(m) ((m)->used)
208 #define DIGIT(m,k) ((m)->dp[(k)])
209 #define SIGN(m) ((m)->sign)
211 /* error code to char* string */
213 char *mp_error_to_string(int code);
216 /* ---> init and deinit bignum functions <--- */
219 int mp_init(mp_int *a);
224 void mp_clear(mp_int *a);
227 /* init a null terminated series of arguments */
229 int mp_init_multi(mp_int *mp, ...);
232 /* clear a null terminated series of arguments */
234 void mp_clear_multi(mp_int *mp, ...);
237 /* exchange two ints */
239 void mp_exch(mp_int *a, mp_int *b);
242 /* shrink ram required for a bignum */
244 int mp_shrink(mp_int *a);
247 /* grow an int to a given size */
249 int mp_grow(mp_int *a, int size);
252 /* init to a given number of digits */
254 int mp_init_size(mp_int *a, int size);
257 /* ---> Basic Manipulations <--- */
258 #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
259 #define mp_iseven(a) (((a)->used == 0 || (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO)
260 #define mp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO)
264 void mp_zero(mp_int *a);
269 void mp_set(mp_int *a, mp_digit b);
272 /* set a 32-bit const */
274 int mp_set_int(mp_int *a, unsigned long b);
277 /* get a 32-bit value */
278 unsigned long mp_get_int(mp_int * a);
280 /* initialize and set a digit */
282 int mp_init_set (mp_int * a, mp_digit b);
285 /* initialize and set 32-bit value */
287 int mp_init_set_int (mp_int * a, unsigned long b);
292 int mp_copy(const mp_int *a, mp_int *b);
295 /* inits and copies, a = b */
297 int mp_init_copy(mp_int *a, mp_int *b);
300 /* trim unused digits */
302 void mp_clamp(mp_int *a);
305 /* ---> digit manipulation <--- */
307 /* right shift by "b" digits */
309 void mp_rshd(mp_int *a, int b);
312 /* left shift by "b" digits */
314 int mp_lshd(mp_int *a, int b);
319 int mp_div_2d(const mp_int *a, int b, mp_int *c, mp_int *d);
324 int mp_div_2(mp_int *a, mp_int *b);
329 int mp_mul_2d(const mp_int *a, int b, mp_int *c);
334 int mp_mul_2(mp_int *a, mp_int *b);
339 int mp_mod_2d(const mp_int *a, int b, mp_int *c);
342 /* computes a = 2**b */
344 int mp_2expt(mp_int *a, int b);
347 /* Counts the number of lsbs which are zero before the first zero bit */
349 int mp_cnt_lsb(mp_int *a);
354 /* makes a pseudo-random int of a given size */
356 int mp_rand(mp_int *a, int digits);
359 /* ---> binary operations <--- */
362 int mp_xor(mp_int *a, mp_int *b, mp_int *c);
367 int mp_or(mp_int *a, mp_int *b, mp_int *c);
372 int mp_and(mp_int *a, mp_int *b, mp_int *c);
375 /* ---> Basic arithmetic <--- */
379 int mp_neg(const mp_int *a, mp_int *b);
384 int mp_abs(mp_int *a, mp_int *b);
389 int mp_cmp(const mp_int *a, const mp_int *b);
392 /* compare |a| to |b| */
394 int mp_cmp_mag(const mp_int *a, const mp_int *b);
399 int mp_add(mp_int *a, mp_int *b, mp_int *c);
404 int mp_sub(mp_int *a, mp_int *b, mp_int *c);
409 int mp_mul(mp_int *a, mp_int *b, mp_int *c);
414 int mp_sqr(mp_int *a, mp_int *b);
417 /* a/b => cb + d == a */
419 int mp_div(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
422 /* c = a mod b, 0 <= c < b */
424 int mp_mod(mp_int *a, mp_int *b, mp_int *c);
427 /* ---> single digit functions <--- */
429 /* compare against a single digit */
431 int mp_cmp_d(const mp_int *a, mp_digit b);
436 int mp_add_d(mp_int *a, mp_digit b, mp_int *c);
441 int mp_sub_d(mp_int *a, mp_digit b, mp_int *c);
446 int mp_mul_d(mp_int *a, mp_digit b, mp_int *c);
449 /* a/b => cb + d == a */
451 int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d);
454 /* a/3 => 3c + d == a */
456 int mp_div_3(mp_int *a, mp_int *c, mp_digit *d);
461 int mp_expt_d(mp_int *a, mp_digit b, mp_int *c);
464 /* c = a mod b, 0 <= c < b */
466 int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c);
469 /* ---> number theory <--- */
471 /* d = a + b (mod c) */
473 int mp_addmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
476 /* d = a - b (mod c) */
478 int mp_submod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
481 /* d = a * b (mod c) */
483 int mp_mulmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
486 /* c = a * a (mod b) */
488 int mp_sqrmod(mp_int *a, mp_int *b, mp_int *c);
491 /* c = 1/a (mod b) */
493 int mp_invmod(mp_int *a, mp_int *b, mp_int *c);
498 int mp_gcd(mp_int *a, mp_int *b, mp_int *c);
501 /* produces value such that U1*a + U2*b = U3 */
503 int mp_exteuclid(mp_int *a, mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3);
506 /* c = [a, b] or (a*b)/(a, b) */
508 int mp_lcm(mp_int *a, mp_int *b, mp_int *c);
511 /* finds one of the b'th root of a, such that |c|**b <= |a|
513 * returns error if a < 0 and b is even
516 int mp_n_root(mp_int *a, mp_digit b, mp_int *c);
519 /* special sqrt algo */
521 int mp_sqrt(mp_int *arg, mp_int *ret);
524 /* is number a square? */
526 int mp_is_square(mp_int *arg, int *ret);
529 /* computes the jacobi c = (a | n) (or Legendre if b is prime) */
531 int mp_jacobi(mp_int *a, mp_int *n, int *c);
534 /* used to setup the Barrett reduction for a given modulus b */
536 int mp_reduce_setup(mp_int *a, mp_int *b);
539 /* Barrett Reduction, computes a (mod b) with a precomputed value c
541 * Assumes that 0 < a <= b*b, note if 0 > a > -(b*b) then you can merely
542 * compute the reduction as -1 * mp_reduce(mp_abs(a)) [pseudo code].
545 int mp_reduce(mp_int *a, mp_int *b, mp_int *c);
548 /* setups the montgomery reduction */
550 int mp_montgomery_setup(mp_int *a, mp_digit *mp);
553 /* computes a = B**n mod b without division or multiplication useful for
554 * normalizing numbers in a Montgomery system.
557 int mp_montgomery_calc_normalization(mp_int *a, mp_int *b);
560 /* computes x/R == x (mod N) via Montgomery Reduction */
562 int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
565 /* returns 1 if a is a valid DR modulus */
567 int mp_dr_is_modulus(mp_int *a);
570 /* sets the value of "d" required for mp_dr_reduce */
572 void mp_dr_setup(mp_int *a, mp_digit *d);
575 /* reduces a modulo b using the Diminished Radix method */
577 int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp);
580 /* returns true if a can be reduced with mp_reduce_2k */
582 int mp_reduce_is_2k(mp_int *a);
585 /* determines k value for 2k reduction */
587 int mp_reduce_2k_setup(mp_int *a, mp_digit *d);
590 /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
592 int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d);
595 /* returns true if a can be reduced with mp_reduce_2k_l */
597 int mp_reduce_is_2k_l(mp_int *a);
600 /* determines k value for 2k reduction */
602 int mp_reduce_2k_setup_l(mp_int *a, mp_int *d);
605 /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
607 int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d);
610 /* d = a**b (mod c) */
612 int mp_exptmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
615 /* ---> Primes <--- */
617 /* number of primes */
619 # define PRIME_SIZE 31
621 # define PRIME_SIZE 256
624 /* table of first PRIME_SIZE primes */
625 #if defined(BUILD_tcl) || !defined(_WIN32)
626 MODULE_SCOPE const mp_digit ltm_prime_tab[];
629 /* result=1 if a is divisible by one of the first PRIME_SIZE primes */
631 int mp_prime_is_divisible(mp_int *a, int *result);
634 /* performs one Fermat test of "a" using base "b".
635 * Sets result to 0 if composite or 1 if probable prime
638 int mp_prime_fermat(mp_int *a, mp_int *b, int *result);
641 /* performs one Miller-Rabin test of "a" using base "b".
642 * Sets result to 0 if composite or 1 if probable prime
645 int mp_prime_miller_rabin(mp_int *a, mp_int *b, int *result);
648 /* This gives [for a given bit size] the number of trials required
649 * such that Miller-Rabin gives a prob of failure lower than 2^-96
652 int mp_prime_rabin_miller_trials(int size);
655 /* performs t rounds of Miller-Rabin on "a" using the first
656 * t prime bases. Also performs an initial sieve of trial
657 * division. Determines if "a" is prime with probability
658 * of error no more than (1/4)**t.
660 * Sets result to 1 if probably prime, 0 otherwise
663 int mp_prime_is_prime(mp_int *a, int t, int *result);
666 /* finds the next prime after the number "a" using "t" trials
669 * bbs_style = 1 means the prime must be congruent to 3 mod 4
672 int mp_prime_next_prime(mp_int *a, int t, int bbs_style);
675 /* makes a truly random prime of a given size (bytes),
676 * call with bbs = 1 if you want it to be congruent to 3 mod 4
678 * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
679 * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
682 * The prime generated will be larger than 2^(8*size).
684 #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)
686 /* makes a truly random prime of a given size (bits),
688 * Flags are as follows:
690 * LTM_PRIME_BBS - make prime congruent to 3 mod 4
691 * LTM_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies LTM_PRIME_BBS)
692 * LTM_PRIME_2MSB_OFF - make the 2nd highest bit zero
693 * LTM_PRIME_2MSB_ON - make the 2nd highest bit one
695 * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
696 * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
701 int mp_prime_random_ex(mp_int *a, int t, int size, int flags, ltm_prime_callback cb, void *dat);
704 /* ---> radix conversion <--- */
706 int mp_count_bits(const mp_int *a);
710 int mp_unsigned_bin_size(mp_int *a);
713 int mp_read_unsigned_bin(mp_int *a, const unsigned char *b, int c);
716 int mp_to_unsigned_bin(mp_int *a, unsigned char *b);
719 int mp_to_unsigned_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen);
723 int mp_signed_bin_size(mp_int *a);
726 int mp_read_signed_bin(mp_int *a, const unsigned char *b, int c);
729 int mp_to_signed_bin(mp_int *a, unsigned char *b);
732 int mp_to_signed_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen);
736 int mp_read_radix(mp_int *a, const char *str, int radix);
739 int mp_toradix(mp_int *a, char *str, int radix);
742 int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen);
745 int mp_radix_size(mp_int *a, int radix, int *size);
749 int mp_fread(mp_int *a, int radix, FILE *stream);
752 int mp_fwrite(mp_int *a, int radix, FILE *stream);
755 #define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len))
756 #define mp_raw_size(mp) mp_signed_bin_size(mp)
757 #define mp_toraw(mp, str) mp_to_signed_bin((mp), (str))
758 #define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len))
759 #define mp_mag_size(mp) mp_unsigned_bin_size(mp)
760 #define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str))
762 #define mp_tobinary(M, S) mp_toradix((M), (S), 2)
763 #define mp_tooctal(M, S) mp_toradix((M), (S), 8)
764 #define mp_todecimal(M, S) mp_toradix((M), (S), 10)
765 #define mp_tohex(M, S) mp_toradix((M), (S), 16)
767 /* lowlevel functions, do not call! */
769 int s_mp_add(mp_int *a, mp_int *b, mp_int *c);
772 int s_mp_sub(mp_int *a, mp_int *b, mp_int *c);
774 #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
776 int fast_s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
779 int s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
782 int fast_s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
785 int s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
788 int fast_s_mp_sqr(mp_int *a, mp_int *b);
791 int s_mp_sqr(mp_int *a, mp_int *b);
794 int mp_karatsuba_mul(mp_int *a, mp_int *b, mp_int *c);
797 int mp_toom_mul(mp_int *a, mp_int *b, mp_int *c);
800 int mp_karatsuba_sqr(mp_int *a, mp_int *b);
803 int mp_toom_sqr(mp_int *a, mp_int *b);
806 int fast_mp_invmod(mp_int *a, mp_int *b, mp_int *c);
809 int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c);
812 int fast_mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
815 int mp_exptmod_fast(mp_int *G, mp_int *X, mp_int *P, mp_int *Y, int mode);
818 int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int mode);
821 void bn_reverse(unsigned char *s, int len);
824 #if defined(BUILD_tcl) || !defined(_WIN32)
825 MODULE_SCOPE const char *mp_s_rmap;