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