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
24 #include "tma_class.h"
26 /* Assure these -Pekka */
32 #define MIN(x,y) ((x)<(y)?(x):(y))
36 #define MAX(x,y) ((x)>(y)?(x):(y))
42 /* C++ compilers don't like assigning void * to tma_mp_digit * */
43 #define OPT_CAST(x) (x *)
47 /* C on the other hand doesn't care */
53 /* detect 64-bit mode if possible */
54 #if defined(__x86_64__)
55 #if !(defined(MP_64BIT) && defined(MP_16BIT) && defined(MP_8BIT))
60 /* some default configurations.
62 * A "tma_mp_digit" must be able to hold DIGIT_BIT + 1 bits
63 * A "tma_mp_word" must be able to hold 2*DIGIT_BIT + 1 bits
65 * At the very least a tma_mp_digit must be able to hold 7 bits
66 * [any size beyond that is ok provided it doesn't overflow the data type]
69 typedef unsigned char tma_mp_digit;
70 typedef unsigned short tma_mp_word;
71 #elif defined(MP_16BIT)
72 typedef unsigned short tma_mp_digit;
73 typedef unsigned long tma_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 typedef unsigned long tma_mp_digit;
82 typedef unsigned long tma_mp_word __attribute__ ((mode(TI)));
86 /* this is the default case, 28-bit digits */
88 /* this is to make porting into LibTomCrypt easier :-) */
90 #if defined(_MSC_VER) || defined(__BORLANDC__)
91 typedef unsigned __int64 ulong64;
92 typedef signed __int64 long64;
94 typedef unsigned long long ulong64;
95 typedef signed long long long64;
99 typedef unsigned long tma_mp_digit;
100 typedef ulong64 tma_mp_word;
103 /* this is an extension that uses 31-bit digits */
106 /* default case is 28-bit digits, defines MP_28BIT as a handy macro to test */
112 /* define heap macros */
114 /* default to libc stuff */
116 #define XMALLOC malloc
118 #define XREALLOC realloc
119 #define XCALLOC calloc
121 /* prototypes for our heap functions */
122 extern void *XMALLOC(size_t n);
123 extern void *XREALLOC(void *p, size_t n);
124 extern void *XCALLOC(size_t n, size_t s);
125 extern void XFREE(void *p);
130 /* otherwise the bits per digit is calculated automatically from the size of a tma_mp_digit */
132 #define DIGIT_BIT ((int)((CHAR_BIT * sizeof(tma_mp_digit) - 1))) /* bits per digit */
135 #define MP_DIGIT_BIT DIGIT_BIT
136 #define MP_MASK ((((tma_mp_digit)1)<<((tma_mp_digit)DIGIT_BIT))-((tma_mp_digit)1))
137 #define MP_DIGIT_MAX MP_MASK
140 #define MP_LT -1 /* less than */
141 #define MP_EQ 0 /* equal to */
142 #define MP_GT 1 /* greater than */
144 #define MP_ZPOS 0 /* positive integer */
145 #define MP_NEG 1 /* negative */
147 #define MP_OKAY 0 /* ok result */
148 #define MP_MEM -2 /* out of mem */
149 #define MP_VAL -3 /* invalid input */
150 #define MP_RANGE MP_VAL
152 #define MP_YES 1 /* yes response */
153 #define MP_NO 0 /* no response */
155 /* Primality generation flags */
156 #define LTM_PRIME_BBS 0x0001 /* BBS style prime */
157 #define LTM_PRIME_SAFE 0x0002 /* Safe prime (p-1)/2 == prime */
158 #define LTM_PRIME_2MSB_ON 0x0008 /* force 2nd MSB to 1 */
160 typedef int tma_mp_err;
162 /* you'll have to tune these... */
163 extern int KARATSUBA_MUL_CUTOFF,
164 KARATSUBA_SQR_CUTOFF,
168 /* define this to use lower memory usage routines (exptmods mostly) */
169 /* #define MP_LOW_MEM */
171 /* default precision */
174 #define MP_PREC 32 /* default digits of precision */
176 #define MP_PREC 8 /* default digits of precision */
180 /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
181 #define MP_WARRAY (1 << (sizeof(tma_mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1))
183 /* the infamous tma_mp_int structure */
185 int used, alloc, sign;
189 /* callback for tma_mp_prime_random, should fill dst with random bytes and return how many read [upto len] */
190 typedef int ltm_prime_callback(unsigned char *dst, int len, void *dat);
193 #define USED(m) ((m)->used)
194 #define DIGIT(m,k) ((m)->dp[(k)])
195 #define SIGN(m) ((m)->sign)
197 /* error code to char* string */
198 char *tma_mp_error_to_string(int code);
200 /* ---> init and deinit bignum functions <--- */
202 int tma_mp_init(tma_mp_int *a);
205 void tma_mp_clear(tma_mp_int *a);
207 /* init a null terminated series of arguments */
208 int tma_mp_init_multi(tma_mp_int *mp, ...);
210 /* clear a null terminated series of arguments */
211 void tma_mp_clear_multi(tma_mp_int *mp, ...);
213 /* exchange two ints */
214 void tma_mp_exch(tma_mp_int *a, tma_mp_int *b);
216 /* shrink ram required for a bignum */
217 int tma_mp_shrink(tma_mp_int *a);
219 /* grow an int to a given size */
220 int tma_mp_grow(tma_mp_int *a, int size);
222 /* init to a given number of digits */
223 int tma_mp_init_size(tma_mp_int *a, int size);
225 /* ---> Basic Manipulations <--- */
226 #define tma_mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
227 #define tma_mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO)
228 #define tma_mp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO)
231 void tma_mp_zero(tma_mp_int *a);
234 void tma_mp_set(tma_mp_int *a, tma_mp_digit b);
236 /* set a 32-bit const */
237 int tma_mp_set_int(tma_mp_int *a, unsigned long b);
239 /* get a 32-bit value */
240 unsigned long tma_mp_get_int(tma_mp_int * a);
242 /* initialize and set a digit */
243 int tma_mp_init_set (tma_mp_int * a, tma_mp_digit b);
245 /* initialize and set 32-bit value */
246 int tma_mp_init_set_int (tma_mp_int * a, unsigned long b);
249 int tma_mp_copy(tma_mp_int *a, tma_mp_int *b);
251 /* inits and copies, a = b */
252 int tma_mp_init_copy(tma_mp_int *a, tma_mp_int *b);
254 /* trim unused digits */
255 void tma_mp_clamp(tma_mp_int *a);
257 /* ---> digit manipulation <--- */
259 /* right shift by "b" digits */
260 void tma_mp_rshd(tma_mp_int *a, int b);
262 /* left shift by "b" digits */
263 int tma_mp_lshd(tma_mp_int *a, int b);
266 int tma_mp_div_2d(tma_mp_int *a, int b, tma_mp_int *c, tma_mp_int *d);
269 int tma_mp_div_2(tma_mp_int *a, tma_mp_int *b);
272 int tma_mp_mul_2d(tma_mp_int *a, int b, tma_mp_int *c);
275 int tma_mp_mul_2(tma_mp_int *a, tma_mp_int *b);
278 int tma_mp_mod_2d(tma_mp_int *a, int b, tma_mp_int *c);
280 /* computes a = 2**b */
281 int tma_mp_2expt(tma_mp_int *a, int b);
283 /* Counts the number of lsbs which are zero before the first zero bit */
284 int tma_mp_cnt_lsb(tma_mp_int *a);
288 /* makes a pseudo-random int of a given size */
289 int tma_mp_rand(tma_mp_int *a, int digits);
291 /* ---> binary operations <--- */
293 int tma_mp_xor(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
296 int tma_mp_or(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
299 int tma_mp_and(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
301 /* ---> Basic arithmetic <--- */
304 int tma_mp_neg(tma_mp_int *a, tma_mp_int *b);
307 int tma_mp_abs(tma_mp_int *a, tma_mp_int *b);
310 int tma_mp_cmp(tma_mp_int *a, tma_mp_int *b);
312 /* compare |a| to |b| */
313 int tma_mp_cmp_mag(tma_mp_int *a, tma_mp_int *b);
316 int tma_mp_add(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
319 int tma_mp_sub(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
322 int tma_mp_mul(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
325 int tma_mp_sqr(tma_mp_int *a, tma_mp_int *b);
327 /* a/b => cb + d == a */
328 int tma_mp_div(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, tma_mp_int *d);
330 /* c = a mod b, 0 <= c < b */
331 int tma_mp_mod(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
333 /* ---> single digit functions <--- */
335 /* compare against a single digit */
336 int tma_mp_cmp_d(tma_mp_int *a, tma_mp_digit b);
339 int tma_mp_add_d(tma_mp_int *a, tma_mp_digit b, tma_mp_int *c);
342 int tma_mp_sub_d(tma_mp_int *a, tma_mp_digit b, tma_mp_int *c);
345 int tma_mp_mul_d(tma_mp_int *a, tma_mp_digit b, tma_mp_int *c);
347 /* a/b => cb + d == a */
348 int tma_mp_div_d(tma_mp_int *a, tma_mp_digit b, tma_mp_int *c, tma_mp_digit *d);
350 /* a/3 => 3c + d == a */
351 int tma_mp_div_3(tma_mp_int *a, tma_mp_int *c, tma_mp_digit *d);
354 int tma_mp_expt_d(tma_mp_int *a, tma_mp_digit b, tma_mp_int *c);
356 /* c = a mod b, 0 <= c < b */
357 int tma_mp_mod_d(tma_mp_int *a, tma_mp_digit b, tma_mp_digit *c);
359 /* ---> number theory <--- */
361 /* d = a + b (mod c) */
362 int tma_mp_addmod(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, tma_mp_int *d);
364 /* d = a - b (mod c) */
365 int tma_mp_submod(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, tma_mp_int *d);
367 /* d = a * b (mod c) */
368 int tma_mp_mulmod(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, tma_mp_int *d);
370 /* c = a * a (mod b) */
371 int tma_mp_sqrmod(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
373 /* c = 1/a (mod b) */
374 int tma_mp_invmod(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
377 int tma_mp_gcd(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
379 /* produces value such that U1*a + U2*b = U3 */
380 int tma_mp_exteuclid(tma_mp_int *a, tma_mp_int *b, tma_mp_int *U1, tma_mp_int *U2, tma_mp_int *U3);
382 /* c = [a, b] or (a*b)/(a, b) */
383 int tma_mp_lcm(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
385 /* finds one of the b'th root of a, such that |c|**b <= |a|
387 * returns error if a < 0 and b is even
389 int tma_mp_n_root(tma_mp_int *a, tma_mp_digit b, tma_mp_int *c);
391 /* special sqrt algo */
392 int tma_mp_sqrt(tma_mp_int *arg, tma_mp_int *ret);
394 /* is number a square? */
395 int tma_mp_is_square(tma_mp_int *arg, int *ret);
397 /* computes the jacobi c = (a | n) (or Legendre if b is prime) */
398 int tma_mp_jacobi(tma_mp_int *a, tma_mp_int *n, int *c);
400 /* used to setup the Barrett reduction for a given modulus b */
401 int tma_mp_reduce_setup(tma_mp_int *a, tma_mp_int *b);
403 /* Barrett Reduction, computes a (mod b) with a precomputed value c
405 * Assumes that 0 < a <= b*b, note if 0 > a > -(b*b) then you can merely
406 * compute the reduction as -1 * tma_mp_reduce(tma_mp_abs(a)) [pseudo code].
408 int tma_mp_reduce(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
410 /* setups the montgomery reduction */
411 int tma_mp_montgomery_setup(tma_mp_int *a, tma_mp_digit *mp);
413 /* computes a = B**n mod b without division or multiplication useful for
414 * normalizing numbers in a Montgomery system.
416 int tma_mp_montgomery_calc_normalization(tma_mp_int *a, tma_mp_int *b);
418 /* computes x/R == x (mod N) via Montgomery Reduction */
419 int tma_mp_montgomery_reduce(tma_mp_int *a, tma_mp_int *m, tma_mp_digit mp);
421 /* returns 1 if a is a valid DR modulus */
422 int tma_mp_dr_is_modulus(tma_mp_int *a);
424 /* sets the value of "d" required for tma_mp_dr_reduce */
425 void tma_mp_dr_setup(tma_mp_int *a, tma_mp_digit *d);
427 /* reduces a modulo b using the Diminished Radix method */
428 int tma_mp_dr_reduce(tma_mp_int *a, tma_mp_int *b, tma_mp_digit mp);
430 /* returns true if a can be reduced with tma_mp_reduce_2k */
431 int tma_mp_reduce_is_2k(tma_mp_int *a);
433 /* determines k value for 2k reduction */
434 int tma_mp_reduce_2k_setup(tma_mp_int *a, tma_mp_digit *d);
436 /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
437 int tma_mp_reduce_2k(tma_mp_int *a, tma_mp_int *n, tma_mp_digit d);
439 /* returns true if a can be reduced with tma_mp_reduce_2k_l */
440 int tma_mp_reduce_is_2k_l(tma_mp_int *a);
442 /* determines k value for 2k reduction */
443 int tma_mp_reduce_2k_setup_l(tma_mp_int *a, tma_mp_int *d);
445 /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
446 int tma_mp_reduce_2k_l(tma_mp_int *a, tma_mp_int *n, tma_mp_int *d);
448 /* d = a**b (mod c) */
449 int tma_mp_exptmod(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, tma_mp_int *d);
451 /* ---> Primes <--- */
453 /* number of primes */
455 #define PRIME_SIZE 31
457 #define PRIME_SIZE 256
460 /* table of first PRIME_SIZE primes */
461 extern const tma_mp_digit ltm_prime_tab[];
463 /* result=1 if a is divisible by one of the first PRIME_SIZE primes */
464 int tma_mp_prime_is_divisible(tma_mp_int *a, int *result);
466 /* performs one Fermat test of "a" using base "b".
467 * Sets result to 0 if composite or 1 if probable prime
469 int tma_mp_prime_fermat(tma_mp_int *a, tma_mp_int *b, int *result);
471 /* performs one Miller-Rabin test of "a" using base "b".
472 * Sets result to 0 if composite or 1 if probable prime
474 int tma_mp_prime_miller_rabin(tma_mp_int *a, tma_mp_int *b, int *result);
476 /* This gives [for a given bit size] the number of trials required
477 * such that Miller-Rabin gives a prob of failure lower than 2^-96
479 int tma_mp_prime_rabin_miller_trials(int size);
481 /* performs t rounds of Miller-Rabin on "a" using the first
482 * t prime bases. Also performs an initial sieve of trial
483 * division. Determines if "a" is prime with probability
484 * of error no more than (1/4)**t.
486 * Sets result to 1 if probably prime, 0 otherwise
488 int tma_mp_prime_is_prime(tma_mp_int *a, int t, int *result);
490 /* finds the next prime after the number "a" using "t" trials
493 * bbs_style = 1 means the prime must be congruent to 3 mod 4
495 int tma_mp_prime_next_prime(tma_mp_int *a, int t, int bbs_style);
497 /* makes a truly random prime of a given size (bytes),
498 * call with bbs = 1 if you want it to be congruent to 3 mod 4
500 * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
501 * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
504 * The prime generated will be larger than 2^(8*size).
506 #define tma_mp_prime_random(a, t, size, bbs, cb, dat) tma_mp_prime_random_ex(a, t, ((size) * 8) + 1, (bbs==1)?LTM_PRIME_BBS:0, cb, dat)
508 /* makes a truly random prime of a given size (bits),
510 * Flags are as follows:
512 * LTM_PRIME_BBS - make prime congruent to 3 mod 4
513 * LTM_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies LTM_PRIME_BBS)
514 * LTM_PRIME_2MSB_OFF - make the 2nd highest bit zero
515 * LTM_PRIME_2MSB_ON - make the 2nd highest bit one
517 * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
518 * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
522 int tma_mp_prime_random_ex(tma_mp_int *a, int t, int size, int flags, ltm_prime_callback cb, void *dat);
524 /* ---> radix conversion <--- */
525 int tma_mp_count_bits(tma_mp_int *a);
527 int tma_mp_unsigned_bin_size(tma_mp_int *a);
528 int tma_mp_read_unsigned_bin(tma_mp_int *a, const unsigned char *b, int c);
529 int tma_mp_to_unsigned_bin(tma_mp_int *a, unsigned char *b);
530 int tma_mp_to_unsigned_bin_n (tma_mp_int * a, unsigned char *b, unsigned long *outlen);
532 int tma_mp_signed_bin_size(tma_mp_int *a);
533 int tma_mp_read_signed_bin(tma_mp_int *a, const unsigned char *b, int c);
534 int tma_mp_to_signed_bin(tma_mp_int *a, unsigned char *b);
535 int tma_mp_to_signed_bin_n (tma_mp_int * a, unsigned char *b, unsigned long *outlen);
537 int tma_mp_read_radix(tma_mp_int *a, const char *str, int radix);
538 int tma_mp_toradix(tma_mp_int *a, char *str, int radix);
539 int tma_mp_toradix_n(tma_mp_int * a, char *str, int radix, int maxlen);
540 int tma_mp_radix_size(tma_mp_int *a, int radix, int *size);
542 int tma_mp_fread(tma_mp_int *a, int radix, FILE *stream);
543 int tma_mp_fwrite(tma_mp_int *a, int radix, FILE *stream);
545 #define tma_mp_read_raw(mp, str, len) tma_mp_read_signed_bin((mp), (str), (len))
546 #define tma_mp_raw_size(mp) tma_mp_signed_bin_size(mp)
547 #define tma_mp_toraw(mp, str) tma_mp_to_signed_bin((mp), (str))
548 #define tma_mp_read_mag(mp, str, len) tma_mp_read_unsigned_bin((mp), (str), (len))
549 #define tma_mp_mag_size(mp) tma_mp_unsigned_bin_size(mp)
550 #define tma_mp_tomag(mp, str) tma_mp_to_unsigned_bin((mp), (str))
552 #define tma_mp_tobinary(M, S) tma_mp_toradix((M), (S), 2)
553 #define tma_mp_tooctal(M, S) tma_mp_toradix((M), (S), 8)
554 #define tma_mp_todecimal(M, S) tma_mp_toradix((M), (S), 10)
555 #define tma_mp_tohex(M, S) tma_mp_toradix((M), (S), 16)
557 /* lowlevel functions, do not call! */
558 int s_tma_mp_add(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
559 int s_tma_mp_sub(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
560 #define s_tma_mp_mul(a, b, c) s_tma_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
561 int fast_s_tma_mp_mul_digs(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, int digs);
562 int s_tma_mp_mul_digs(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, int digs);
563 int fast_s_tma_mp_mul_high_digs(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, int digs);
564 int s_tma_mp_mul_high_digs(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c, int digs);
565 int fast_s_tma_mp_sqr(tma_mp_int *a, tma_mp_int *b);
566 int s_tma_mp_sqr(tma_mp_int *a, tma_mp_int *b);
567 int tma_mp_karatsuba_mul(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
568 int tma_mp_toom_mul(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
569 int tma_mp_karatsuba_sqr(tma_mp_int *a, tma_mp_int *b);
570 int tma_mp_toom_sqr(tma_mp_int *a, tma_mp_int *b);
571 int fast_tma_mp_invmod(tma_mp_int *a, tma_mp_int *b, tma_mp_int *c);
572 int tma_mp_invmod_slow (tma_mp_int * a, tma_mp_int * b, tma_mp_int * c);
573 int fast_tma_mp_montgomery_reduce(tma_mp_int *a, tma_mp_int *m, tma_mp_digit mp);
574 int tma_mp_exptmod_fast(tma_mp_int *G, tma_mp_int *X, tma_mp_int *P, tma_mp_int *Y, int mode);
575 int s_tma_mp_exptmod (tma_mp_int * G, tma_mp_int * X, tma_mp_int * P, tma_mp_int * Y, int mode);
576 void bn_reverse(unsigned char *s, int len);
578 extern const char *tma_mp_s_rmap;