Sun Mar 11 15:22:42 CET 2007 Jochen Eisinger <coffee@silcnet.org>
[silc.git] / lib / silcmath / tma.h
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
2  *
3  * LibTomMath is a library that provides multiple-precision
4  * integer arithmetic as well as number theoretic functionality.
5  *
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.
9  *
10  * The library is free for all purposes without any express
11  * guarantee it works.
12  *
13  * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
14  */
15 #ifndef TMA_H
16 #define TMA_H
17
18 #include <stddef.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <ctype.h>
23 #include <limits.h>
24
25 #include "tma_class.h"
26
27 /* Assure these -Pekka */
28 #undef MP_8BIT
29 #undef MP_16BIT
30 #undef CRYPT
31
32 #undef MIN
33 #define MIN(x,y) ((x)<(y)?(x):(y))
34 #undef MAX
35 #define MAX(x,y) ((x)>(y)?(x):(y))
36
37 #ifdef __cplusplus
38 extern "C" {
39
40 /* C++ compilers don't like assigning void * to mp_digit * */
41 #define  OPT_CAST(x)  (x *)
42
43 #else
44
45 /* C on the other hand doesn't care */
46 #define  OPT_CAST(x)
47
48 #endif
49
50
51 /* detect 64-bit mode if possible */
52 #if defined(__x86_64__)
53    #if !(defined(MP_64BIT) && defined(MP_16BIT) && defined(MP_8BIT))
54       #define MP_64BIT
55    #endif
56 #endif
57
58 /* some default configurations.
59  *
60  * A "mp_digit" must be able to hold DIGIT_BIT + 1 bits
61  * A "mp_word" must be able to hold 2*DIGIT_BIT + 1 bits
62  *
63  * At the very least a mp_digit must be able to hold 7 bits
64  * [any size beyond that is ok provided it doesn't overflow the data type]
65  */
66 #ifdef MP_8BIT
67    typedef unsigned char      mp_digit;
68    typedef unsigned short     mp_word;
69 #elif defined(MP_16BIT)
70    typedef unsigned short     mp_digit;
71    typedef unsigned long      mp_word;
72 #elif defined(MP_64BIT)
73    /* for GCC only on supported platforms */
74 #ifndef CRYPT
75    typedef unsigned long long ulong64;
76    typedef signed long long   long64;
77 #endif
78
79    typedef unsigned long      mp_digit;
80    typedef unsigned long      mp_word __attribute__ ((mode(TI)));
81
82    #define DIGIT_BIT          60
83 #else
84    /* this is the default case, 28-bit digits */
85
86    /* this is to make porting into LibTomCrypt easier :-) */
87 #ifndef CRYPT
88    #if defined(_MSC_VER) || defined(__BORLANDC__)
89       typedef unsigned __int64   ulong64;
90       typedef signed __int64     long64;
91    #else
92       typedef unsigned long long ulong64;
93       typedef signed long long   long64;
94    #endif
95 #endif
96
97    typedef unsigned long      mp_digit;
98    typedef ulong64            mp_word;
99
100 #ifdef MP_31BIT
101    /* this is an extension that uses 31-bit digits */
102    #define DIGIT_BIT          31
103 #else
104    /* default case is 28-bit digits, defines MP_28BIT as a handy macro to test */
105    #define DIGIT_BIT          28
106    #define MP_28BIT
107 #endif
108 #endif
109
110 /* define heap macros */
111 #ifndef CRYPT
112    /* default to libc stuff */
113    #ifndef XMALLOC
114        #define XMALLOC  malloc
115        #define XFREE    free
116        #define XREALLOC realloc
117        #define XCALLOC  calloc
118    #else
119       /* prototypes for our heap functions */
120       extern void *XMALLOC(size_t n);
121       extern void *REALLOC(void *p, size_t n);
122       extern void *XCALLOC(size_t n, size_t s);
123       extern void XFREE(void *p);
124    #endif
125 #endif
126
127
128 /* otherwise the bits per digit is calculated automatically from the size of a mp_digit */
129 #ifndef DIGIT_BIT
130    #define DIGIT_BIT     ((int)((CHAR_BIT * sizeof(mp_digit) - 1)))  /* bits per digit */
131 #endif
132
133 #define MP_DIGIT_BIT     DIGIT_BIT
134 #define MP_MASK          ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))
135 #define MP_DIGIT_MAX     MP_MASK
136
137 /* equalities */
138 #define MP_LT        -1   /* less than */
139 #define MP_EQ         0   /* equal to */
140 #define MP_GT         1   /* greater than */
141
142 #define MP_ZPOS       0   /* positive integer */
143 #define MP_NEG        1   /* negative */
144
145 #define MP_OKAY       0   /* ok result */
146 #define MP_MEM        -2  /* out of mem */
147 #define MP_VAL        -3  /* invalid input */
148 #define MP_RANGE      MP_VAL
149
150 #define MP_YES        1   /* yes response */
151 #define MP_NO         0   /* no response */
152
153 /* Primality generation flags */
154 #define LTM_PRIME_BBS      0x0001 /* BBS style prime */
155 #define LTM_PRIME_SAFE     0x0002 /* Safe prime (p-1)/2 == prime */
156 #define LTM_PRIME_2MSB_OFF 0x0004 /* force 2nd MSB to 0 */
157 #define LTM_PRIME_2MSB_ON  0x0008 /* force 2nd MSB to 1 */
158
159 typedef int           mp_err;
160
161 /* you'll have to tune these... */
162 extern int KARATSUBA_MUL_CUTOFF,
163            KARATSUBA_SQR_CUTOFF,
164            TOOM_MUL_CUTOFF,
165            TOOM_SQR_CUTOFF;
166
167 /* define this to use lower memory usage routines (exptmods mostly) */
168 /* #define MP_LOW_MEM */
169
170 /* default precision */
171 #ifndef MP_PREC
172    #ifndef MP_LOW_MEM
173       #define MP_PREC                 64     /* default digits of precision */
174    #else
175       #define MP_PREC                 8      /* default digits of precision */
176    #endif
177 #endif
178
179 /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
180 #define MP_WARRAY               (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1))
181
182 /* the infamous mp_int structure */
183 typedef struct  {
184     int used, alloc, sign;
185     mp_digit *dp;
186 } mp_int;
187
188 /* callback for mp_prime_random, should fill dst with random bytes and return how many read [upto len] */
189 typedef int ltm_prime_callback(unsigned char *dst, int len, void *dat);
190
191
192 #define USED(m)    ((m)->used)
193 #define DIGIT(m,k) ((m)->dp[(k)])
194 #define SIGN(m)    ((m)->sign)
195
196 /* error code to char* string */
197 char *mp_error_to_string(int code);
198
199 /* ---> init and deinit bignum functions <--- */
200 /* init a bignum */
201 int mp_init(mp_int *a);
202
203 /* free a bignum */
204 void mp_clear(mp_int *a);
205
206 /* init a null terminated series of arguments */
207 int mp_init_multi(mp_int *mp, ...);
208
209 /* clear a null terminated series of arguments */
210 void mp_clear_multi(mp_int *mp, ...);
211
212 /* exchange two ints */
213 void mp_exch(mp_int *a, mp_int *b);
214
215 /* shrink ram required for a bignum */
216 int mp_shrink(mp_int *a);
217
218 /* grow an int to a given size */
219 int mp_grow(mp_int *a, int size);
220
221 /* init to a given number of digits */
222 int mp_init_size(mp_int *a, int size);
223
224 /* ---> Basic Manipulations <--- */
225 #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
226 #define mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO)
227 #define mp_isodd(a)  (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO)
228
229 /* set to zero */
230 void mp_zero(mp_int *a);
231
232 /* set to a digit */
233 void mp_set(mp_int *a, mp_digit b);
234
235 /* set a 32-bit const */
236 int mp_set_int(mp_int *a, unsigned long b);
237
238 /* get a 32-bit value */
239 unsigned long mp_get_int(mp_int * a);
240
241 /* initialize and set a digit */
242 int mp_init_set (mp_int * a, mp_digit b);
243
244 /* initialize and set 32-bit value */
245 int mp_init_set_int (mp_int * a, unsigned long b);
246
247 /* copy, b = a */
248 int mp_copy(mp_int *a, mp_int *b);
249
250 /* inits and copies, a = b */
251 int mp_init_copy(mp_int *a, mp_int *b);
252
253 /* trim unused digits */
254 void mp_clamp(mp_int *a);
255
256 /* ---> digit manipulation <--- */
257
258 /* right shift by "b" digits */
259 void mp_rshd(mp_int *a, int b);
260
261 /* left shift by "b" digits */
262 int mp_lshd(mp_int *a, int b);
263
264 /* c = a / 2**b */
265 int mp_div_2d(mp_int *a, int b, mp_int *c, mp_int *d);
266
267 /* b = a/2 */
268 int mp_div_2(mp_int *a, mp_int *b);
269
270 /* c = a * 2**b */
271 int mp_mul_2d(mp_int *a, int b, mp_int *c);
272
273 /* b = a*2 */
274 int mp_mul_2(mp_int *a, mp_int *b);
275
276 /* c = a mod 2**d */
277 int mp_mod_2d(mp_int *a, int b, mp_int *c);
278
279 /* computes a = 2**b */
280 int mp_2expt(mp_int *a, int b);
281
282 /* Counts the number of lsbs which are zero before the first zero bit */
283 int mp_cnt_lsb(mp_int *a);
284
285 /* I Love Earth! */
286
287 /* makes a pseudo-random int of a given size */
288 int mp_rand(mp_int *a, int digits);
289
290 /* ---> binary operations <--- */
291 /* c = a XOR b  */
292 int mp_xor(mp_int *a, mp_int *b, mp_int *c);
293
294 /* c = a OR b */
295 int mp_or(mp_int *a, mp_int *b, mp_int *c);
296
297 /* c = a AND b */
298 int mp_and(mp_int *a, mp_int *b, mp_int *c);
299
300 /* ---> Basic arithmetic <--- */
301
302 /* b = -a */
303 int mp_neg(mp_int *a, mp_int *b);
304
305 /* b = |a| */
306 int mp_abs(mp_int *a, mp_int *b);
307
308 /* compare a to b */
309 int mp_cmp(mp_int *a, mp_int *b);
310
311 /* compare |a| to |b| */
312 int mp_cmp_mag(mp_int *a, mp_int *b);
313
314 /* c = a + b */
315 int mp_add(mp_int *a, mp_int *b, mp_int *c);
316
317 /* c = a - b */
318 int mp_sub(mp_int *a, mp_int *b, mp_int *c);
319
320 /* c = a * b */
321 int mp_mul(mp_int *a, mp_int *b, mp_int *c);
322
323 /* b = a*a  */
324 int mp_sqr(mp_int *a, mp_int *b);
325
326 /* a/b => cb + d == a */
327 int mp_div(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
328
329 /* c = a mod b, 0 <= c < b  */
330 int mp_mod(mp_int *a, mp_int *b, mp_int *c);
331
332 /* ---> single digit functions <--- */
333
334 /* compare against a single digit */
335 int mp_cmp_d(mp_int *a, mp_digit b);
336
337 /* c = a + b */
338 int mp_add_d(mp_int *a, mp_digit b, mp_int *c);
339
340 /* c = a - b */
341 int mp_sub_d(mp_int *a, mp_digit b, mp_int *c);
342
343 /* c = a * b */
344 int mp_mul_d(mp_int *a, mp_digit b, mp_int *c);
345
346 /* a/b => cb + d == a */
347 int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d);
348
349 /* a/3 => 3c + d == a */
350 int mp_div_3(mp_int *a, mp_int *c, mp_digit *d);
351
352 /* c = a**b */
353 int mp_expt_d(mp_int *a, mp_digit b, mp_int *c);
354
355 /* c = a mod b, 0 <= c < b  */
356 int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c);
357
358 /* ---> number theory <--- */
359
360 /* d = a + b (mod c) */
361 int mp_addmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
362
363 /* d = a - b (mod c) */
364 int mp_submod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
365
366 /* d = a * b (mod c) */
367 int mp_mulmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
368
369 /* c = a * a (mod b) */
370 int mp_sqrmod(mp_int *a, mp_int *b, mp_int *c);
371
372 /* c = 1/a (mod b) */
373 int mp_invmod(mp_int *a, mp_int *b, mp_int *c);
374
375 /* c = (a, b) */
376 int mp_gcd(mp_int *a, mp_int *b, mp_int *c);
377
378 /* produces value such that U1*a + U2*b = U3 */
379 int mp_exteuclid(mp_int *a, mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3);
380
381 /* c = [a, b] or (a*b)/(a, b) */
382 int mp_lcm(mp_int *a, mp_int *b, mp_int *c);
383
384 /* finds one of the b'th root of a, such that |c|**b <= |a|
385  *
386  * returns error if a < 0 and b is even
387  */
388 int mp_n_root(mp_int *a, mp_digit b, mp_int *c);
389
390 /* special sqrt algo */
391 int mp_sqrt(mp_int *arg, mp_int *ret);
392
393 /* is number a square? */
394 int mp_is_square(mp_int *arg, int *ret);
395
396 /* computes the jacobi c = (a | n) (or Legendre if b is prime)  */
397 int mp_jacobi(mp_int *a, mp_int *n, int *c);
398
399 /* used to setup the Barrett reduction for a given modulus b */
400 int mp_reduce_setup(mp_int *a, mp_int *b);
401
402 /* Barrett Reduction, computes a (mod b) with a precomputed value c
403  *
404  * Assumes that 0 < a <= b*b, note if 0 > a > -(b*b) then you can merely
405  * compute the reduction as -1 * mp_reduce(mp_abs(a)) [pseudo code].
406  */
407 int mp_reduce(mp_int *a, mp_int *b, mp_int *c);
408
409 /* setups the montgomery reduction */
410 int mp_montgomery_setup(mp_int *a, mp_digit *mp);
411
412 /* computes a = B**n mod b without division or multiplication useful for
413  * normalizing numbers in a Montgomery system.
414  */
415 int mp_montgomery_calc_normalization(mp_int *a, mp_int *b);
416
417 /* computes x/R == x (mod N) via Montgomery Reduction */
418 int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
419
420 /* returns 1 if a is a valid DR modulus */
421 int mp_dr_is_modulus(mp_int *a);
422
423 /* sets the value of "d" required for mp_dr_reduce */
424 void mp_dr_setup(mp_int *a, mp_digit *d);
425
426 /* reduces a modulo b using the Diminished Radix method */
427 int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp);
428
429 /* returns true if a can be reduced with mp_reduce_2k */
430 int mp_reduce_is_2k(mp_int *a);
431
432 /* determines k value for 2k reduction */
433 int mp_reduce_2k_setup(mp_int *a, mp_digit *d);
434
435 /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
436 int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d);
437
438 /* returns true if a can be reduced with mp_reduce_2k_l */
439 int mp_reduce_is_2k_l(mp_int *a);
440
441 /* determines k value for 2k reduction */
442 int mp_reduce_2k_setup_l(mp_int *a, mp_int *d);
443
444 /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
445 int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d);
446
447 /* d = a**b (mod c) */
448 int mp_exptmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
449
450 /* ---> Primes <--- */
451
452 /* number of primes */
453 #ifdef MP_8BIT
454    #define PRIME_SIZE      31
455 #else
456    #define PRIME_SIZE      256
457 #endif
458
459 /* table of first PRIME_SIZE primes */
460 extern const mp_digit ltm_prime_tab[];
461
462 /* result=1 if a is divisible by one of the first PRIME_SIZE primes */
463 int mp_prime_is_divisible(mp_int *a, int *result);
464
465 /* performs one Fermat test of "a" using base "b".
466  * Sets result to 0 if composite or 1 if probable prime
467  */
468 int mp_prime_fermat(mp_int *a, mp_int *b, int *result);
469
470 /* performs one Miller-Rabin test of "a" using base "b".
471  * Sets result to 0 if composite or 1 if probable prime
472  */
473 int mp_prime_miller_rabin(mp_int *a, mp_int *b, int *result);
474
475 /* This gives [for a given bit size] the number of trials required
476  * such that Miller-Rabin gives a prob of failure lower than 2^-96
477  */
478 int mp_prime_rabin_miller_trials(int size);
479
480 /* performs t rounds of Miller-Rabin on "a" using the first
481  * t prime bases.  Also performs an initial sieve of trial
482  * division.  Determines if "a" is prime with probability
483  * of error no more than (1/4)**t.
484  *
485  * Sets result to 1 if probably prime, 0 otherwise
486  */
487 int mp_prime_is_prime(mp_int *a, int t, int *result);
488
489 /* finds the next prime after the number "a" using "t" trials
490  * of Miller-Rabin.
491  *
492  * bbs_style = 1 means the prime must be congruent to 3 mod 4
493  */
494 int mp_prime_next_prime(mp_int *a, int t, int bbs_style);
495
496 /* makes a truly random prime of a given size (bytes),
497  * call with bbs = 1 if you want it to be congruent to 3 mod 4
498  *
499  * You have to supply a callback which fills in a buffer with random bytes.  "dat" is a parameter you can
500  * have passed to the callback (e.g. a state or something).  This function doesn't use "dat" itself
501  * so it can be NULL
502  *
503  * The prime generated will be larger than 2^(8*size).
504  */
505 #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)
506
507 /* makes a truly random prime of a given size (bits),
508  *
509  * Flags are as follows:
510  *
511  *   LTM_PRIME_BBS      - make prime congruent to 3 mod 4
512  *   LTM_PRIME_SAFE     - make sure (p-1)/2 is prime as well (implies LTM_PRIME_BBS)
513  *   LTM_PRIME_2MSB_OFF - make the 2nd highest bit zero
514  *   LTM_PRIME_2MSB_ON  - make the 2nd highest bit one
515  *
516  * You have to supply a callback which fills in a buffer with random bytes.  "dat" is a parameter you can
517  * have passed to the callback (e.g. a state or something).  This function doesn't use "dat" itself
518  * so it can be NULL
519  *
520  */
521 int mp_prime_random_ex(mp_int *a, int t, int size, int flags, ltm_prime_callback cb, void *dat);
522
523 /* ---> radix conversion <--- */
524 int mp_count_bits(mp_int *a);
525
526 int mp_unsigned_bin_size(mp_int *a);
527 int mp_read_unsigned_bin(mp_int *a, unsigned char *b, int c);
528 int mp_to_unsigned_bin(mp_int *a, unsigned char *b);
529 int mp_to_unsigned_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen);
530
531 int mp_signed_bin_size(mp_int *a);
532 int mp_read_signed_bin(mp_int *a, unsigned char *b, int c);
533 int mp_to_signed_bin(mp_int *a, unsigned char *b);
534 int mp_to_signed_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen);
535
536 int mp_read_radix(mp_int *a, const char *str, int radix);
537 int mp_toradix(mp_int *a, char *str, int radix);
538 int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen);
539 int mp_radix_size(mp_int *a, int radix, int *size);
540
541 int mp_fread(mp_int *a, int radix, FILE *stream);
542 int mp_fwrite(mp_int *a, int radix, FILE *stream);
543
544 #define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len))
545 #define mp_raw_size(mp)           mp_signed_bin_size(mp)
546 #define mp_toraw(mp, str)         mp_to_signed_bin((mp), (str))
547 #define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len))
548 #define mp_mag_size(mp)           mp_unsigned_bin_size(mp)
549 #define mp_tomag(mp, str)         mp_to_unsigned_bin((mp), (str))
550
551 #define mp_tobinary(M, S)  mp_toradix((M), (S), 2)
552 #define mp_tooctal(M, S)   mp_toradix((M), (S), 8)
553 #define mp_todecimal(M, S) mp_toradix((M), (S), 10)
554 #define mp_tohex(M, S)     mp_toradix((M), (S), 16)
555
556 /* lowlevel functions, do not call! */
557 int s_mp_add(mp_int *a, mp_int *b, mp_int *c);
558 int s_mp_sub(mp_int *a, mp_int *b, mp_int *c);
559 #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
560 int fast_s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
561 int s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
562 int fast_s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
563 int s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
564 int fast_s_mp_sqr(mp_int *a, mp_int *b);
565 int s_mp_sqr(mp_int *a, mp_int *b);
566 int mp_karatsuba_mul(mp_int *a, mp_int *b, mp_int *c);
567 int mp_toom_mul(mp_int *a, mp_int *b, mp_int *c);
568 int mp_karatsuba_sqr(mp_int *a, mp_int *b);
569 int mp_toom_sqr(mp_int *a, mp_int *b);
570 int fast_mp_invmod(mp_int *a, mp_int *b, mp_int *c);
571 int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c);
572 int fast_mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
573 int mp_exptmod_fast(mp_int *G, mp_int *X, mp_int *P, mp_int *Y, int mode);
574 int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int mode);
575 void bn_reverse(unsigned char *s, int len);
576
577 extern const char *mp_s_rmap;
578
579 #ifdef __cplusplus
580    }
581 #endif
582
583 #endif /* TMA_H */