Updated the comments since Montgomery reduction is now included
[libeap.git] / src / tls / libtommath.c
1 /*
2  * Minimal code for RSA support from LibTomMath 0.3.9
3  * http://math.libtomcrypt.com/
4  * http://math.libtomcrypt.com/files/ltm-0.39.tar.bz2
5  * This library was released in public domain by Tom St Denis.
6  *
7  * The combination in this file may not use all of the optimized algorithms
8  * from LibTomMath and may be considerable slower than the LibTomMath with its
9  * default settings. The main purpose of having this version here is to make it
10  * easier to build bignum.c wrapper without having to install and build an
11  * external library.
12  *
13  * If CONFIG_INTERNAL_LIBTOMMATH is defined, bignum.c includes this
14  * libtommath.c file instead of using the external LibTomMath library.
15  */
16
17 #ifndef CHAR_BIT
18 #define CHAR_BIT 8
19 #endif
20
21 #define BN_MP_INVMOD_C
22 #define BN_S_MP_EXPTMOD_C /* Note: #undef in tommath_superclass.h; this would
23                            * require BN_MP_EXPTMOD_FAST_C instead */
24 #define BN_S_MP_MUL_DIGS_C
25 #define BN_MP_INVMOD_SLOW_C
26 #define BN_S_MP_SQR_C
27 #define BN_S_MP_MUL_HIGH_DIGS_C /* Note: #undef in tommath_superclass.h; this
28                                  * would require other than mp_reduce */
29
30 #ifdef LTM_FAST_EXPTMOD
31 /* Include faster exptmod (Montgomery) at the cost of about 2.5 kB in code */
32 #define BN_MP_EXPTMOD_FAST_C
33 #define BN_MP_MONTGOMERY_SETUP_C
34 #define BN_FAST_MP_MONTGOMERY_REDUCE_C
35 #define BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
36 #define BN_MP_MUL_2_C
37 #endif /* LTM_FAST_EXPTMOD */
38
39 /* Current uses do not require support for negative exponent in exptmod, so we
40  * can save about 1.5 kB in leaving out invmod. */
41 #define LTM_NO_NEG_EXP
42
43 /* from tommath.h */
44
45 #ifndef MIN
46    #define MIN(x,y) ((x)<(y)?(x):(y))
47 #endif
48
49 #ifndef MAX
50    #define MAX(x,y) ((x)>(y)?(x):(y))
51 #endif
52
53 #define  OPT_CAST(x)
54
55 typedef unsigned long mp_digit;
56 typedef u64 mp_word;
57
58 #define DIGIT_BIT          28
59 #define MP_28BIT
60
61
62 #define XMALLOC  os_malloc
63 #define XFREE    os_free
64 #define XREALLOC os_realloc
65
66
67 #define MP_MASK          ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))
68
69 #define MP_LT        -1   /* less than */
70 #define MP_EQ         0   /* equal to */
71 #define MP_GT         1   /* greater than */
72
73 #define MP_ZPOS       0   /* positive integer */
74 #define MP_NEG        1   /* negative */
75
76 #define MP_OKAY       0   /* ok result */
77 #define MP_MEM        -2  /* out of mem */
78 #define MP_VAL        -3  /* invalid input */
79
80 #define MP_YES        1   /* yes response */
81 #define MP_NO         0   /* no response */
82
83 typedef int           mp_err;
84
85 /* define this to use lower memory usage routines (exptmods mostly) */
86 #define MP_LOW_MEM
87
88 /* default precision */
89 #ifndef MP_PREC
90    #ifndef MP_LOW_MEM
91       #define MP_PREC                 32     /* default digits of precision */
92    #else
93       #define MP_PREC                 8      /* default digits of precision */
94    #endif   
95 #endif
96
97 /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
98 #define MP_WARRAY               (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1))
99
100 /* the infamous mp_int structure */
101 typedef struct  {
102     int used, alloc, sign;
103     mp_digit *dp;
104 } mp_int;
105
106
107 /* ---> Basic Manipulations <--- */
108 #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
109 #define mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO)
110 #define mp_isodd(a)  (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO)
111
112
113 /* prototypes for copied functions */
114 #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
115 static int s_mp_exptmod(mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode);
116 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
117 static int s_mp_sqr(mp_int * a, mp_int * b);
118 static int s_mp_mul_high_digs(mp_int * a, mp_int * b, mp_int * c, int digs);
119
120 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
121
122 static int mp_init_multi(mp_int *mp, ...);
123 static void mp_clear_multi(mp_int *mp, ...);
124 static int mp_lshd(mp_int * a, int b);
125 static void mp_set(mp_int * a, mp_digit b);
126 static void mp_clamp(mp_int * a);
127 static void mp_exch(mp_int * a, mp_int * b);
128 static void mp_rshd(mp_int * a, int b);
129 static void mp_zero(mp_int * a);
130 static int mp_mod_2d(mp_int * a, int b, mp_int * c);
131 static int mp_div_2d(mp_int * a, int b, mp_int * c, mp_int * d);
132 static int mp_init_copy(mp_int * a, mp_int * b);
133 static int mp_mul_2d(mp_int * a, int b, mp_int * c);
134 #ifndef LTM_NO_NEG_EXP
135 static int mp_div_2(mp_int * a, mp_int * b);
136 static int mp_invmod(mp_int * a, mp_int * b, mp_int * c);
137 static int mp_invmod_slow(mp_int * a, mp_int * b, mp_int * c);
138 #endif /* LTM_NO_NEG_EXP */
139 static int mp_copy(mp_int * a, mp_int * b);
140 static int mp_count_bits(mp_int * a);
141 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d);
142 static int mp_mod(mp_int * a, mp_int * b, mp_int * c);
143 static int mp_grow(mp_int * a, int size);
144 static int mp_cmp_mag(mp_int * a, mp_int * b);
145 static int mp_abs(mp_int * a, mp_int * b);
146 static int mp_sqr(mp_int * a, mp_int * b);
147 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d);
148 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d);
149 static int mp_2expt(mp_int * a, int b);
150 static int mp_reduce_setup(mp_int * a, mp_int * b);
151 static int mp_reduce(mp_int * x, mp_int * m, mp_int * mu);
152 static int mp_init_size(mp_int * a, int size);
153 #ifdef BN_MP_EXPTMOD_FAST_C
154 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode);
155 #endif /* BN_MP_EXPTMOD_FAST_C */
156
157
158
159 /* functions from bn_<func name>.c */
160
161
162 /* reverse an array, used for radix code */
163 static void bn_reverse (unsigned char *s, int len)
164 {
165   int     ix, iy;
166   unsigned char t;
167
168   ix = 0;
169   iy = len - 1;
170   while (ix < iy) {
171     t     = s[ix];
172     s[ix] = s[iy];
173     s[iy] = t;
174     ++ix;
175     --iy;
176   }
177 }
178
179
180 /* low level addition, based on HAC pp.594, Algorithm 14.7 */
181 static int s_mp_add (mp_int * a, mp_int * b, mp_int * c)
182 {
183   mp_int *x;
184   int     olduse, res, min, max;
185
186   /* find sizes, we let |a| <= |b| which means we have to sort
187    * them.  "x" will point to the input with the most digits
188    */
189   if (a->used > b->used) {
190     min = b->used;
191     max = a->used;
192     x = a;
193   } else {
194     min = a->used;
195     max = b->used;
196     x = b;
197   }
198
199   /* init result */
200   if (c->alloc < max + 1) {
201     if ((res = mp_grow (c, max + 1)) != MP_OKAY) {
202       return res;
203     }
204   }
205
206   /* get old used digit count and set new one */
207   olduse = c->used;
208   c->used = max + 1;
209
210   {
211     register mp_digit u, *tmpa, *tmpb, *tmpc;
212     register int i;
213
214     /* alias for digit pointers */
215
216     /* first input */
217     tmpa = a->dp;
218
219     /* second input */
220     tmpb = b->dp;
221
222     /* destination */
223     tmpc = c->dp;
224
225     /* zero the carry */
226     u = 0;
227     for (i = 0; i < min; i++) {
228       /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
229       *tmpc = *tmpa++ + *tmpb++ + u;
230
231       /* U = carry bit of T[i] */
232       u = *tmpc >> ((mp_digit)DIGIT_BIT);
233
234       /* take away carry bit from T[i] */
235       *tmpc++ &= MP_MASK;
236     }
237
238     /* now copy higher words if any, that is in A+B 
239      * if A or B has more digits add those in 
240      */
241     if (min != max) {
242       for (; i < max; i++) {
243         /* T[i] = X[i] + U */
244         *tmpc = x->dp[i] + u;
245
246         /* U = carry bit of T[i] */
247         u = *tmpc >> ((mp_digit)DIGIT_BIT);
248
249         /* take away carry bit from T[i] */
250         *tmpc++ &= MP_MASK;
251       }
252     }
253
254     /* add carry */
255     *tmpc++ = u;
256
257     /* clear digits above oldused */
258     for (i = c->used; i < olduse; i++) {
259       *tmpc++ = 0;
260     }
261   }
262
263   mp_clamp (c);
264   return MP_OKAY;
265 }
266
267
268 /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
269 static int s_mp_sub (mp_int * a, mp_int * b, mp_int * c)
270 {
271   int     olduse, res, min, max;
272
273   /* find sizes */
274   min = b->used;
275   max = a->used;
276
277   /* init result */
278   if (c->alloc < max) {
279     if ((res = mp_grow (c, max)) != MP_OKAY) {
280       return res;
281     }
282   }
283   olduse = c->used;
284   c->used = max;
285
286   {
287     register mp_digit u, *tmpa, *tmpb, *tmpc;
288     register int i;
289
290     /* alias for digit pointers */
291     tmpa = a->dp;
292     tmpb = b->dp;
293     tmpc = c->dp;
294
295     /* set carry to zero */
296     u = 0;
297     for (i = 0; i < min; i++) {
298       /* T[i] = A[i] - B[i] - U */
299       *tmpc = *tmpa++ - *tmpb++ - u;
300
301       /* U = carry bit of T[i]
302        * Note this saves performing an AND operation since
303        * if a carry does occur it will propagate all the way to the
304        * MSB.  As a result a single shift is enough to get the carry
305        */
306       u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
307
308       /* Clear carry from T[i] */
309       *tmpc++ &= MP_MASK;
310     }
311
312     /* now copy higher words if any, e.g. if A has more digits than B  */
313     for (; i < max; i++) {
314       /* T[i] = A[i] - U */
315       *tmpc = *tmpa++ - u;
316
317       /* U = carry bit of T[i] */
318       u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
319
320       /* Clear carry from T[i] */
321       *tmpc++ &= MP_MASK;
322     }
323
324     /* clear digits above used (since we may not have grown result above) */
325     for (i = c->used; i < olduse; i++) {
326       *tmpc++ = 0;
327     }
328   }
329
330   mp_clamp (c);
331   return MP_OKAY;
332 }
333
334
335 /* init a new mp_int */
336 static int mp_init (mp_int * a)
337 {
338   int i;
339
340   /* allocate memory required and clear it */
341   a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * MP_PREC);
342   if (a->dp == NULL) {
343     return MP_MEM;
344   }
345
346   /* set the digits to zero */
347   for (i = 0; i < MP_PREC; i++) {
348       a->dp[i] = 0;
349   }
350
351   /* set the used to zero, allocated digits to the default precision
352    * and sign to positive */
353   a->used  = 0;
354   a->alloc = MP_PREC;
355   a->sign  = MP_ZPOS;
356
357   return MP_OKAY;
358 }
359
360
361 /* clear one (frees)  */
362 static void mp_clear (mp_int * a)
363 {
364   int i;
365
366   /* only do anything if a hasn't been freed previously */
367   if (a->dp != NULL) {
368     /* first zero the digits */
369     for (i = 0; i < a->used; i++) {
370         a->dp[i] = 0;
371     }
372
373     /* free ram */
374     XFREE(a->dp);
375
376     /* reset members to make debugging easier */
377     a->dp    = NULL;
378     a->alloc = a->used = 0;
379     a->sign  = MP_ZPOS;
380   }
381 }
382
383
384 /* high level addition (handles signs) */
385 static int mp_add (mp_int * a, mp_int * b, mp_int * c)
386 {
387   int     sa, sb, res;
388
389   /* get sign of both inputs */
390   sa = a->sign;
391   sb = b->sign;
392
393   /* handle two cases, not four */
394   if (sa == sb) {
395     /* both positive or both negative */
396     /* add their magnitudes, copy the sign */
397     c->sign = sa;
398     res = s_mp_add (a, b, c);
399   } else {
400     /* one positive, the other negative */
401     /* subtract the one with the greater magnitude from */
402     /* the one of the lesser magnitude.  The result gets */
403     /* the sign of the one with the greater magnitude. */
404     if (mp_cmp_mag (a, b) == MP_LT) {
405       c->sign = sb;
406       res = s_mp_sub (b, a, c);
407     } else {
408       c->sign = sa;
409       res = s_mp_sub (a, b, c);
410     }
411   }
412   return res;
413 }
414
415
416 /* high level subtraction (handles signs) */
417 static int mp_sub (mp_int * a, mp_int * b, mp_int * c)
418 {
419   int     sa, sb, res;
420
421   sa = a->sign;
422   sb = b->sign;
423
424   if (sa != sb) {
425     /* subtract a negative from a positive, OR */
426     /* subtract a positive from a negative. */
427     /* In either case, ADD their magnitudes, */
428     /* and use the sign of the first number. */
429     c->sign = sa;
430     res = s_mp_add (a, b, c);
431   } else {
432     /* subtract a positive from a positive, OR */
433     /* subtract a negative from a negative. */
434     /* First, take the difference between their */
435     /* magnitudes, then... */
436     if (mp_cmp_mag (a, b) != MP_LT) {
437       /* Copy the sign from the first */
438       c->sign = sa;
439       /* The first has a larger or equal magnitude */
440       res = s_mp_sub (a, b, c);
441     } else {
442       /* The result has the *opposite* sign from */
443       /* the first number. */
444       c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
445       /* The second has a larger magnitude */
446       res = s_mp_sub (b, a, c);
447     }
448   }
449   return res;
450 }
451
452
453 /* high level multiplication (handles sign) */
454 static int mp_mul (mp_int * a, mp_int * b, mp_int * c)
455 {
456   int     res, neg;
457   neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
458
459   /* use Toom-Cook? */
460 #ifdef BN_MP_TOOM_MUL_C
461   if (MIN (a->used, b->used) >= TOOM_MUL_CUTOFF) {
462     res = mp_toom_mul(a, b, c);
463   } else 
464 #endif
465 #ifdef BN_MP_KARATSUBA_MUL_C
466   /* use Karatsuba? */
467   if (MIN (a->used, b->used) >= KARATSUBA_MUL_CUTOFF) {
468     res = mp_karatsuba_mul (a, b, c);
469   } else 
470 #endif
471   {
472     /* can we use the fast multiplier?
473      *
474      * The fast multiplier can be used if the output will 
475      * have less than MP_WARRAY digits and the number of 
476      * digits won't affect carry propagation
477      */
478 #ifdef BN_FAST_S_MP_MUL_DIGS_C
479     int     digs = a->used + b->used + 1;
480
481     if ((digs < MP_WARRAY) &&
482         MIN(a->used, b->used) <= 
483         (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
484       res = fast_s_mp_mul_digs (a, b, c, digs);
485     } else 
486 #endif
487 #ifdef BN_S_MP_MUL_DIGS_C
488       res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */
489 #else
490 #error mp_mul could fail
491       res = MP_VAL;
492 #endif
493
494   }
495   c->sign = (c->used > 0) ? neg : MP_ZPOS;
496   return res;
497 }
498
499
500 /* d = a * b (mod c) */
501 static int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
502 {
503   int     res;
504   mp_int  t;
505
506   if ((res = mp_init (&t)) != MP_OKAY) {
507     return res;
508   }
509
510   if ((res = mp_mul (a, b, &t)) != MP_OKAY) {
511     mp_clear (&t);
512     return res;
513   }
514   res = mp_mod (&t, c, d);
515   mp_clear (&t);
516   return res;
517 }
518
519
520 /* c = a mod b, 0 <= c < b */
521 static int mp_mod (mp_int * a, mp_int * b, mp_int * c)
522 {
523   mp_int  t;
524   int     res;
525
526   if ((res = mp_init (&t)) != MP_OKAY) {
527     return res;
528   }
529
530   if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) {
531     mp_clear (&t);
532     return res;
533   }
534
535   if (t.sign != b->sign) {
536     res = mp_add (b, &t, c);
537   } else {
538     res = MP_OKAY;
539     mp_exch (&t, c);
540   }
541
542   mp_clear (&t);
543   return res;
544 }
545
546
547 /* this is a shell function that calls either the normal or Montgomery
548  * exptmod functions.  Originally the call to the montgomery code was
549  * embedded in the normal function but that wasted alot of stack space
550  * for nothing (since 99% of the time the Montgomery code would be called)
551  */
552 static int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
553 {
554   int dr;
555
556   /* modulus P must be positive */
557   if (P->sign == MP_NEG) {
558      return MP_VAL;
559   }
560
561   /* if exponent X is negative we have to recurse */
562   if (X->sign == MP_NEG) {
563 #ifdef LTM_NO_NEG_EXP
564         return MP_VAL;
565 #else /* LTM_NO_NEG_EXP */
566 #ifdef BN_MP_INVMOD_C
567      mp_int tmpG, tmpX;
568      int err;
569
570      /* first compute 1/G mod P */
571      if ((err = mp_init(&tmpG)) != MP_OKAY) {
572         return err;
573      }
574      if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
575         mp_clear(&tmpG);
576         return err;
577      }
578
579      /* now get |X| */
580      if ((err = mp_init(&tmpX)) != MP_OKAY) {
581         mp_clear(&tmpG);
582         return err;
583      }
584      if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
585         mp_clear_multi(&tmpG, &tmpX, NULL);
586         return err;
587      }
588
589      /* and now compute (1/G)**|X| instead of G**X [X < 0] */
590      err = mp_exptmod(&tmpG, &tmpX, P, Y);
591      mp_clear_multi(&tmpG, &tmpX, NULL);
592      return err;
593 #else 
594 #error mp_exptmod would always fail
595      /* no invmod */
596      return MP_VAL;
597 #endif
598 #endif /* LTM_NO_NEG_EXP */
599   }
600
601 /* modified diminished radix reduction */
602 #if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && defined(BN_S_MP_EXPTMOD_C)
603   if (mp_reduce_is_2k_l(P) == MP_YES) {
604      return s_mp_exptmod(G, X, P, Y, 1);
605   }
606 #endif
607
608 #ifdef BN_MP_DR_IS_MODULUS_C
609   /* is it a DR modulus? */
610   dr = mp_dr_is_modulus(P);
611 #else
612   /* default to no */
613   dr = 0;
614 #endif
615
616 #ifdef BN_MP_REDUCE_IS_2K_C
617   /* if not, is it a unrestricted DR modulus? */
618   if (dr == 0) {
619      dr = mp_reduce_is_2k(P) << 1;
620   }
621 #endif
622     
623   /* if the modulus is odd or dr != 0 use the montgomery method */
624 #ifdef BN_MP_EXPTMOD_FAST_C
625   if (mp_isodd (P) == 1 || dr !=  0) {
626     return mp_exptmod_fast (G, X, P, Y, dr);
627   } else {
628 #endif
629 #ifdef BN_S_MP_EXPTMOD_C
630     /* otherwise use the generic Barrett reduction technique */
631     return s_mp_exptmod (G, X, P, Y, 0);
632 #else
633 #error mp_exptmod could fail
634     /* no exptmod for evens */
635     return MP_VAL;
636 #endif
637 #ifdef BN_MP_EXPTMOD_FAST_C
638   }
639 #endif
640 }
641
642
643 /* compare two ints (signed)*/
644 static int mp_cmp (mp_int * a, mp_int * b)
645 {
646   /* compare based on sign */
647   if (a->sign != b->sign) {
648      if (a->sign == MP_NEG) {
649         return MP_LT;
650      } else {
651         return MP_GT;
652      }
653   }
654   
655   /* compare digits */
656   if (a->sign == MP_NEG) {
657      /* if negative compare opposite direction */
658      return mp_cmp_mag(b, a);
659   } else {
660      return mp_cmp_mag(a, b);
661   }
662 }
663
664
665 /* compare a digit */
666 static int mp_cmp_d(mp_int * a, mp_digit b)
667 {
668   /* compare based on sign */
669   if (a->sign == MP_NEG) {
670     return MP_LT;
671   }
672
673   /* compare based on magnitude */
674   if (a->used > 1) {
675     return MP_GT;
676   }
677
678   /* compare the only digit of a to b */
679   if (a->dp[0] > b) {
680     return MP_GT;
681   } else if (a->dp[0] < b) {
682     return MP_LT;
683   } else {
684     return MP_EQ;
685   }
686 }
687
688
689 #ifndef LTM_NO_NEG_EXP
690 /* hac 14.61, pp608 */
691 static int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
692 {
693   /* b cannot be negative */
694   if (b->sign == MP_NEG || mp_iszero(b) == 1) {
695     return MP_VAL;
696   }
697
698 #ifdef BN_FAST_MP_INVMOD_C
699   /* if the modulus is odd we can use a faster routine instead */
700   if (mp_isodd (b) == 1) {
701     return fast_mp_invmod (a, b, c);
702   }
703 #endif
704
705 #ifdef BN_MP_INVMOD_SLOW_C
706   return mp_invmod_slow(a, b, c);
707 #endif
708
709 #ifndef BN_FAST_MP_INVMOD_C
710 #ifndef BN_MP_INVMOD_SLOW_C
711 #error mp_invmod would always fail
712 #endif
713 #endif
714   return MP_VAL;
715 }
716 #endif /* LTM_NO_NEG_EXP */
717
718
719 /* get the size for an unsigned equivalent */
720 static int mp_unsigned_bin_size (mp_int * a)
721 {
722   int     size = mp_count_bits (a);
723   return (size / 8 + ((size & 7) != 0 ? 1 : 0));
724 }
725
726
727 #ifndef LTM_NO_NEG_EXP
728 /* hac 14.61, pp608 */
729 static int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c)
730 {
731   mp_int  x, y, u, v, A, B, C, D;
732   int     res;
733
734   /* b cannot be negative */
735   if (b->sign == MP_NEG || mp_iszero(b) == 1) {
736     return MP_VAL;
737   }
738
739   /* init temps */
740   if ((res = mp_init_multi(&x, &y, &u, &v, 
741                            &A, &B, &C, &D, NULL)) != MP_OKAY) {
742      return res;
743   }
744
745   /* x = a, y = b */
746   if ((res = mp_mod(a, b, &x)) != MP_OKAY) {
747       goto LBL_ERR;
748   }
749   if ((res = mp_copy (b, &y)) != MP_OKAY) {
750     goto LBL_ERR;
751   }
752
753   /* 2. [modified] if x,y are both even then return an error! */
754   if (mp_iseven (&x) == 1 && mp_iseven (&y) == 1) {
755     res = MP_VAL;
756     goto LBL_ERR;
757   }
758
759   /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
760   if ((res = mp_copy (&x, &u)) != MP_OKAY) {
761     goto LBL_ERR;
762   }
763   if ((res = mp_copy (&y, &v)) != MP_OKAY) {
764     goto LBL_ERR;
765   }
766   mp_set (&A, 1);
767   mp_set (&D, 1);
768
769 top:
770   /* 4.  while u is even do */
771   while (mp_iseven (&u) == 1) {
772     /* 4.1 u = u/2 */
773     if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
774       goto LBL_ERR;
775     }
776     /* 4.2 if A or B is odd then */
777     if (mp_isodd (&A) == 1 || mp_isodd (&B) == 1) {
778       /* A = (A+y)/2, B = (B-x)/2 */
779       if ((res = mp_add (&A, &y, &A)) != MP_OKAY) {
780          goto LBL_ERR;
781       }
782       if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
783          goto LBL_ERR;
784       }
785     }
786     /* A = A/2, B = B/2 */
787     if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
788       goto LBL_ERR;
789     }
790     if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
791       goto LBL_ERR;
792     }
793   }
794
795   /* 5.  while v is even do */
796   while (mp_iseven (&v) == 1) {
797     /* 5.1 v = v/2 */
798     if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
799       goto LBL_ERR;
800     }
801     /* 5.2 if C or D is odd then */
802     if (mp_isodd (&C) == 1 || mp_isodd (&D) == 1) {
803       /* C = (C+y)/2, D = (D-x)/2 */
804       if ((res = mp_add (&C, &y, &C)) != MP_OKAY) {
805          goto LBL_ERR;
806       }
807       if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
808          goto LBL_ERR;
809       }
810     }
811     /* C = C/2, D = D/2 */
812     if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
813       goto LBL_ERR;
814     }
815     if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
816       goto LBL_ERR;
817     }
818   }
819
820   /* 6.  if u >= v then */
821   if (mp_cmp (&u, &v) != MP_LT) {
822     /* u = u - v, A = A - C, B = B - D */
823     if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
824       goto LBL_ERR;
825     }
826
827     if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
828       goto LBL_ERR;
829     }
830
831     if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
832       goto LBL_ERR;
833     }
834   } else {
835     /* v - v - u, C = C - A, D = D - B */
836     if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
837       goto LBL_ERR;
838     }
839
840     if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
841       goto LBL_ERR;
842     }
843
844     if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
845       goto LBL_ERR;
846     }
847   }
848
849   /* if not zero goto step 4 */
850   if (mp_iszero (&u) == 0)
851     goto top;
852
853   /* now a = C, b = D, gcd == g*v */
854
855   /* if v != 1 then there is no inverse */
856   if (mp_cmp_d (&v, 1) != MP_EQ) {
857     res = MP_VAL;
858     goto LBL_ERR;
859   }
860
861   /* if its too low */
862   while (mp_cmp_d(&C, 0) == MP_LT) {
863       if ((res = mp_add(&C, b, &C)) != MP_OKAY) {
864          goto LBL_ERR;
865       }
866   }
867   
868   /* too big */
869   while (mp_cmp_mag(&C, b) != MP_LT) {
870       if ((res = mp_sub(&C, b, &C)) != MP_OKAY) {
871          goto LBL_ERR;
872       }
873   }
874   
875   /* C is now the inverse */
876   mp_exch (&C, c);
877   res = MP_OKAY;
878 LBL_ERR:mp_clear_multi (&x, &y, &u, &v, &A, &B, &C, &D, NULL);
879   return res;
880 }
881 #endif /* LTM_NO_NEG_EXP */
882
883
884 /* compare maginitude of two ints (unsigned) */
885 static int mp_cmp_mag (mp_int * a, mp_int * b)
886 {
887   int     n;
888   mp_digit *tmpa, *tmpb;
889
890   /* compare based on # of non-zero digits */
891   if (a->used > b->used) {
892     return MP_GT;
893   }
894   
895   if (a->used < b->used) {
896     return MP_LT;
897   }
898
899   /* alias for a */
900   tmpa = a->dp + (a->used - 1);
901
902   /* alias for b */
903   tmpb = b->dp + (a->used - 1);
904
905   /* compare based on digits  */
906   for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
907     if (*tmpa > *tmpb) {
908       return MP_GT;
909     }
910
911     if (*tmpa < *tmpb) {
912       return MP_LT;
913     }
914   }
915   return MP_EQ;
916 }
917
918
919 /* reads a unsigned char array, assumes the msb is stored first [big endian] */
920 static int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
921 {
922   int     res;
923
924   /* make sure there are at least two digits */
925   if (a->alloc < 2) {
926      if ((res = mp_grow(a, 2)) != MP_OKAY) {
927         return res;
928      }
929   }
930
931   /* zero the int */
932   mp_zero (a);
933
934   /* read the bytes in */
935   while (c-- > 0) {
936     if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) {
937       return res;
938     }
939
940 #ifndef MP_8BIT
941       a->dp[0] |= *b++;
942       a->used += 1;
943 #else
944       a->dp[0] = (*b & MP_MASK);
945       a->dp[1] |= ((*b++ >> 7U) & 1);
946       a->used += 2;
947 #endif
948   }
949   mp_clamp (a);
950   return MP_OKAY;
951 }
952
953
954 /* store in unsigned [big endian] format */
955 static int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
956 {
957   int     x, res;
958   mp_int  t;
959
960   if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
961     return res;
962   }
963
964   x = 0;
965   while (mp_iszero (&t) == 0) {
966 #ifndef MP_8BIT
967       b[x++] = (unsigned char) (t.dp[0] & 255);
968 #else
969       b[x++] = (unsigned char) (t.dp[0] | ((t.dp[1] & 0x01) << 7));
970 #endif
971     if ((res = mp_div_2d (&t, 8, &t, NULL)) != MP_OKAY) {
972       mp_clear (&t);
973       return res;
974     }
975   }
976   bn_reverse (b, x);
977   mp_clear (&t);
978   return MP_OKAY;
979 }
980
981
982 /* shift right by a certain bit count (store quotient in c, optional remainder in d) */
983 static int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
984 {
985   mp_digit D, r, rr;
986   int     x, res;
987   mp_int  t;
988
989
990   /* if the shift count is <= 0 then we do no work */
991   if (b <= 0) {
992     res = mp_copy (a, c);
993     if (d != NULL) {
994       mp_zero (d);
995     }
996     return res;
997   }
998
999   if ((res = mp_init (&t)) != MP_OKAY) {
1000     return res;
1001   }
1002
1003   /* get the remainder */
1004   if (d != NULL) {
1005     if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
1006       mp_clear (&t);
1007       return res;
1008     }
1009   }
1010
1011   /* copy */
1012   if ((res = mp_copy (a, c)) != MP_OKAY) {
1013     mp_clear (&t);
1014     return res;
1015   }
1016
1017   /* shift by as many digits in the bit count */
1018   if (b >= (int)DIGIT_BIT) {
1019     mp_rshd (c, b / DIGIT_BIT);
1020   }
1021
1022   /* shift any bit count < DIGIT_BIT */
1023   D = (mp_digit) (b % DIGIT_BIT);
1024   if (D != 0) {
1025     register mp_digit *tmpc, mask, shift;
1026
1027     /* mask */
1028     mask = (((mp_digit)1) << D) - 1;
1029
1030     /* shift for lsb */
1031     shift = DIGIT_BIT - D;
1032
1033     /* alias */
1034     tmpc = c->dp + (c->used - 1);
1035
1036     /* carry */
1037     r = 0;
1038     for (x = c->used - 1; x >= 0; x--) {
1039       /* get the lower  bits of this word in a temp */
1040       rr = *tmpc & mask;
1041
1042       /* shift the current word and mix in the carry bits from the previous word */
1043       *tmpc = (*tmpc >> D) | (r << shift);
1044       --tmpc;
1045
1046       /* set the carry to the carry bits of the current word found above */
1047       r = rr;
1048     }
1049   }
1050   mp_clamp (c);
1051   if (d != NULL) {
1052     mp_exch (&t, d);
1053   }
1054   mp_clear (&t);
1055   return MP_OKAY;
1056 }
1057
1058
1059 static int mp_init_copy (mp_int * a, mp_int * b)
1060 {
1061   int     res;
1062
1063   if ((res = mp_init (a)) != MP_OKAY) {
1064     return res;
1065   }
1066   return mp_copy (b, a);
1067 }
1068
1069
1070 /* set to zero */
1071 static void mp_zero (mp_int * a)
1072 {
1073   int       n;
1074   mp_digit *tmp;
1075
1076   a->sign = MP_ZPOS;
1077   a->used = 0;
1078
1079   tmp = a->dp;
1080   for (n = 0; n < a->alloc; n++) {
1081      *tmp++ = 0;
1082   }
1083 }
1084
1085
1086 /* copy, b = a */
1087 static int mp_copy (mp_int * a, mp_int * b)
1088 {
1089   int     res, n;
1090
1091   /* if dst == src do nothing */
1092   if (a == b) {
1093     return MP_OKAY;
1094   }
1095
1096   /* grow dest */
1097   if (b->alloc < a->used) {
1098      if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1099         return res;
1100      }
1101   }
1102
1103   /* zero b and copy the parameters over */
1104   {
1105     register mp_digit *tmpa, *tmpb;
1106
1107     /* pointer aliases */
1108
1109     /* source */
1110     tmpa = a->dp;
1111
1112     /* destination */
1113     tmpb = b->dp;
1114
1115     /* copy all the digits */
1116     for (n = 0; n < a->used; n++) {
1117       *tmpb++ = *tmpa++;
1118     }
1119
1120     /* clear high digits */
1121     for (; n < b->used; n++) {
1122       *tmpb++ = 0;
1123     }
1124   }
1125
1126   /* copy used count and sign */
1127   b->used = a->used;
1128   b->sign = a->sign;
1129   return MP_OKAY;
1130 }
1131
1132
1133 /* shift right a certain amount of digits */
1134 static void mp_rshd (mp_int * a, int b)
1135 {
1136   int     x;
1137
1138   /* if b <= 0 then ignore it */
1139   if (b <= 0) {
1140     return;
1141   }
1142
1143   /* if b > used then simply zero it and return */
1144   if (a->used <= b) {
1145     mp_zero (a);
1146     return;
1147   }
1148
1149   {
1150     register mp_digit *bottom, *top;
1151
1152     /* shift the digits down */
1153
1154     /* bottom */
1155     bottom = a->dp;
1156
1157     /* top [offset into digits] */
1158     top = a->dp + b;
1159
1160     /* this is implemented as a sliding window where 
1161      * the window is b-digits long and digits from 
1162      * the top of the window are copied to the bottom
1163      *
1164      * e.g.
1165
1166      b-2 | b-1 | b0 | b1 | b2 | ... | bb |   ---->
1167                  /\                   |      ---->
1168                   \-------------------/      ---->
1169      */
1170     for (x = 0; x < (a->used - b); x++) {
1171       *bottom++ = *top++;
1172     }
1173
1174     /* zero the top digits */
1175     for (; x < a->used; x++) {
1176       *bottom++ = 0;
1177     }
1178   }
1179   
1180   /* remove excess digits */
1181   a->used -= b;
1182 }
1183
1184
1185 /* swap the elements of two integers, for cases where you can't simply swap the 
1186  * mp_int pointers around
1187  */
1188 static void mp_exch (mp_int * a, mp_int * b)
1189 {
1190   mp_int  t;
1191
1192   t  = *a;
1193   *a = *b;
1194   *b = t;
1195 }
1196
1197
1198 /* trim unused digits 
1199  *
1200  * This is used to ensure that leading zero digits are
1201  * trimed and the leading "used" digit will be non-zero
1202  * Typically very fast.  Also fixes the sign if there
1203  * are no more leading digits
1204  */
1205 static void mp_clamp (mp_int * a)
1206 {
1207   /* decrease used while the most significant digit is
1208    * zero.
1209    */
1210   while (a->used > 0 && a->dp[a->used - 1] == 0) {
1211     --(a->used);
1212   }
1213
1214   /* reset the sign flag if used == 0 */
1215   if (a->used == 0) {
1216     a->sign = MP_ZPOS;
1217   }
1218 }
1219
1220
1221 /* grow as required */
1222 static int mp_grow (mp_int * a, int size)
1223 {
1224   int     i;
1225   mp_digit *tmp;
1226
1227   /* if the alloc size is smaller alloc more ram */
1228   if (a->alloc < size) {
1229     /* ensure there are always at least MP_PREC digits extra on top */
1230     size += (MP_PREC * 2) - (size % MP_PREC);
1231
1232     /* reallocate the array a->dp
1233      *
1234      * We store the return in a temporary variable
1235      * in case the operation failed we don't want
1236      * to overwrite the dp member of a.
1237      */
1238     tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size);
1239     if (tmp == NULL) {
1240       /* reallocation failed but "a" is still valid [can be freed] */
1241       return MP_MEM;
1242     }
1243
1244     /* reallocation succeeded so set a->dp */
1245     a->dp = tmp;
1246
1247     /* zero excess digits */
1248     i        = a->alloc;
1249     a->alloc = size;
1250     for (; i < a->alloc; i++) {
1251       a->dp[i] = 0;
1252     }
1253   }
1254   return MP_OKAY;
1255 }
1256
1257
1258 /* b = |a| 
1259  *
1260  * Simple function copies the input and fixes the sign to positive
1261  */
1262 static int mp_abs (mp_int * a, mp_int * b)
1263 {
1264   int     res;
1265
1266   /* copy a to b */
1267   if (a != b) {
1268      if ((res = mp_copy (a, b)) != MP_OKAY) {
1269        return res;
1270      }
1271   }
1272
1273   /* force the sign of b to positive */
1274   b->sign = MP_ZPOS;
1275
1276   return MP_OKAY;
1277 }
1278
1279
1280 /* set to a digit */
1281 static void mp_set (mp_int * a, mp_digit b)
1282 {
1283   mp_zero (a);
1284   a->dp[0] = b & MP_MASK;
1285   a->used  = (a->dp[0] != 0) ? 1 : 0;
1286 }
1287
1288
1289 #ifndef LTM_NO_NEG_EXP
1290 /* b = a/2 */
1291 static int mp_div_2(mp_int * a, mp_int * b)
1292 {
1293   int     x, res, oldused;
1294
1295   /* copy */
1296   if (b->alloc < a->used) {
1297     if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1298       return res;
1299     }
1300   }
1301
1302   oldused = b->used;
1303   b->used = a->used;
1304   {
1305     register mp_digit r, rr, *tmpa, *tmpb;
1306
1307     /* source alias */
1308     tmpa = a->dp + b->used - 1;
1309
1310     /* dest alias */
1311     tmpb = b->dp + b->used - 1;
1312
1313     /* carry */
1314     r = 0;
1315     for (x = b->used - 1; x >= 0; x--) {
1316       /* get the carry for the next iteration */
1317       rr = *tmpa & 1;
1318
1319       /* shift the current digit, add in carry and store */
1320       *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
1321
1322       /* forward carry to next iteration */
1323       r = rr;
1324     }
1325
1326     /* zero excess digits */
1327     tmpb = b->dp + b->used;
1328     for (x = b->used; x < oldused; x++) {
1329       *tmpb++ = 0;
1330     }
1331   }
1332   b->sign = a->sign;
1333   mp_clamp (b);
1334   return MP_OKAY;
1335 }
1336 #endif /* LTM_NO_NEG_EXP */
1337
1338
1339 /* shift left by a certain bit count */
1340 static int mp_mul_2d (mp_int * a, int b, mp_int * c)
1341 {
1342   mp_digit d;
1343   int      res;
1344
1345   /* copy */
1346   if (a != c) {
1347      if ((res = mp_copy (a, c)) != MP_OKAY) {
1348        return res;
1349      }
1350   }
1351
1352   if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) {
1353      if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) {
1354        return res;
1355      }
1356   }
1357
1358   /* shift by as many digits in the bit count */
1359   if (b >= (int)DIGIT_BIT) {
1360     if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) {
1361       return res;
1362     }
1363   }
1364
1365   /* shift any bit count < DIGIT_BIT */
1366   d = (mp_digit) (b % DIGIT_BIT);
1367   if (d != 0) {
1368     register mp_digit *tmpc, shift, mask, r, rr;
1369     register int x;
1370
1371     /* bitmask for carries */
1372     mask = (((mp_digit)1) << d) - 1;
1373
1374     /* shift for msbs */
1375     shift = DIGIT_BIT - d;
1376
1377     /* alias */
1378     tmpc = c->dp;
1379
1380     /* carry */
1381     r    = 0;
1382     for (x = 0; x < c->used; x++) {
1383       /* get the higher bits of the current word */
1384       rr = (*tmpc >> shift) & mask;
1385
1386       /* shift the current word and OR in the carry */
1387       *tmpc = ((*tmpc << d) | r) & MP_MASK;
1388       ++tmpc;
1389
1390       /* set the carry to the carry bits of the current word */
1391       r = rr;
1392     }
1393     
1394     /* set final carry */
1395     if (r != 0) {
1396        c->dp[(c->used)++] = r;
1397     }
1398   }
1399   mp_clamp (c);
1400   return MP_OKAY;
1401 }
1402
1403
1404 static int mp_init_multi(mp_int *mp, ...) 
1405 {
1406     mp_err res = MP_OKAY;      /* Assume ok until proven otherwise */
1407     int n = 0;                 /* Number of ok inits */
1408     mp_int* cur_arg = mp;
1409     va_list args;
1410
1411     va_start(args, mp);        /* init args to next argument from caller */
1412     while (cur_arg != NULL) {
1413         if (mp_init(cur_arg) != MP_OKAY) {
1414             /* Oops - error! Back-track and mp_clear what we already
1415                succeeded in init-ing, then return error.
1416             */
1417             va_list clean_args;
1418             
1419             /* end the current list */
1420             va_end(args);
1421             
1422             /* now start cleaning up */            
1423             cur_arg = mp;
1424             va_start(clean_args, mp);
1425             while (n--) {
1426                 mp_clear(cur_arg);
1427                 cur_arg = va_arg(clean_args, mp_int*);
1428             }
1429             va_end(clean_args);
1430             res = MP_MEM;
1431             break;
1432         }
1433         n++;
1434         cur_arg = va_arg(args, mp_int*);
1435     }
1436     va_end(args);
1437     return res;                /* Assumed ok, if error flagged above. */
1438 }
1439
1440
1441 static void mp_clear_multi(mp_int *mp, ...) 
1442 {
1443     mp_int* next_mp = mp;
1444     va_list args;
1445     va_start(args, mp);
1446     while (next_mp != NULL) {
1447         mp_clear(next_mp);
1448         next_mp = va_arg(args, mp_int*);
1449     }
1450     va_end(args);
1451 }
1452
1453
1454 /* shift left a certain amount of digits */
1455 static int mp_lshd (mp_int * a, int b)
1456 {
1457   int     x, res;
1458
1459   /* if its less than zero return */
1460   if (b <= 0) {
1461     return MP_OKAY;
1462   }
1463
1464   /* grow to fit the new digits */
1465   if (a->alloc < a->used + b) {
1466      if ((res = mp_grow (a, a->used + b)) != MP_OKAY) {
1467        return res;
1468      }
1469   }
1470
1471   {
1472     register mp_digit *top, *bottom;
1473
1474     /* increment the used by the shift amount then copy upwards */
1475     a->used += b;
1476
1477     /* top */
1478     top = a->dp + a->used - 1;
1479
1480     /* base */
1481     bottom = a->dp + a->used - 1 - b;
1482
1483     /* much like mp_rshd this is implemented using a sliding window
1484      * except the window goes the otherway around.  Copying from
1485      * the bottom to the top.  see bn_mp_rshd.c for more info.
1486      */
1487     for (x = a->used - 1; x >= b; x--) {
1488       *top-- = *bottom--;
1489     }
1490
1491     /* zero the lower digits */
1492     top = a->dp;
1493     for (x = 0; x < b; x++) {
1494       *top++ = 0;
1495     }
1496   }
1497   return MP_OKAY;
1498 }
1499
1500
1501 /* returns the number of bits in an int */
1502 static int mp_count_bits (mp_int * a)
1503 {
1504   int     r;
1505   mp_digit q;
1506
1507   /* shortcut */
1508   if (a->used == 0) {
1509     return 0;
1510   }
1511
1512   /* get number of digits and add that */
1513   r = (a->used - 1) * DIGIT_BIT;
1514   
1515   /* take the last digit and count the bits in it */
1516   q = a->dp[a->used - 1];
1517   while (q > ((mp_digit) 0)) {
1518     ++r;
1519     q >>= ((mp_digit) 1);
1520   }
1521   return r;
1522 }
1523
1524
1525 /* calc a value mod 2**b */
1526 static int mp_mod_2d (mp_int * a, int b, mp_int * c)
1527 {
1528   int     x, res;
1529
1530   /* if b is <= 0 then zero the int */
1531   if (b <= 0) {
1532     mp_zero (c);
1533     return MP_OKAY;
1534   }
1535
1536   /* if the modulus is larger than the value than return */
1537   if (b >= (int) (a->used * DIGIT_BIT)) {
1538     res = mp_copy (a, c);
1539     return res;
1540   }
1541
1542   /* copy */
1543   if ((res = mp_copy (a, c)) != MP_OKAY) {
1544     return res;
1545   }
1546
1547   /* zero digits above the last digit of the modulus */
1548   for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x++) {
1549     c->dp[x] = 0;
1550   }
1551   /* clear the digit that is not completely outside/inside the modulus */
1552   c->dp[b / DIGIT_BIT] &=
1553     (mp_digit) ((((mp_digit) 1) << (((mp_digit) b) % DIGIT_BIT)) - ((mp_digit) 1));
1554   mp_clamp (c);
1555   return MP_OKAY;
1556 }
1557
1558
1559 /* slower bit-bang division... also smaller */
1560 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d)
1561 {
1562    mp_int ta, tb, tq, q;
1563    int    res, n, n2;
1564
1565   /* is divisor zero ? */
1566   if (mp_iszero (b) == 1) {
1567     return MP_VAL;
1568   }
1569
1570   /* if a < b then q=0, r = a */
1571   if (mp_cmp_mag (a, b) == MP_LT) {
1572     if (d != NULL) {
1573       res = mp_copy (a, d);
1574     } else {
1575       res = MP_OKAY;
1576     }
1577     if (c != NULL) {
1578       mp_zero (c);
1579     }
1580     return res;
1581   }
1582         
1583   /* init our temps */
1584   if ((res = mp_init_multi(&ta, &tb, &tq, &q, NULL) != MP_OKAY)) {
1585      return res;
1586   }
1587
1588
1589   mp_set(&tq, 1);
1590   n = mp_count_bits(a) - mp_count_bits(b);
1591   if (((res = mp_abs(a, &ta)) != MP_OKAY) ||
1592       ((res = mp_abs(b, &tb)) != MP_OKAY) || 
1593       ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) ||
1594       ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) {
1595       goto LBL_ERR;
1596   }
1597
1598   while (n-- >= 0) {
1599      if (mp_cmp(&tb, &ta) != MP_GT) {
1600         if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) ||
1601             ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) {
1602            goto LBL_ERR;
1603         }
1604      }
1605      if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) ||
1606          ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) {
1607            goto LBL_ERR;
1608      }
1609   }
1610
1611   /* now q == quotient and ta == remainder */
1612   n  = a->sign;
1613   n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG);
1614   if (c != NULL) {
1615      mp_exch(c, &q);
1616      c->sign  = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2;
1617   }
1618   if (d != NULL) {
1619      mp_exch(d, &ta);
1620      d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n;
1621   }
1622 LBL_ERR:
1623    mp_clear_multi(&ta, &tb, &tq, &q, NULL);
1624    return res;
1625 }
1626
1627
1628 #ifdef MP_LOW_MEM
1629    #define TAB_SIZE 32
1630 #else
1631    #define TAB_SIZE 256
1632 #endif
1633
1634 static int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
1635 {
1636   mp_int  M[TAB_SIZE], res, mu;
1637   mp_digit buf;
1638   int     err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
1639   int (*redux)(mp_int*,mp_int*,mp_int*);
1640
1641   /* find window size */
1642   x = mp_count_bits (X);
1643   if (x <= 7) {
1644     winsize = 2;
1645   } else if (x <= 36) {
1646     winsize = 3;
1647   } else if (x <= 140) {
1648     winsize = 4;
1649   } else if (x <= 450) {
1650     winsize = 5;
1651   } else if (x <= 1303) {
1652     winsize = 6;
1653   } else if (x <= 3529) {
1654     winsize = 7;
1655   } else {
1656     winsize = 8;
1657   }
1658
1659 #ifdef MP_LOW_MEM
1660     if (winsize > 5) {
1661        winsize = 5;
1662     }
1663 #endif
1664
1665   /* init M array */
1666   /* init first cell */
1667   if ((err = mp_init(&M[1])) != MP_OKAY) {
1668      return err; 
1669   }
1670
1671   /* now init the second half of the array */
1672   for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
1673     if ((err = mp_init(&M[x])) != MP_OKAY) {
1674       for (y = 1<<(winsize-1); y < x; y++) {
1675         mp_clear (&M[y]);
1676       }
1677       mp_clear(&M[1]);
1678       return err;
1679     }
1680   }
1681
1682   /* create mu, used for Barrett reduction */
1683   if ((err = mp_init (&mu)) != MP_OKAY) {
1684     goto LBL_M;
1685   }
1686   
1687   if (redmode == 0) {
1688      if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) {
1689         goto LBL_MU;
1690      }
1691      redux = mp_reduce;
1692   } else {
1693      if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) {
1694         goto LBL_MU;
1695      }
1696      redux = mp_reduce_2k_l;
1697   }    
1698
1699   /* create M table
1700    *
1701    * The M table contains powers of the base, 
1702    * e.g. M[x] = G**x mod P
1703    *
1704    * The first half of the table is not 
1705    * computed though accept for M[0] and M[1]
1706    */
1707   if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) {
1708     goto LBL_MU;
1709   }
1710
1711   /* compute the value at M[1<<(winsize-1)] by squaring 
1712    * M[1] (winsize-1) times 
1713    */
1714   if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
1715     goto LBL_MU;
1716   }
1717
1718   for (x = 0; x < (winsize - 1); x++) {
1719     /* square it */
1720     if ((err = mp_sqr (&M[1 << (winsize - 1)], 
1721                        &M[1 << (winsize - 1)])) != MP_OKAY) {
1722       goto LBL_MU;
1723     }
1724
1725     /* reduce modulo P */
1726     if ((err = redux (&M[1 << (winsize - 1)], P, &mu)) != MP_OKAY) {
1727       goto LBL_MU;
1728     }
1729   }
1730
1731   /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
1732    * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
1733    */
1734   for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
1735     if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
1736       goto LBL_MU;
1737     }
1738     if ((err = redux (&M[x], P, &mu)) != MP_OKAY) {
1739       goto LBL_MU;
1740     }
1741   }
1742
1743   /* setup result */
1744   if ((err = mp_init (&res)) != MP_OKAY) {
1745     goto LBL_MU;
1746   }
1747   mp_set (&res, 1);
1748
1749   /* set initial mode and bit cnt */
1750   mode   = 0;
1751   bitcnt = 1;
1752   buf    = 0;
1753   digidx = X->used - 1;
1754   bitcpy = 0;
1755   bitbuf = 0;
1756
1757   for (;;) {
1758     /* grab next digit as required */
1759     if (--bitcnt == 0) {
1760       /* if digidx == -1 we are out of digits */
1761       if (digidx == -1) {
1762         break;
1763       }
1764       /* read next digit and reset the bitcnt */
1765       buf    = X->dp[digidx--];
1766       bitcnt = (int) DIGIT_BIT;
1767     }
1768
1769     /* grab the next msb from the exponent */
1770     y     = (buf >> (mp_digit)(DIGIT_BIT - 1)) & 1;
1771     buf <<= (mp_digit)1;
1772
1773     /* if the bit is zero and mode == 0 then we ignore it
1774      * These represent the leading zero bits before the first 1 bit
1775      * in the exponent.  Technically this opt is not required but it
1776      * does lower the # of trivial squaring/reductions used
1777      */
1778     if (mode == 0 && y == 0) {
1779       continue;
1780     }
1781
1782     /* if the bit is zero and mode == 1 then we square */
1783     if (mode == 1 && y == 0) {
1784       if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
1785         goto LBL_RES;
1786       }
1787       if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1788         goto LBL_RES;
1789       }
1790       continue;
1791     }
1792
1793     /* else we add it to the window */
1794     bitbuf |= (y << (winsize - ++bitcpy));
1795     mode    = 2;
1796
1797     if (bitcpy == winsize) {
1798       /* ok window is filled so square as required and multiply  */
1799       /* square first */
1800       for (x = 0; x < winsize; x++) {
1801         if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
1802           goto LBL_RES;
1803         }
1804         if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1805           goto LBL_RES;
1806         }
1807       }
1808
1809       /* then multiply */
1810       if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
1811         goto LBL_RES;
1812       }
1813       if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1814         goto LBL_RES;
1815       }
1816
1817       /* empty window and reset */
1818       bitcpy = 0;
1819       bitbuf = 0;
1820       mode   = 1;
1821     }
1822   }
1823
1824   /* if bits remain then square/multiply */
1825   if (mode == 2 && bitcpy > 0) {
1826     /* square then multiply if the bit is set */
1827     for (x = 0; x < bitcpy; x++) {
1828       if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
1829         goto LBL_RES;
1830       }
1831       if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1832         goto LBL_RES;
1833       }
1834
1835       bitbuf <<= 1;
1836       if ((bitbuf & (1 << winsize)) != 0) {
1837         /* then multiply */
1838         if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
1839           goto LBL_RES;
1840         }
1841         if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1842           goto LBL_RES;
1843         }
1844       }
1845     }
1846   }
1847
1848   mp_exch (&res, Y);
1849   err = MP_OKAY;
1850 LBL_RES:mp_clear (&res);
1851 LBL_MU:mp_clear (&mu);
1852 LBL_M:
1853   mp_clear(&M[1]);
1854   for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
1855     mp_clear (&M[x]);
1856   }
1857   return err;
1858 }
1859
1860
1861 /* computes b = a*a */
1862 static int mp_sqr (mp_int * a, mp_int * b)
1863 {
1864   int     res;
1865
1866 #ifdef BN_MP_TOOM_SQR_C
1867   /* use Toom-Cook? */
1868   if (a->used >= TOOM_SQR_CUTOFF) {
1869     res = mp_toom_sqr(a, b);
1870   /* Karatsuba? */
1871   } else 
1872 #endif
1873 #ifdef BN_MP_KARATSUBA_SQR_C
1874 if (a->used >= KARATSUBA_SQR_CUTOFF) {
1875     res = mp_karatsuba_sqr (a, b);
1876   } else 
1877 #endif
1878   {
1879 #ifdef BN_FAST_S_MP_SQR_C
1880     /* can we use the fast comba multiplier? */
1881     if ((a->used * 2 + 1) < MP_WARRAY && 
1882          a->used < 
1883          (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) {
1884       res = fast_s_mp_sqr (a, b);
1885     } else
1886 #endif
1887 #ifdef BN_S_MP_SQR_C
1888       res = s_mp_sqr (a, b);
1889 #else
1890 #error mp_sqr could fail
1891       res = MP_VAL;
1892 #endif
1893   }
1894   b->sign = MP_ZPOS;
1895   return res;
1896 }
1897
1898
1899 /* reduces a modulo n where n is of the form 2**p - d 
1900    This differs from reduce_2k since "d" can be larger
1901    than a single digit.
1902 */
1903 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
1904 {
1905    mp_int q;
1906    int    p, res;
1907    
1908    if ((res = mp_init(&q)) != MP_OKAY) {
1909       return res;
1910    }
1911    
1912    p = mp_count_bits(n);    
1913 top:
1914    /* q = a/2**p, a = a mod 2**p */
1915    if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
1916       goto ERR;
1917    }
1918    
1919    /* q = q * d */
1920    if ((res = mp_mul(&q, d, &q)) != MP_OKAY) { 
1921       goto ERR;
1922    }
1923    
1924    /* a = a + q */
1925    if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
1926       goto ERR;
1927    }
1928    
1929    if (mp_cmp_mag(a, n) != MP_LT) {
1930       s_mp_sub(a, n, a);
1931       goto top;
1932    }
1933    
1934 ERR:
1935    mp_clear(&q);
1936    return res;
1937 }
1938
1939
1940 /* determines the setup value */
1941 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d)
1942 {
1943    int    res;
1944    mp_int tmp;
1945    
1946    if ((res = mp_init(&tmp)) != MP_OKAY) {
1947       return res;
1948    }
1949    
1950    if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
1951       goto ERR;
1952    }
1953    
1954    if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
1955       goto ERR;
1956    }
1957    
1958 ERR:
1959    mp_clear(&tmp);
1960    return res;
1961 }
1962
1963
1964 /* computes a = 2**b 
1965  *
1966  * Simple algorithm which zeroes the int, grows it then just sets one bit
1967  * as required.
1968  */
1969 static int mp_2expt (mp_int * a, int b)
1970 {
1971   int     res;
1972
1973   /* zero a as per default */
1974   mp_zero (a);
1975
1976   /* grow a to accomodate the single bit */
1977   if ((res = mp_grow (a, b / DIGIT_BIT + 1)) != MP_OKAY) {
1978     return res;
1979   }
1980
1981   /* set the used count of where the bit will go */
1982   a->used = b / DIGIT_BIT + 1;
1983
1984   /* put the single bit in its place */
1985   a->dp[b / DIGIT_BIT] = ((mp_digit)1) << (b % DIGIT_BIT);
1986
1987   return MP_OKAY;
1988 }
1989
1990
1991 /* pre-calculate the value required for Barrett reduction
1992  * For a given modulus "b" it calulates the value required in "a"
1993  */
1994 static int mp_reduce_setup (mp_int * a, mp_int * b)
1995 {
1996   int     res;
1997   
1998   if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) {
1999     return res;
2000   }
2001   return mp_div (a, b, a, NULL);
2002 }
2003
2004
2005 /* reduces x mod m, assumes 0 < x < m**2, mu is 
2006  * precomputed via mp_reduce_setup.
2007  * From HAC pp.604 Algorithm 14.42
2008  */
2009 static int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
2010 {
2011   mp_int  q;
2012   int     res, um = m->used;
2013
2014   /* q = x */
2015   if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
2016     return res;
2017   }
2018
2019   /* q1 = x / b**(k-1)  */
2020   mp_rshd (&q, um - 1);         
2021
2022   /* according to HAC this optimization is ok */
2023   if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) {
2024     if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) {
2025       goto CLEANUP;
2026     }
2027   } else {
2028 #ifdef BN_S_MP_MUL_HIGH_DIGS_C
2029     if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
2030       goto CLEANUP;
2031     }
2032 #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C)
2033     if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
2034       goto CLEANUP;
2035     }
2036 #else 
2037     { 
2038 #error mp_reduce would always fail
2039       res = MP_VAL;
2040       goto CLEANUP;
2041     }
2042 #endif
2043   }
2044
2045   /* q3 = q2 / b**(k+1) */
2046   mp_rshd (&q, um + 1);         
2047
2048   /* x = x mod b**(k+1), quick (no division) */
2049   if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
2050     goto CLEANUP;
2051   }
2052
2053   /* q = q * m mod b**(k+1), quick (no division) */
2054   if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) {
2055     goto CLEANUP;
2056   }
2057
2058   /* x = x - q */
2059   if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
2060     goto CLEANUP;
2061   }
2062
2063   /* If x < 0, add b**(k+1) to it */
2064   if (mp_cmp_d (x, 0) == MP_LT) {
2065     mp_set (&q, 1);
2066     if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) {
2067       goto CLEANUP;
2068     }
2069     if ((res = mp_add (x, &q, x)) != MP_OKAY) {
2070       goto CLEANUP;
2071     }
2072   }
2073
2074   /* Back off if it's too big */
2075   while (mp_cmp (x, m) != MP_LT) {
2076     if ((res = s_mp_sub (x, m, x)) != MP_OKAY) {
2077       goto CLEANUP;
2078     }
2079   }
2080   
2081 CLEANUP:
2082   mp_clear (&q);
2083
2084   return res;
2085 }
2086
2087
2088 /* multiplies |a| * |b| and only computes upto digs digits of result
2089  * HAC pp. 595, Algorithm 14.12  Modified so you can control how 
2090  * many digits of output are created.
2091  */
2092 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2093 {
2094   mp_int  t;
2095   int     res, pa, pb, ix, iy;
2096   mp_digit u;
2097   mp_word r;
2098   mp_digit tmpx, *tmpt, *tmpy;
2099
2100   /* can we use the fast multiplier? */
2101   if (((digs) < MP_WARRAY) &&
2102       MIN (a->used, b->used) < 
2103           (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2104     return fast_s_mp_mul_digs (a, b, c, digs);
2105   }
2106
2107   if ((res = mp_init_size (&t, digs)) != MP_OKAY) {
2108     return res;
2109   }
2110   t.used = digs;
2111
2112   /* compute the digits of the product directly */
2113   pa = a->used;
2114   for (ix = 0; ix < pa; ix++) {
2115     /* set the carry to zero */
2116     u = 0;
2117
2118     /* limit ourselves to making digs digits of output */
2119     pb = MIN (b->used, digs - ix);
2120
2121     /* setup some aliases */
2122     /* copy of the digit from a used within the nested loop */
2123     tmpx = a->dp[ix];
2124     
2125     /* an alias for the destination shifted ix places */
2126     tmpt = t.dp + ix;
2127     
2128     /* an alias for the digits of b */
2129     tmpy = b->dp;
2130
2131     /* compute the columns of the output and propagate the carry */
2132     for (iy = 0; iy < pb; iy++) {
2133       /* compute the column as a mp_word */
2134       r       = ((mp_word)*tmpt) +
2135                 ((mp_word)tmpx) * ((mp_word)*tmpy++) +
2136                 ((mp_word) u);
2137
2138       /* the new column is the lower part of the result */
2139       *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2140
2141       /* get the carry word from the result */
2142       u       = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2143     }
2144     /* set carry if it is placed below digs */
2145     if (ix + iy < digs) {
2146       *tmpt = u;
2147     }
2148   }
2149
2150   mp_clamp (&t);
2151   mp_exch (&t, c);
2152
2153   mp_clear (&t);
2154   return MP_OKAY;
2155 }
2156
2157
2158 /* Fast (comba) multiplier
2159  *
2160  * This is the fast column-array [comba] multiplier.  It is 
2161  * designed to compute the columns of the product first 
2162  * then handle the carries afterwards.  This has the effect 
2163  * of making the nested loops that compute the columns very
2164  * simple and schedulable on super-scalar processors.
2165  *
2166  * This has been modified to produce a variable number of 
2167  * digits of output so if say only a half-product is required 
2168  * you don't have to compute the upper half (a feature 
2169  * required for fast Barrett reduction).
2170  *
2171  * Based on Algorithm 14.12 on pp.595 of HAC.
2172  *
2173  */
2174 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2175 {
2176   int     olduse, res, pa, ix, iz;
2177   mp_digit W[MP_WARRAY];
2178   register mp_word  _W;
2179
2180   /* grow the destination as required */
2181   if (c->alloc < digs) {
2182     if ((res = mp_grow (c, digs)) != MP_OKAY) {
2183       return res;
2184     }
2185   }
2186
2187   /* number of output digits to produce */
2188   pa = MIN(digs, a->used + b->used);
2189
2190   /* clear the carry */
2191   _W = 0;
2192   for (ix = 0; ix < pa; ix++) { 
2193       int      tx, ty;
2194       int      iy;
2195       mp_digit *tmpx, *tmpy;
2196
2197       /* get offsets into the two bignums */
2198       ty = MIN(b->used-1, ix);
2199       tx = ix - ty;
2200
2201       /* setup temp aliases */
2202       tmpx = a->dp + tx;
2203       tmpy = b->dp + ty;
2204
2205       /* this is the number of times the loop will iterrate, essentially 
2206          while (tx++ < a->used && ty-- >= 0) { ... }
2207        */
2208       iy = MIN(a->used-tx, ty+1);
2209
2210       /* execute loop */
2211       for (iz = 0; iz < iy; ++iz) {
2212          _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
2213
2214       }
2215
2216       /* store term */
2217       W[ix] = ((mp_digit)_W) & MP_MASK;
2218
2219       /* make next carry */
2220       _W = _W >> ((mp_word)DIGIT_BIT);
2221  }
2222
2223   /* setup dest */
2224   olduse  = c->used;
2225   c->used = pa;
2226
2227   {
2228     register mp_digit *tmpc;
2229     tmpc = c->dp;
2230     for (ix = 0; ix < pa+1; ix++) {
2231       /* now extract the previous digit [below the carry] */
2232       *tmpc++ = W[ix];
2233     }
2234
2235     /* clear unused digits [that existed in the old copy of c] */
2236     for (; ix < olduse; ix++) {
2237       *tmpc++ = 0;
2238     }
2239   }
2240   mp_clamp (c);
2241   return MP_OKAY;
2242 }
2243
2244
2245 /* init an mp_init for a given size */
2246 static int mp_init_size (mp_int * a, int size)
2247 {
2248   int x;
2249
2250   /* pad size so there are always extra digits */
2251   size += (MP_PREC * 2) - (size % MP_PREC);     
2252   
2253   /* alloc mem */
2254   a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size);
2255   if (a->dp == NULL) {
2256     return MP_MEM;
2257   }
2258
2259   /* set the members */
2260   a->used  = 0;
2261   a->alloc = size;
2262   a->sign  = MP_ZPOS;
2263
2264   /* zero the digits */
2265   for (x = 0; x < size; x++) {
2266       a->dp[x] = 0;
2267   }
2268
2269   return MP_OKAY;
2270 }
2271
2272
2273 /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
2274 static int s_mp_sqr (mp_int * a, mp_int * b)
2275 {
2276   mp_int  t;
2277   int     res, ix, iy, pa;
2278   mp_word r;
2279   mp_digit u, tmpx, *tmpt;
2280
2281   pa = a->used;
2282   if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
2283     return res;
2284   }
2285
2286   /* default used is maximum possible size */
2287   t.used = 2*pa + 1;
2288
2289   for (ix = 0; ix < pa; ix++) {
2290     /* first calculate the digit at 2*ix */
2291     /* calculate double precision result */
2292     r = ((mp_word) t.dp[2*ix]) +
2293         ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]);
2294
2295     /* store lower part in result */
2296     t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
2297
2298     /* get the carry */
2299     u           = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2300
2301     /* left hand side of A[ix] * A[iy] */
2302     tmpx        = a->dp[ix];
2303
2304     /* alias for where to store the results */
2305     tmpt        = t.dp + (2*ix + 1);
2306     
2307     for (iy = ix + 1; iy < pa; iy++) {
2308       /* first calculate the product */
2309       r       = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
2310
2311       /* now calculate the double precision result, note we use
2312        * addition instead of *2 since it's easier to optimize
2313        */
2314       r       = ((mp_word) *tmpt) + r + r + ((mp_word) u);
2315
2316       /* store lower part */
2317       *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2318
2319       /* get carry */
2320       u       = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2321     }
2322     /* propagate upwards */
2323     while (u != ((mp_digit) 0)) {
2324       r       = ((mp_word) *tmpt) + ((mp_word) u);
2325       *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2326       u       = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2327     }
2328   }
2329
2330   mp_clamp (&t);
2331   mp_exch (&t, b);
2332   mp_clear (&t);
2333   return MP_OKAY;
2334 }
2335
2336
2337 /* multiplies |a| * |b| and does not compute the lower digs digits
2338  * [meant to get the higher part of the product]
2339  */
2340 static int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2341 {
2342   mp_int  t;
2343   int     res, pa, pb, ix, iy;
2344   mp_digit u;
2345   mp_word r;
2346   mp_digit tmpx, *tmpt, *tmpy;
2347
2348   /* can we use the fast multiplier? */
2349 #ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C
2350   if (((a->used + b->used + 1) < MP_WARRAY)
2351       && MIN (a->used, b->used) < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2352     return fast_s_mp_mul_high_digs (a, b, c, digs);
2353   }
2354 #endif
2355
2356   if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) {
2357     return res;
2358   }
2359   t.used = a->used + b->used + 1;
2360
2361   pa = a->used;
2362   pb = b->used;
2363   for (ix = 0; ix < pa; ix++) {
2364     /* clear the carry */
2365     u = 0;
2366
2367     /* left hand side of A[ix] * B[iy] */
2368     tmpx = a->dp[ix];
2369
2370     /* alias to the address of where the digits will be stored */
2371     tmpt = &(t.dp[digs]);
2372
2373     /* alias for where to read the right hand side from */
2374     tmpy = b->dp + (digs - ix);
2375
2376     for (iy = digs - ix; iy < pb; iy++) {
2377       /* calculate the double precision result */
2378       r       = ((mp_word)*tmpt) +
2379                 ((mp_word)tmpx) * ((mp_word)*tmpy++) +
2380                 ((mp_word) u);
2381
2382       /* get the lower part */
2383       *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2384
2385       /* carry the carry */
2386       u       = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2387     }
2388     *tmpt = u;
2389   }
2390   mp_clamp (&t);
2391   mp_exch (&t, c);
2392   mp_clear (&t);
2393   return MP_OKAY;
2394 }
2395
2396
2397 #ifdef BN_MP_MONTGOMERY_SETUP_C
2398 /* setups the montgomery reduction stuff */
2399 static int
2400 mp_montgomery_setup (mp_int * n, mp_digit * rho)
2401 {
2402   mp_digit x, b;
2403
2404 /* fast inversion mod 2**k
2405  *
2406  * Based on the fact that
2407  *
2408  * XA = 1 (mod 2**n)  =>  (X(2-XA)) A = 1 (mod 2**2n)
2409  *                    =>  2*X*A - X*X*A*A = 1
2410  *                    =>  2*(1) - (1)     = 1
2411  */
2412   b = n->dp[0];
2413
2414   if ((b & 1) == 0) {
2415     return MP_VAL;
2416   }
2417
2418   x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
2419   x *= 2 - b * x;               /* here x*a==1 mod 2**8 */
2420 #if !defined(MP_8BIT)
2421   x *= 2 - b * x;               /* here x*a==1 mod 2**16 */
2422 #endif
2423 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
2424   x *= 2 - b * x;               /* here x*a==1 mod 2**32 */
2425 #endif
2426 #ifdef MP_64BIT
2427   x *= 2 - b * x;               /* here x*a==1 mod 2**64 */
2428 #endif
2429
2430   /* rho = -1/m mod b */
2431   *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK;
2432
2433   return MP_OKAY;
2434 }
2435 #endif
2436
2437
2438 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2439 /* computes xR**-1 == x (mod N) via Montgomery Reduction
2440  *
2441  * This is an optimized implementation of montgomery_reduce
2442  * which uses the comba method to quickly calculate the columns of the
2443  * reduction.
2444  *
2445  * Based on Algorithm 14.32 on pp.601 of HAC.
2446 */
2447 int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
2448 {
2449   int     ix, res, olduse;
2450   mp_word W[MP_WARRAY];
2451
2452   /* get old used count */
2453   olduse = x->used;
2454
2455   /* grow a as required */
2456   if (x->alloc < n->used + 1) {
2457     if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) {
2458       return res;
2459     }
2460   }
2461
2462   /* first we have to get the digits of the input into
2463    * an array of double precision words W[...]
2464    */
2465   {
2466     register mp_word *_W;
2467     register mp_digit *tmpx;
2468
2469     /* alias for the W[] array */
2470     _W   = W;
2471
2472     /* alias for the digits of  x*/
2473     tmpx = x->dp;
2474
2475     /* copy the digits of a into W[0..a->used-1] */
2476     for (ix = 0; ix < x->used; ix++) {
2477       *_W++ = *tmpx++;
2478     }
2479
2480     /* zero the high words of W[a->used..m->used*2] */
2481     for (; ix < n->used * 2 + 1; ix++) {
2482       *_W++ = 0;
2483     }
2484   }
2485
2486   /* now we proceed to zero successive digits
2487    * from the least significant upwards
2488    */
2489   for (ix = 0; ix < n->used; ix++) {
2490     /* mu = ai * m' mod b
2491      *
2492      * We avoid a double precision multiplication (which isn't required)
2493      * by casting the value down to a mp_digit.  Note this requires
2494      * that W[ix-1] have  the carry cleared (see after the inner loop)
2495      */
2496     register mp_digit mu;
2497     mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK);
2498
2499     /* a = a + mu * m * b**i
2500      *
2501      * This is computed in place and on the fly.  The multiplication
2502      * by b**i is handled by offseting which columns the results
2503      * are added to.
2504      *
2505      * Note the comba method normally doesn't handle carries in the
2506      * inner loop In this case we fix the carry from the previous
2507      * column since the Montgomery reduction requires digits of the
2508      * result (so far) [see above] to work.  This is
2509      * handled by fixing up one carry after the inner loop.  The
2510      * carry fixups are done in order so after these loops the
2511      * first m->used words of W[] have the carries fixed
2512      */
2513     {
2514       register int iy;
2515       register mp_digit *tmpn;
2516       register mp_word *_W;
2517
2518       /* alias for the digits of the modulus */
2519       tmpn = n->dp;
2520
2521       /* Alias for the columns set by an offset of ix */
2522       _W = W + ix;
2523
2524       /* inner loop */
2525       for (iy = 0; iy < n->used; iy++) {
2526           *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++);
2527       }
2528     }
2529
2530     /* now fix carry for next digit, W[ix+1] */
2531     W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT);
2532   }
2533
2534   /* now we have to propagate the carries and
2535    * shift the words downward [all those least
2536    * significant digits we zeroed].
2537    */
2538   {
2539     register mp_digit *tmpx;
2540     register mp_word *_W, *_W1;
2541
2542     /* nox fix rest of carries */
2543
2544     /* alias for current word */
2545     _W1 = W + ix;
2546
2547     /* alias for next word, where the carry goes */
2548     _W = W + ++ix;
2549
2550     for (; ix <= n->used * 2 + 1; ix++) {
2551       *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT);
2552     }
2553
2554     /* copy out, A = A/b**n
2555      *
2556      * The result is A/b**n but instead of converting from an
2557      * array of mp_word to mp_digit than calling mp_rshd
2558      * we just copy them in the right order
2559      */
2560
2561     /* alias for destination word */
2562     tmpx = x->dp;
2563
2564     /* alias for shifted double precision result */
2565     _W = W + n->used;
2566
2567     for (ix = 0; ix < n->used + 1; ix++) {
2568       *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK));
2569     }
2570
2571     /* zero oldused digits, if the input a was larger than
2572      * m->used+1 we'll have to clear the digits
2573      */
2574     for (; ix < olduse; ix++) {
2575       *tmpx++ = 0;
2576     }
2577   }
2578
2579   /* set the max used and clamp */
2580   x->used = n->used + 1;
2581   mp_clamp (x);
2582
2583   /* if A >= m then A = A - m */
2584   if (mp_cmp_mag (x, n) != MP_LT) {
2585     return s_mp_sub (x, n, x);
2586   }
2587   return MP_OKAY;
2588 }
2589 #endif
2590
2591
2592 #ifdef BN_MP_MUL_2_C
2593 /* b = a*2 */
2594 static int mp_mul_2(mp_int * a, mp_int * b)
2595 {
2596   int     x, res, oldused;
2597
2598   /* grow to accomodate result */
2599   if (b->alloc < a->used + 1) {
2600     if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) {
2601       return res;
2602     }
2603   }
2604
2605   oldused = b->used;
2606   b->used = a->used;
2607
2608   {
2609     register mp_digit r, rr, *tmpa, *tmpb;
2610
2611     /* alias for source */
2612     tmpa = a->dp;
2613     
2614     /* alias for dest */
2615     tmpb = b->dp;
2616
2617     /* carry */
2618     r = 0;
2619     for (x = 0; x < a->used; x++) {
2620     
2621       /* get what will be the *next* carry bit from the 
2622        * MSB of the current digit 
2623        */
2624       rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1));
2625       
2626       /* now shift up this digit, add in the carry [from the previous] */
2627       *tmpb++ = ((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK;
2628       
2629       /* copy the carry that would be from the source 
2630        * digit into the next iteration 
2631        */
2632       r = rr;
2633     }
2634
2635     /* new leading digit? */
2636     if (r != 0) {
2637       /* add a MSB which is always 1 at this point */
2638       *tmpb = 1;
2639       ++(b->used);
2640     }
2641
2642     /* now zero any excess digits on the destination 
2643      * that we didn't write to 
2644      */
2645     tmpb = b->dp + b->used;
2646     for (x = b->used; x < oldused; x++) {
2647       *tmpb++ = 0;
2648     }
2649   }
2650   b->sign = a->sign;
2651   return MP_OKAY;
2652 }
2653 #endif
2654
2655
2656 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
2657 /*
2658  * shifts with subtractions when the result is greater than b.
2659  *
2660  * The method is slightly modified to shift B unconditionally upto just under
2661  * the leading bit of b.  This saves alot of multiple precision shifting.
2662  */
2663 static int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
2664 {
2665   int     x, bits, res;
2666
2667   /* how many bits of last digit does b use */
2668   bits = mp_count_bits (b) % DIGIT_BIT;
2669
2670   if (b->used > 1) {
2671      if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) {
2672         return res;
2673      }
2674   } else {
2675      mp_set(a, 1);
2676      bits = 1;
2677   }
2678
2679
2680   /* now compute C = A * B mod b */
2681   for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
2682     if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
2683       return res;
2684     }
2685     if (mp_cmp_mag (a, b) != MP_LT) {
2686       if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
2687         return res;
2688       }
2689     }
2690   }
2691
2692   return MP_OKAY;
2693 }
2694 #endif
2695
2696
2697 #ifdef BN_MP_EXPTMOD_FAST_C
2698 /* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
2699  *
2700  * Uses a left-to-right k-ary sliding window to compute the modular exponentiation.
2701  * The value of k changes based on the size of the exponent.
2702  *
2703  * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
2704  */
2705
2706 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
2707 {
2708   mp_int  M[TAB_SIZE], res;
2709   mp_digit buf, mp;
2710   int     err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
2711
2712   /* use a pointer to the reduction algorithm.  This allows us to use
2713    * one of many reduction algorithms without modding the guts of
2714    * the code with if statements everywhere.
2715    */
2716   int     (*redux)(mp_int*,mp_int*,mp_digit);
2717
2718   /* find window size */
2719   x = mp_count_bits (X);
2720   if (x <= 7) {
2721     winsize = 2;
2722   } else if (x <= 36) {
2723     winsize = 3;
2724   } else if (x <= 140) {
2725     winsize = 4;
2726   } else if (x <= 450) {
2727     winsize = 5;
2728   } else if (x <= 1303) {
2729     winsize = 6;
2730   } else if (x <= 3529) {
2731     winsize = 7;
2732   } else {
2733     winsize = 8;
2734   }
2735
2736 #ifdef MP_LOW_MEM
2737   if (winsize > 5) {
2738      winsize = 5;
2739   }
2740 #endif
2741
2742   /* init M array */
2743   /* init first cell */
2744   if ((err = mp_init(&M[1])) != MP_OKAY) {
2745      return err;
2746   }
2747
2748   /* now init the second half of the array */
2749   for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
2750     if ((err = mp_init(&M[x])) != MP_OKAY) {
2751       for (y = 1<<(winsize-1); y < x; y++) {
2752         mp_clear (&M[y]);
2753       }
2754       mp_clear(&M[1]);
2755       return err;
2756     }
2757   }
2758
2759   /* determine and setup reduction code */
2760   if (redmode == 0) {
2761 #ifdef BN_MP_MONTGOMERY_SETUP_C     
2762      /* now setup montgomery  */
2763      if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
2764         goto LBL_M;
2765      }
2766 #else
2767      err = MP_VAL;
2768      goto LBL_M;
2769 #endif
2770
2771      /* automatically pick the comba one if available (saves quite a few calls/ifs) */
2772 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2773      if (((P->used * 2 + 1) < MP_WARRAY) &&
2774           P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2775         redux = fast_mp_montgomery_reduce;
2776      } else 
2777 #endif
2778      {
2779 #ifdef BN_MP_MONTGOMERY_REDUCE_C
2780         /* use slower baseline Montgomery method */
2781         redux = mp_montgomery_reduce;
2782 #else
2783         err = MP_VAL;
2784         goto LBL_M;
2785 #endif
2786      }
2787   } else if (redmode == 1) {
2788 #if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C)
2789      /* setup DR reduction for moduli of the form B**k - b */
2790      mp_dr_setup(P, &mp);
2791      redux = mp_dr_reduce;
2792 #else
2793      err = MP_VAL;
2794      goto LBL_M;
2795 #endif
2796   } else {
2797 #if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C)
2798      /* setup DR reduction for moduli of the form 2**k - b */
2799      if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) {
2800         goto LBL_M;
2801      }
2802      redux = mp_reduce_2k;
2803 #else
2804      err = MP_VAL;
2805      goto LBL_M;
2806 #endif
2807   }
2808
2809   /* setup result */
2810   if ((err = mp_init (&res)) != MP_OKAY) {
2811     goto LBL_M;
2812   }
2813
2814   /* create M table
2815    *
2816
2817    *
2818    * The first half of the table is not computed though accept for M[0] and M[1]
2819    */
2820
2821   if (redmode == 0) {
2822 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
2823      /* now we need R mod m */
2824      if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) {
2825        goto LBL_RES;
2826      }
2827 #else 
2828      err = MP_VAL;
2829      goto LBL_RES;
2830 #endif
2831
2832      /* now set M[1] to G * R mod m */
2833      if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
2834        goto LBL_RES;
2835      }
2836   } else {
2837      mp_set(&res, 1);
2838      if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
2839         goto LBL_RES;
2840      }
2841   }
2842
2843   /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times */
2844   if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
2845     goto LBL_RES;
2846   }
2847
2848   for (x = 0; x < (winsize - 1); x++) {
2849     if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) {
2850       goto LBL_RES;
2851     }
2852     if ((err = redux (&M[1 << (winsize - 1)], P, mp)) != MP_OKAY) {
2853       goto LBL_RES;
2854     }
2855   }
2856
2857   /* create upper table */
2858   for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
2859     if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
2860       goto LBL_RES;
2861     }
2862     if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
2863       goto LBL_RES;
2864     }
2865   }
2866
2867   /* set initial mode and bit cnt */
2868   mode   = 0;
2869   bitcnt = 1;
2870   buf    = 0;
2871   digidx = X->used - 1;
2872   bitcpy = 0;
2873   bitbuf = 0;
2874
2875   for (;;) {
2876     /* grab next digit as required */
2877     if (--bitcnt == 0) {
2878       /* if digidx == -1 we are out of digits so break */
2879       if (digidx == -1) {
2880         break;
2881       }
2882       /* read next digit and reset bitcnt */
2883       buf    = X->dp[digidx--];
2884       bitcnt = (int)DIGIT_BIT;
2885     }
2886
2887     /* grab the next msb from the exponent */
2888     y     = (mp_digit)(buf >> (DIGIT_BIT - 1)) & 1;
2889     buf <<= (mp_digit)1;
2890
2891     /* if the bit is zero and mode == 0 then we ignore it
2892      * These represent the leading zero bits before the first 1 bit
2893      * in the exponent.  Technically this opt is not required but it
2894      * does lower the # of trivial squaring/reductions used
2895      */
2896     if (mode == 0 && y == 0) {
2897       continue;
2898     }
2899
2900     /* if the bit is zero and mode == 1 then we square */
2901     if (mode == 1 && y == 0) {
2902       if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2903         goto LBL_RES;
2904       }
2905       if ((err = redux (&res, P, mp)) != MP_OKAY) {
2906         goto LBL_RES;
2907       }
2908       continue;
2909     }
2910
2911     /* else we add it to the window */
2912     bitbuf |= (y << (winsize - ++bitcpy));
2913     mode    = 2;
2914
2915     if (bitcpy == winsize) {
2916       /* ok window is filled so square as required and multiply  */
2917       /* square first */
2918       for (x = 0; x < winsize; x++) {
2919         if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2920           goto LBL_RES;
2921         }
2922         if ((err = redux (&res, P, mp)) != MP_OKAY) {
2923           goto LBL_RES;
2924         }
2925       }
2926
2927       /* then multiply */
2928       if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
2929         goto LBL_RES;
2930       }
2931       if ((err = redux (&res, P, mp)) != MP_OKAY) {
2932         goto LBL_RES;
2933       }
2934
2935       /* empty window and reset */
2936       bitcpy = 0;
2937       bitbuf = 0;
2938       mode   = 1;
2939     }
2940   }
2941
2942   /* if bits remain then square/multiply */
2943   if (mode == 2 && bitcpy > 0) {
2944     /* square then multiply if the bit is set */
2945     for (x = 0; x < bitcpy; x++) {
2946       if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2947         goto LBL_RES;
2948       }
2949       if ((err = redux (&res, P, mp)) != MP_OKAY) {
2950         goto LBL_RES;
2951       }
2952
2953       /* get next bit of the window */
2954       bitbuf <<= 1;
2955       if ((bitbuf & (1 << winsize)) != 0) {
2956         /* then multiply */
2957         if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
2958           goto LBL_RES;
2959         }
2960         if ((err = redux (&res, P, mp)) != MP_OKAY) {
2961           goto LBL_RES;
2962         }
2963       }
2964     }
2965   }
2966
2967   if (redmode == 0) {
2968      /* fixup result if Montgomery reduction is used
2969       * recall that any value in a Montgomery system is
2970       * actually multiplied by R mod n.  So we have
2971       * to reduce one more time to cancel out the factor
2972       * of R.
2973       */
2974      if ((err = redux(&res, P, mp)) != MP_OKAY) {
2975        goto LBL_RES;
2976      }
2977   }
2978
2979   /* swap res with Y */
2980   mp_exch (&res, Y);
2981   err = MP_OKAY;
2982 LBL_RES:mp_clear (&res);
2983 LBL_M:
2984   mp_clear(&M[1]);
2985   for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
2986     mp_clear (&M[x]);
2987   }
2988   return err;
2989 }
2990 #endif