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.
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
13 * If CONFIG_INTERNAL_LIBTOMMATH is defined, bignum.c includes this
14 * libtommath.c file instead of using the external LibTomMath library.
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
27 #define BN_S_MP_MUL_HIGH_DIGS_C /* Note: #undef in tommath_superclass.h; this
28 * would require other than mp_reduce */
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
37 #endif /* LTM_FAST_EXPTMOD */
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
46 #define MIN(x,y) ((x)<(y)?(x):(y))
50 #define MAX(x,y) ((x)>(y)?(x):(y))
55 typedef unsigned long mp_digit;
62 #define XMALLOC os_malloc
64 #define XREALLOC os_realloc
67 #define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))
69 #define MP_LT -1 /* less than */
70 #define MP_EQ 0 /* equal to */
71 #define MP_GT 1 /* greater than */
73 #define MP_ZPOS 0 /* positive integer */
74 #define MP_NEG 1 /* negative */
76 #define MP_OKAY 0 /* ok result */
77 #define MP_MEM -2 /* out of mem */
78 #define MP_VAL -3 /* invalid input */
80 #define MP_YES 1 /* yes response */
81 #define MP_NO 0 /* no response */
85 /* define this to use lower memory usage routines (exptmods mostly) */
88 /* default precision */
91 #define MP_PREC 32 /* default digits of precision */
93 #define MP_PREC 8 /* default digits of precision */
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))
100 /* the infamous mp_int structure */
102 int used, alloc, sign;
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)
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);
120 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
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 */
159 /* functions from bn_<func name>.c */
162 /* reverse an array, used for radix code */
163 static void bn_reverse (unsigned char *s, int len)
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)
184 int olduse, res, min, max;
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
189 if (a->used > b->used) {
200 if (c->alloc < max + 1) {
201 if ((res = mp_grow (c, max + 1)) != MP_OKAY) {
206 /* get old used digit count and set new one */
211 register mp_digit u, *tmpa, *tmpb, *tmpc;
214 /* alias for digit pointers */
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;
231 /* U = carry bit of T[i] */
232 u = *tmpc >> ((mp_digit)DIGIT_BIT);
234 /* take away carry bit from T[i] */
238 /* now copy higher words if any, that is in A+B
239 * if A or B has more digits add those in
242 for (; i < max; i++) {
243 /* T[i] = X[i] + U */
244 *tmpc = x->dp[i] + u;
246 /* U = carry bit of T[i] */
247 u = *tmpc >> ((mp_digit)DIGIT_BIT);
249 /* take away carry bit from T[i] */
257 /* clear digits above oldused */
258 for (i = c->used; i < olduse; i++) {
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)
271 int olduse, res, min, max;
278 if (c->alloc < max) {
279 if ((res = mp_grow (c, max)) != MP_OKAY) {
287 register mp_digit u, *tmpa, *tmpb, *tmpc;
290 /* alias for digit pointers */
295 /* set carry to zero */
297 for (i = 0; i < min; i++) {
298 /* T[i] = A[i] - B[i] - U */
299 *tmpc = *tmpa++ - *tmpb++ - u;
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
306 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
308 /* Clear carry from T[i] */
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 */
317 /* U = carry bit of T[i] */
318 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
320 /* Clear carry from T[i] */
324 /* clear digits above used (since we may not have grown result above) */
325 for (i = c->used; i < olduse; i++) {
335 /* init a new mp_int */
336 static int mp_init (mp_int * a)
340 /* allocate memory required and clear it */
341 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * MP_PREC);
346 /* set the digits to zero */
347 for (i = 0; i < MP_PREC; i++) {
351 /* set the used to zero, allocated digits to the default precision
352 * and sign to positive */
361 /* clear one (frees) */
362 static void mp_clear (mp_int * a)
366 /* only do anything if a hasn't been freed previously */
368 /* first zero the digits */
369 for (i = 0; i < a->used; i++) {
376 /* reset members to make debugging easier */
378 a->alloc = a->used = 0;
384 /* high level addition (handles signs) */
385 static int mp_add (mp_int * a, mp_int * b, mp_int * c)
389 /* get sign of both inputs */
393 /* handle two cases, not four */
395 /* both positive or both negative */
396 /* add their magnitudes, copy the sign */
398 res = s_mp_add (a, b, c);
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) {
406 res = s_mp_sub (b, a, c);
409 res = s_mp_sub (a, b, c);
416 /* high level subtraction (handles signs) */
417 static int mp_sub (mp_int * a, mp_int * b, mp_int * c)
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. */
430 res = s_mp_add (a, b, c);
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 */
439 /* The first has a larger or equal magnitude */
440 res = s_mp_sub (a, b, c);
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);
453 /* high level multiplication (handles sign) */
454 static int mp_mul (mp_int * a, mp_int * b, mp_int * c)
457 neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
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);
465 #ifdef BN_MP_KARATSUBA_MUL_C
467 if (MIN (a->used, b->used) >= KARATSUBA_MUL_CUTOFF) {
468 res = mp_karatsuba_mul (a, b, c);
472 /* can we use the fast multiplier?
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
478 #ifdef BN_FAST_S_MP_MUL_DIGS_C
479 int digs = a->used + b->used + 1;
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);
487 #ifdef BN_S_MP_MUL_DIGS_C
488 res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */
490 #error mp_mul could fail
495 c->sign = (c->used > 0) ? neg : MP_ZPOS;
500 /* d = a * b (mod c) */
501 static int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
506 if ((res = mp_init (&t)) != MP_OKAY) {
510 if ((res = mp_mul (a, b, &t)) != MP_OKAY) {
514 res = mp_mod (&t, c, d);
520 /* c = a mod b, 0 <= c < b */
521 static int mp_mod (mp_int * a, mp_int * b, mp_int * c)
526 if ((res = mp_init (&t)) != MP_OKAY) {
530 if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) {
535 if (t.sign != b->sign) {
536 res = mp_add (b, &t, c);
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)
552 static int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
556 /* modulus P must be positive */
557 if (P->sign == MP_NEG) {
561 /* if exponent X is negative we have to recurse */
562 if (X->sign == MP_NEG) {
563 #ifdef LTM_NO_NEG_EXP
565 #else /* LTM_NO_NEG_EXP */
566 #ifdef BN_MP_INVMOD_C
570 /* first compute 1/G mod P */
571 if ((err = mp_init(&tmpG)) != MP_OKAY) {
574 if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
580 if ((err = mp_init(&tmpX)) != MP_OKAY) {
584 if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
585 mp_clear_multi(&tmpG, &tmpX, NULL);
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);
594 #error mp_exptmod would always fail
598 #endif /* LTM_NO_NEG_EXP */
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);
608 #ifdef BN_MP_DR_IS_MODULUS_C
609 /* is it a DR modulus? */
610 dr = mp_dr_is_modulus(P);
616 #ifdef BN_MP_REDUCE_IS_2K_C
617 /* if not, is it a unrestricted DR modulus? */
619 dr = mp_reduce_is_2k(P) << 1;
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);
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);
633 #error mp_exptmod could fail
634 /* no exptmod for evens */
637 #ifdef BN_MP_EXPTMOD_FAST_C
643 /* compare two ints (signed)*/
644 static int mp_cmp (mp_int * a, mp_int * b)
646 /* compare based on sign */
647 if (a->sign != b->sign) {
648 if (a->sign == MP_NEG) {
656 if (a->sign == MP_NEG) {
657 /* if negative compare opposite direction */
658 return mp_cmp_mag(b, a);
660 return mp_cmp_mag(a, b);
665 /* compare a digit */
666 static int mp_cmp_d(mp_int * a, mp_digit b)
668 /* compare based on sign */
669 if (a->sign == MP_NEG) {
673 /* compare based on magnitude */
678 /* compare the only digit of a to b */
681 } else if (a->dp[0] < b) {
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)
693 /* b cannot be negative */
694 if (b->sign == MP_NEG || mp_iszero(b) == 1) {
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);
705 #ifdef BN_MP_INVMOD_SLOW_C
706 return mp_invmod_slow(a, b, c);
709 #ifndef BN_FAST_MP_INVMOD_C
710 #ifndef BN_MP_INVMOD_SLOW_C
711 #error mp_invmod would always fail
716 #endif /* LTM_NO_NEG_EXP */
719 /* get the size for an unsigned equivalent */
720 static int mp_unsigned_bin_size (mp_int * a)
722 int size = mp_count_bits (a);
723 return (size / 8 + ((size & 7) != 0 ? 1 : 0));
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)
731 mp_int x, y, u, v, A, B, C, D;
734 /* b cannot be negative */
735 if (b->sign == MP_NEG || mp_iszero(b) == 1) {
740 if ((res = mp_init_multi(&x, &y, &u, &v,
741 &A, &B, &C, &D, NULL)) != MP_OKAY) {
746 if ((res = mp_mod(a, b, &x)) != MP_OKAY) {
749 if ((res = mp_copy (b, &y)) != MP_OKAY) {
753 /* 2. [modified] if x,y are both even then return an error! */
754 if (mp_iseven (&x) == 1 && mp_iseven (&y) == 1) {
759 /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
760 if ((res = mp_copy (&x, &u)) != MP_OKAY) {
763 if ((res = mp_copy (&y, &v)) != MP_OKAY) {
770 /* 4. while u is even do */
771 while (mp_iseven (&u) == 1) {
773 if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
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) {
782 if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
786 /* A = A/2, B = B/2 */
787 if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
790 if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
795 /* 5. while v is even do */
796 while (mp_iseven (&v) == 1) {
798 if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
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) {
807 if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
811 /* C = C/2, D = D/2 */
812 if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
815 if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
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) {
827 if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
831 if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
835 /* v - v - u, C = C - A, D = D - B */
836 if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
840 if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
844 if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
849 /* if not zero goto step 4 */
850 if (mp_iszero (&u) == 0)
853 /* now a = C, b = D, gcd == g*v */
855 /* if v != 1 then there is no inverse */
856 if (mp_cmp_d (&v, 1) != MP_EQ) {
862 while (mp_cmp_d(&C, 0) == MP_LT) {
863 if ((res = mp_add(&C, b, &C)) != MP_OKAY) {
869 while (mp_cmp_mag(&C, b) != MP_LT) {
870 if ((res = mp_sub(&C, b, &C)) != MP_OKAY) {
875 /* C is now the inverse */
878 LBL_ERR:mp_clear_multi (&x, &y, &u, &v, &A, &B, &C, &D, NULL);
881 #endif /* LTM_NO_NEG_EXP */
884 /* compare maginitude of two ints (unsigned) */
885 static int mp_cmp_mag (mp_int * a, mp_int * b)
888 mp_digit *tmpa, *tmpb;
890 /* compare based on # of non-zero digits */
891 if (a->used > b->used) {
895 if (a->used < b->used) {
900 tmpa = a->dp + (a->used - 1);
903 tmpb = b->dp + (a->used - 1);
905 /* compare based on digits */
906 for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
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)
924 /* make sure there are at least two digits */
926 if ((res = mp_grow(a, 2)) != MP_OKAY) {
934 /* read the bytes in */
936 if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) {
944 a->dp[0] = (*b & MP_MASK);
945 a->dp[1] |= ((*b++ >> 7U) & 1);
954 /* store in unsigned [big endian] format */
955 static int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
960 if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
965 while (mp_iszero (&t) == 0) {
967 b[x++] = (unsigned char) (t.dp[0] & 255);
969 b[x++] = (unsigned char) (t.dp[0] | ((t.dp[1] & 0x01) << 7));
971 if ((res = mp_div_2d (&t, 8, &t, NULL)) != MP_OKAY) {
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)
990 /* if the shift count is <= 0 then we do no work */
992 res = mp_copy (a, c);
999 if ((res = mp_init (&t)) != MP_OKAY) {
1003 /* get the remainder */
1005 if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
1012 if ((res = mp_copy (a, c)) != MP_OKAY) {
1017 /* shift by as many digits in the bit count */
1018 if (b >= (int)DIGIT_BIT) {
1019 mp_rshd (c, b / DIGIT_BIT);
1022 /* shift any bit count < DIGIT_BIT */
1023 D = (mp_digit) (b % DIGIT_BIT);
1025 register mp_digit *tmpc, mask, shift;
1028 mask = (((mp_digit)1) << D) - 1;
1031 shift = DIGIT_BIT - D;
1034 tmpc = c->dp + (c->used - 1);
1038 for (x = c->used - 1; x >= 0; x--) {
1039 /* get the lower bits of this word in a temp */
1042 /* shift the current word and mix in the carry bits from the previous word */
1043 *tmpc = (*tmpc >> D) | (r << shift);
1046 /* set the carry to the carry bits of the current word found above */
1059 static int mp_init_copy (mp_int * a, mp_int * b)
1063 if ((res = mp_init (a)) != MP_OKAY) {
1066 return mp_copy (b, a);
1071 static void mp_zero (mp_int * a)
1080 for (n = 0; n < a->alloc; n++) {
1087 static int mp_copy (mp_int * a, mp_int * b)
1091 /* if dst == src do nothing */
1097 if (b->alloc < a->used) {
1098 if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1103 /* zero b and copy the parameters over */
1105 register mp_digit *tmpa, *tmpb;
1107 /* pointer aliases */
1115 /* copy all the digits */
1116 for (n = 0; n < a->used; n++) {
1120 /* clear high digits */
1121 for (; n < b->used; n++) {
1126 /* copy used count and sign */
1133 /* shift right a certain amount of digits */
1134 static void mp_rshd (mp_int * a, int b)
1138 /* if b <= 0 then ignore it */
1143 /* if b > used then simply zero it and return */
1150 register mp_digit *bottom, *top;
1152 /* shift the digits down */
1157 /* top [offset into digits] */
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
1166 b-2 | b-1 | b0 | b1 | b2 | ... | bb | ---->
1168 \-------------------/ ---->
1170 for (x = 0; x < (a->used - b); x++) {
1174 /* zero the top digits */
1175 for (; x < a->used; x++) {
1180 /* remove excess digits */
1185 /* swap the elements of two integers, for cases where you can't simply swap the
1186 * mp_int pointers around
1188 static void mp_exch (mp_int * a, mp_int * b)
1198 /* trim unused digits
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
1205 static void mp_clamp (mp_int * a)
1207 /* decrease used while the most significant digit is
1210 while (a->used > 0 && a->dp[a->used - 1] == 0) {
1214 /* reset the sign flag if used == 0 */
1221 /* grow as required */
1222 static int mp_grow (mp_int * a, int size)
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);
1232 /* reallocate the array a->dp
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.
1238 tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size);
1240 /* reallocation failed but "a" is still valid [can be freed] */
1244 /* reallocation succeeded so set a->dp */
1247 /* zero excess digits */
1250 for (; i < a->alloc; i++) {
1260 * Simple function copies the input and fixes the sign to positive
1262 static int mp_abs (mp_int * a, mp_int * b)
1268 if ((res = mp_copy (a, b)) != MP_OKAY) {
1273 /* force the sign of b to positive */
1280 /* set to a digit */
1281 static void mp_set (mp_int * a, mp_digit b)
1284 a->dp[0] = b & MP_MASK;
1285 a->used = (a->dp[0] != 0) ? 1 : 0;
1289 #ifndef LTM_NO_NEG_EXP
1291 static int mp_div_2(mp_int * a, mp_int * b)
1293 int x, res, oldused;
1296 if (b->alloc < a->used) {
1297 if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1305 register mp_digit r, rr, *tmpa, *tmpb;
1308 tmpa = a->dp + b->used - 1;
1311 tmpb = b->dp + b->used - 1;
1315 for (x = b->used - 1; x >= 0; x--) {
1316 /* get the carry for the next iteration */
1319 /* shift the current digit, add in carry and store */
1320 *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
1322 /* forward carry to next iteration */
1326 /* zero excess digits */
1327 tmpb = b->dp + b->used;
1328 for (x = b->used; x < oldused; x++) {
1336 #endif /* LTM_NO_NEG_EXP */
1339 /* shift left by a certain bit count */
1340 static int mp_mul_2d (mp_int * a, int b, mp_int * c)
1347 if ((res = mp_copy (a, c)) != MP_OKAY) {
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) {
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) {
1365 /* shift any bit count < DIGIT_BIT */
1366 d = (mp_digit) (b % DIGIT_BIT);
1368 register mp_digit *tmpc, shift, mask, r, rr;
1371 /* bitmask for carries */
1372 mask = (((mp_digit)1) << d) - 1;
1374 /* shift for msbs */
1375 shift = DIGIT_BIT - d;
1382 for (x = 0; x < c->used; x++) {
1383 /* get the higher bits of the current word */
1384 rr = (*tmpc >> shift) & mask;
1386 /* shift the current word and OR in the carry */
1387 *tmpc = ((*tmpc << d) | r) & MP_MASK;
1390 /* set the carry to the carry bits of the current word */
1394 /* set final carry */
1396 c->dp[(c->used)++] = r;
1404 static int mp_init_multi(mp_int *mp, ...)
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;
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.
1419 /* end the current list */
1422 /* now start cleaning up */
1424 va_start(clean_args, mp);
1427 cur_arg = va_arg(clean_args, mp_int*);
1434 cur_arg = va_arg(args, mp_int*);
1437 return res; /* Assumed ok, if error flagged above. */
1441 static void mp_clear_multi(mp_int *mp, ...)
1443 mp_int* next_mp = mp;
1446 while (next_mp != NULL) {
1448 next_mp = va_arg(args, mp_int*);
1454 /* shift left a certain amount of digits */
1455 static int mp_lshd (mp_int * a, int b)
1459 /* if its less than zero return */
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) {
1472 register mp_digit *top, *bottom;
1474 /* increment the used by the shift amount then copy upwards */
1478 top = a->dp + a->used - 1;
1481 bottom = a->dp + a->used - 1 - b;
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.
1487 for (x = a->used - 1; x >= b; x--) {
1491 /* zero the lower digits */
1493 for (x = 0; x < b; x++) {
1501 /* returns the number of bits in an int */
1502 static int mp_count_bits (mp_int * a)
1512 /* get number of digits and add that */
1513 r = (a->used - 1) * DIGIT_BIT;
1515 /* take the last digit and count the bits in it */
1516 q = a->dp[a->used - 1];
1517 while (q > ((mp_digit) 0)) {
1519 q >>= ((mp_digit) 1);
1525 /* calc a value mod 2**b */
1526 static int mp_mod_2d (mp_int * a, int b, mp_int * c)
1530 /* if b is <= 0 then zero the int */
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);
1543 if ((res = mp_copy (a, c)) != MP_OKAY) {
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++) {
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));
1559 /* slower bit-bang division... also smaller */
1560 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d)
1562 mp_int ta, tb, tq, q;
1565 /* is divisor zero ? */
1566 if (mp_iszero (b) == 1) {
1570 /* if a < b then q=0, r = a */
1571 if (mp_cmp_mag (a, b) == MP_LT) {
1573 res = mp_copy (a, d);
1583 /* init our temps */
1584 if ((res = mp_init_multi(&ta, &tb, &tq, &q, NULL) != MP_OKAY)) {
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)) {
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)) {
1605 if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) ||
1606 ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) {
1611 /* now q == quotient and ta == remainder */
1613 n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG);
1616 c->sign = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2;
1620 d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n;
1623 mp_clear_multi(&ta, &tb, &tq, &q, NULL);
1631 #define TAB_SIZE 256
1634 static int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
1636 mp_int M[TAB_SIZE], res, mu;
1638 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
1639 int (*redux)(mp_int*,mp_int*,mp_int*);
1641 /* find window size */
1642 x = mp_count_bits (X);
1645 } else if (x <= 36) {
1647 } else if (x <= 140) {
1649 } else if (x <= 450) {
1651 } else if (x <= 1303) {
1653 } else if (x <= 3529) {
1666 /* init first cell */
1667 if ((err = mp_init(&M[1])) != MP_OKAY) {
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++) {
1682 /* create mu, used for Barrett reduction */
1683 if ((err = mp_init (&mu)) != MP_OKAY) {
1688 if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) {
1693 if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) {
1696 redux = mp_reduce_2k_l;
1701 * The M table contains powers of the base,
1702 * e.g. M[x] = G**x mod P
1704 * The first half of the table is not
1705 * computed though accept for M[0] and M[1]
1707 if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) {
1711 /* compute the value at M[1<<(winsize-1)] by squaring
1712 * M[1] (winsize-1) times
1714 if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
1718 for (x = 0; x < (winsize - 1); x++) {
1720 if ((err = mp_sqr (&M[1 << (winsize - 1)],
1721 &M[1 << (winsize - 1)])) != MP_OKAY) {
1725 /* reduce modulo P */
1726 if ((err = redux (&M[1 << (winsize - 1)], P, &mu)) != MP_OKAY) {
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)
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) {
1738 if ((err = redux (&M[x], P, &mu)) != MP_OKAY) {
1744 if ((err = mp_init (&res)) != MP_OKAY) {
1749 /* set initial mode and bit cnt */
1753 digidx = X->used - 1;
1758 /* grab next digit as required */
1759 if (--bitcnt == 0) {
1760 /* if digidx == -1 we are out of digits */
1764 /* read next digit and reset the bitcnt */
1765 buf = X->dp[digidx--];
1766 bitcnt = (int) DIGIT_BIT;
1769 /* grab the next msb from the exponent */
1770 y = (buf >> (mp_digit)(DIGIT_BIT - 1)) & 1;
1771 buf <<= (mp_digit)1;
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
1778 if (mode == 0 && y == 0) {
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) {
1787 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1793 /* else we add it to the window */
1794 bitbuf |= (y << (winsize - ++bitcpy));
1797 if (bitcpy == winsize) {
1798 /* ok window is filled so square as required and multiply */
1800 for (x = 0; x < winsize; x++) {
1801 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
1804 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1810 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
1813 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1817 /* empty window and reset */
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) {
1831 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1836 if ((bitbuf & (1 << winsize)) != 0) {
1838 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
1841 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1850 LBL_RES:mp_clear (&res);
1851 LBL_MU:mp_clear (&mu);
1854 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
1861 /* computes b = a*a */
1862 static int mp_sqr (mp_int * a, mp_int * b)
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);
1873 #ifdef BN_MP_KARATSUBA_SQR_C
1874 if (a->used >= KARATSUBA_SQR_CUTOFF) {
1875 res = mp_karatsuba_sqr (a, b);
1879 #ifdef BN_FAST_S_MP_SQR_C
1880 /* can we use the fast comba multiplier? */
1881 if ((a->used * 2 + 1) < MP_WARRAY &&
1883 (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) {
1884 res = fast_s_mp_sqr (a, b);
1887 #ifdef BN_S_MP_SQR_C
1888 res = s_mp_sqr (a, b);
1890 #error mp_sqr could fail
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.
1903 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
1908 if ((res = mp_init(&q)) != MP_OKAY) {
1912 p = mp_count_bits(n);
1914 /* q = a/2**p, a = a mod 2**p */
1915 if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
1920 if ((res = mp_mul(&q, d, &q)) != MP_OKAY) {
1925 if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
1929 if (mp_cmp_mag(a, n) != MP_LT) {
1940 /* determines the setup value */
1941 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d)
1946 if ((res = mp_init(&tmp)) != MP_OKAY) {
1950 if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
1954 if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
1964 /* computes a = 2**b
1966 * Simple algorithm which zeroes the int, grows it then just sets one bit
1969 static int mp_2expt (mp_int * a, int b)
1973 /* zero a as per default */
1976 /* grow a to accomodate the single bit */
1977 if ((res = mp_grow (a, b / DIGIT_BIT + 1)) != MP_OKAY) {
1981 /* set the used count of where the bit will go */
1982 a->used = b / DIGIT_BIT + 1;
1984 /* put the single bit in its place */
1985 a->dp[b / DIGIT_BIT] = ((mp_digit)1) << (b % DIGIT_BIT);
1991 /* pre-calculate the value required for Barrett reduction
1992 * For a given modulus "b" it calulates the value required in "a"
1994 static int mp_reduce_setup (mp_int * a, mp_int * b)
1998 if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) {
2001 return mp_div (a, b, a, NULL);
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
2009 static int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
2012 int res, um = m->used;
2015 if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
2019 /* q1 = x / b**(k-1) */
2020 mp_rshd (&q, um - 1);
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) {
2028 #ifdef BN_S_MP_MUL_HIGH_DIGS_C
2029 if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
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) {
2038 #error mp_reduce would always fail
2045 /* q3 = q2 / b**(k+1) */
2046 mp_rshd (&q, um + 1);
2048 /* x = x mod b**(k+1), quick (no division) */
2049 if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
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) {
2059 if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
2063 /* If x < 0, add b**(k+1) to it */
2064 if (mp_cmp_d (x, 0) == MP_LT) {
2066 if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) {
2069 if ((res = mp_add (x, &q, x)) != MP_OKAY) {
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) {
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.
2092 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2095 int res, pa, pb, ix, iy;
2098 mp_digit tmpx, *tmpt, *tmpy;
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);
2107 if ((res = mp_init_size (&t, digs)) != MP_OKAY) {
2112 /* compute the digits of the product directly */
2114 for (ix = 0; ix < pa; ix++) {
2115 /* set the carry to zero */
2118 /* limit ourselves to making digs digits of output */
2119 pb = MIN (b->used, digs - ix);
2121 /* setup some aliases */
2122 /* copy of the digit from a used within the nested loop */
2125 /* an alias for the destination shifted ix places */
2128 /* an alias for the digits of b */
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++) +
2138 /* the new column is the lower part of the result */
2139 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2141 /* get the carry word from the result */
2142 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2144 /* set carry if it is placed below digs */
2145 if (ix + iy < digs) {
2158 /* Fast (comba) multiplier
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.
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).
2171 * Based on Algorithm 14.12 on pp.595 of HAC.
2174 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2176 int olduse, res, pa, ix, iz;
2177 mp_digit W[MP_WARRAY];
2178 register mp_word _W;
2180 /* grow the destination as required */
2181 if (c->alloc < digs) {
2182 if ((res = mp_grow (c, digs)) != MP_OKAY) {
2187 /* number of output digits to produce */
2188 pa = MIN(digs, a->used + b->used);
2190 /* clear the carry */
2192 for (ix = 0; ix < pa; ix++) {
2195 mp_digit *tmpx, *tmpy;
2197 /* get offsets into the two bignums */
2198 ty = MIN(b->used-1, ix);
2201 /* setup temp aliases */
2205 /* this is the number of times the loop will iterrate, essentially
2206 while (tx++ < a->used && ty-- >= 0) { ... }
2208 iy = MIN(a->used-tx, ty+1);
2211 for (iz = 0; iz < iy; ++iz) {
2212 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
2217 W[ix] = ((mp_digit)_W) & MP_MASK;
2219 /* make next carry */
2220 _W = _W >> ((mp_word)DIGIT_BIT);
2228 register mp_digit *tmpc;
2230 for (ix = 0; ix < pa+1; ix++) {
2231 /* now extract the previous digit [below the carry] */
2235 /* clear unused digits [that existed in the old copy of c] */
2236 for (; ix < olduse; ix++) {
2245 /* init an mp_init for a given size */
2246 static int mp_init_size (mp_int * a, int size)
2250 /* pad size so there are always extra digits */
2251 size += (MP_PREC * 2) - (size % MP_PREC);
2254 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size);
2255 if (a->dp == NULL) {
2259 /* set the members */
2264 /* zero the digits */
2265 for (x = 0; x < size; x++) {
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)
2277 int res, ix, iy, pa;
2279 mp_digit u, tmpx, *tmpt;
2282 if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
2286 /* default used is maximum possible size */
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]);
2295 /* store lower part in result */
2296 t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
2299 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2301 /* left hand side of A[ix] * A[iy] */
2304 /* alias for where to store the results */
2305 tmpt = t.dp + (2*ix + 1);
2307 for (iy = ix + 1; iy < pa; iy++) {
2308 /* first calculate the product */
2309 r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
2311 /* now calculate the double precision result, note we use
2312 * addition instead of *2 since it's easier to optimize
2314 r = ((mp_word) *tmpt) + r + r + ((mp_word) u);
2316 /* store lower part */
2317 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2320 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
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));
2337 /* multiplies |a| * |b| and does not compute the lower digs digits
2338 * [meant to get the higher part of the product]
2340 static int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2343 int res, pa, pb, ix, iy;
2346 mp_digit tmpx, *tmpt, *tmpy;
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);
2356 if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) {
2359 t.used = a->used + b->used + 1;
2363 for (ix = 0; ix < pa; ix++) {
2364 /* clear the carry */
2367 /* left hand side of A[ix] * B[iy] */
2370 /* alias to the address of where the digits will be stored */
2371 tmpt = &(t.dp[digs]);
2373 /* alias for where to read the right hand side from */
2374 tmpy = b->dp + (digs - ix);
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++) +
2382 /* get the lower part */
2383 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2385 /* carry the carry */
2386 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2397 #ifdef BN_MP_MONTGOMERY_SETUP_C
2398 /* setups the montgomery reduction stuff */
2400 mp_montgomery_setup (mp_int * n, mp_digit * rho)
2404 /* fast inversion mod 2**k
2406 * Based on the fact that
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
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 */
2423 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
2424 x *= 2 - b * x; /* here x*a==1 mod 2**32 */
2427 x *= 2 - b * x; /* here x*a==1 mod 2**64 */
2430 /* rho = -1/m mod b */
2431 *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK;
2438 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2439 /* computes xR**-1 == x (mod N) via Montgomery Reduction
2441 * This is an optimized implementation of montgomery_reduce
2442 * which uses the comba method to quickly calculate the columns of the
2445 * Based on Algorithm 14.32 on pp.601 of HAC.
2447 int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
2449 int ix, res, olduse;
2450 mp_word W[MP_WARRAY];
2452 /* get old used count */
2455 /* grow a as required */
2456 if (x->alloc < n->used + 1) {
2457 if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) {
2462 /* first we have to get the digits of the input into
2463 * an array of double precision words W[...]
2466 register mp_word *_W;
2467 register mp_digit *tmpx;
2469 /* alias for the W[] array */
2472 /* alias for the digits of x*/
2475 /* copy the digits of a into W[0..a->used-1] */
2476 for (ix = 0; ix < x->used; ix++) {
2480 /* zero the high words of W[a->used..m->used*2] */
2481 for (; ix < n->used * 2 + 1; ix++) {
2486 /* now we proceed to zero successive digits
2487 * from the least significant upwards
2489 for (ix = 0; ix < n->used; ix++) {
2490 /* mu = ai * m' mod b
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)
2496 register mp_digit mu;
2497 mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK);
2499 /* a = a + mu * m * b**i
2501 * This is computed in place and on the fly. The multiplication
2502 * by b**i is handled by offseting which columns the results
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
2515 register mp_digit *tmpn;
2516 register mp_word *_W;
2518 /* alias for the digits of the modulus */
2521 /* Alias for the columns set by an offset of ix */
2525 for (iy = 0; iy < n->used; iy++) {
2526 *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++);
2530 /* now fix carry for next digit, W[ix+1] */
2531 W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT);
2534 /* now we have to propagate the carries and
2535 * shift the words downward [all those least
2536 * significant digits we zeroed].
2539 register mp_digit *tmpx;
2540 register mp_word *_W, *_W1;
2542 /* nox fix rest of carries */
2544 /* alias for current word */
2547 /* alias for next word, where the carry goes */
2550 for (; ix <= n->used * 2 + 1; ix++) {
2551 *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT);
2554 /* copy out, A = A/b**n
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
2561 /* alias for destination word */
2564 /* alias for shifted double precision result */
2567 for (ix = 0; ix < n->used + 1; ix++) {
2568 *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK));
2571 /* zero oldused digits, if the input a was larger than
2572 * m->used+1 we'll have to clear the digits
2574 for (; ix < olduse; ix++) {
2579 /* set the max used and clamp */
2580 x->used = n->used + 1;
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);
2592 #ifdef BN_MP_MUL_2_C
2594 static int mp_mul_2(mp_int * a, mp_int * b)
2596 int x, res, oldused;
2598 /* grow to accomodate result */
2599 if (b->alloc < a->used + 1) {
2600 if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) {
2609 register mp_digit r, rr, *tmpa, *tmpb;
2611 /* alias for source */
2614 /* alias for dest */
2619 for (x = 0; x < a->used; x++) {
2621 /* get what will be the *next* carry bit from the
2622 * MSB of the current digit
2624 rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1));
2626 /* now shift up this digit, add in the carry [from the previous] */
2627 *tmpb++ = ((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK;
2629 /* copy the carry that would be from the source
2630 * digit into the next iteration
2635 /* new leading digit? */
2637 /* add a MSB which is always 1 at this point */
2642 /* now zero any excess digits on the destination
2643 * that we didn't write to
2645 tmpb = b->dp + b->used;
2646 for (x = b->used; x < oldused; x++) {
2656 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
2658 * shifts with subtractions when the result is greater than b.
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.
2663 static int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
2667 /* how many bits of last digit does b use */
2668 bits = mp_count_bits (b) % DIGIT_BIT;
2671 if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) {
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) {
2685 if (mp_cmp_mag (a, b) != MP_LT) {
2686 if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
2697 #ifdef BN_MP_EXPTMOD_FAST_C
2698 /* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
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.
2703 * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
2706 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
2708 mp_int M[TAB_SIZE], res;
2710 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
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.
2716 int (*redux)(mp_int*,mp_int*,mp_digit);
2718 /* find window size */
2719 x = mp_count_bits (X);
2722 } else if (x <= 36) {
2724 } else if (x <= 140) {
2726 } else if (x <= 450) {
2728 } else if (x <= 1303) {
2730 } else if (x <= 3529) {
2743 /* init first cell */
2744 if ((err = mp_init(&M[1])) != MP_OKAY) {
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++) {
2759 /* determine and setup reduction code */
2761 #ifdef BN_MP_MONTGOMERY_SETUP_C
2762 /* now setup montgomery */
2763 if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
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;
2779 #ifdef BN_MP_MONTGOMERY_REDUCE_C
2780 /* use slower baseline Montgomery method */
2781 redux = mp_montgomery_reduce;
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;
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) {
2802 redux = mp_reduce_2k;
2810 if ((err = mp_init (&res)) != MP_OKAY) {
2818 * The first half of the table is not computed though accept for M[0] and M[1]
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) {
2832 /* now set M[1] to G * R mod m */
2833 if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
2838 if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
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) {
2848 for (x = 0; x < (winsize - 1); x++) {
2849 if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) {
2852 if ((err = redux (&M[1 << (winsize - 1)], P, mp)) != MP_OKAY) {
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) {
2862 if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
2867 /* set initial mode and bit cnt */
2871 digidx = X->used - 1;
2876 /* grab next digit as required */
2877 if (--bitcnt == 0) {
2878 /* if digidx == -1 we are out of digits so break */
2882 /* read next digit and reset bitcnt */
2883 buf = X->dp[digidx--];
2884 bitcnt = (int)DIGIT_BIT;
2887 /* grab the next msb from the exponent */
2888 y = (mp_digit)(buf >> (DIGIT_BIT - 1)) & 1;
2889 buf <<= (mp_digit)1;
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
2896 if (mode == 0 && y == 0) {
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) {
2905 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2911 /* else we add it to the window */
2912 bitbuf |= (y << (winsize - ++bitcpy));
2915 if (bitcpy == winsize) {
2916 /* ok window is filled so square as required and multiply */
2918 for (x = 0; x < winsize; x++) {
2919 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2922 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2928 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
2931 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2935 /* empty window and reset */
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) {
2949 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2953 /* get next bit of the window */
2955 if ((bitbuf & (1 << winsize)) != 0) {
2957 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
2960 if ((err = redux (&res, P, mp)) != MP_OKAY) {
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
2974 if ((err = redux(&res, P, mp)) != MP_OKAY) {
2979 /* swap res with Y */
2982 LBL_RES:mp_clear (&res);
2985 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {