2 * Minimal code for RSA support from LibTomMath 0.41
4 * http://libtom.org/files/ltm-0.41.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 */
32 /* Use faster div at the cost of about 1 kB */
35 /* Include faster exptmod (Montgomery) at the cost of about 2.5 kB in code */
36 #define BN_MP_EXPTMOD_FAST_C
37 #define BN_MP_MONTGOMERY_SETUP_C
38 #define BN_FAST_MP_MONTGOMERY_REDUCE_C
39 #define BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
42 /* Include faster sqr at the cost of about 0.5 kB in code */
43 #define BN_FAST_S_MP_SQR_C
47 #define BN_MP_DIV_SMALL
48 #define BN_MP_INIT_MULTI_C
49 #define BN_MP_CLEAR_MULTI_C
53 /* Current uses do not require support for negative exponent in exptmod, so we
54 * can save about 1.5 kB in leaving out invmod. */
55 #define LTM_NO_NEG_EXP
60 #define MIN(x,y) ((x)<(y)?(x):(y))
64 #define MAX(x,y) ((x)>(y)?(x):(y))
70 typedef unsigned long mp_digit;
71 typedef unsigned long mp_word __attribute__((mode(TI)));
76 typedef unsigned long mp_digit;
84 #define XMALLOC os_malloc
86 #define XREALLOC os_realloc
89 #define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))
91 #define MP_LT -1 /* less than */
92 #define MP_EQ 0 /* equal to */
93 #define MP_GT 1 /* greater than */
95 #define MP_ZPOS 0 /* positive integer */
96 #define MP_NEG 1 /* negative */
98 #define MP_OKAY 0 /* ok result */
99 #define MP_MEM -2 /* out of mem */
100 #define MP_VAL -3 /* invalid input */
102 #define MP_YES 1 /* yes response */
103 #define MP_NO 0 /* no response */
107 /* define this to use lower memory usage routines (exptmods mostly) */
110 /* default precision */
113 #define MP_PREC 32 /* default digits of precision */
115 #define MP_PREC 8 /* default digits of precision */
119 /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
120 #define MP_WARRAY (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1))
122 /* the infamous mp_int structure */
124 int used, alloc, sign;
129 /* ---> Basic Manipulations <--- */
130 #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
131 #define mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO)
132 #define mp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO)
135 /* prototypes for copied functions */
136 #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
137 static int s_mp_exptmod(mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode);
138 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
139 static int s_mp_sqr(mp_int * a, mp_int * b);
140 static int s_mp_mul_high_digs(mp_int * a, mp_int * b, mp_int * c, int digs);
142 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
144 #ifdef BN_MP_INIT_MULTI_C
145 static int mp_init_multi(mp_int *mp, ...);
147 #ifdef BN_MP_CLEAR_MULTI_C
148 static void mp_clear_multi(mp_int *mp, ...);
150 static int mp_lshd(mp_int * a, int b);
151 static void mp_set(mp_int * a, mp_digit b);
152 static void mp_clamp(mp_int * a);
153 static void mp_exch(mp_int * a, mp_int * b);
154 static void mp_rshd(mp_int * a, int b);
155 static void mp_zero(mp_int * a);
156 static int mp_mod_2d(mp_int * a, int b, mp_int * c);
157 static int mp_div_2d(mp_int * a, int b, mp_int * c, mp_int * d);
158 static int mp_init_copy(mp_int * a, mp_int * b);
159 static int mp_mul_2d(mp_int * a, int b, mp_int * c);
160 #ifndef LTM_NO_NEG_EXP
161 static int mp_div_2(mp_int * a, mp_int * b);
162 static int mp_invmod(mp_int * a, mp_int * b, mp_int * c);
163 static int mp_invmod_slow(mp_int * a, mp_int * b, mp_int * c);
164 #endif /* LTM_NO_NEG_EXP */
165 static int mp_copy(mp_int * a, mp_int * b);
166 static int mp_count_bits(mp_int * a);
167 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d);
168 static int mp_mod(mp_int * a, mp_int * b, mp_int * c);
169 static int mp_grow(mp_int * a, int size);
170 static int mp_cmp_mag(mp_int * a, mp_int * b);
172 static int mp_abs(mp_int * a, mp_int * b);
174 static int mp_sqr(mp_int * a, mp_int * b);
175 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d);
176 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d);
177 static int mp_2expt(mp_int * a, int b);
178 static int mp_reduce_setup(mp_int * a, mp_int * b);
179 static int mp_reduce(mp_int * x, mp_int * m, mp_int * mu);
180 static int mp_init_size(mp_int * a, int size);
181 #ifdef BN_MP_EXPTMOD_FAST_C
182 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode);
183 #endif /* BN_MP_EXPTMOD_FAST_C */
184 #ifdef BN_FAST_S_MP_SQR_C
185 static int fast_s_mp_sqr (mp_int * a, mp_int * b);
186 #endif /* BN_FAST_S_MP_SQR_C */
188 static int mp_mul_d (mp_int * a, mp_digit b, mp_int * c);
189 #endif /* BN_MP_MUL_D_C */
193 /* functions from bn_<func name>.c */
196 /* reverse an array, used for radix code */
197 static void bn_reverse (unsigned char *s, int len)
214 /* low level addition, based on HAC pp.594, Algorithm 14.7 */
215 static int s_mp_add (mp_int * a, mp_int * b, mp_int * c)
218 int olduse, res, min, max;
220 /* find sizes, we let |a| <= |b| which means we have to sort
221 * them. "x" will point to the input with the most digits
223 if (a->used > b->used) {
234 if (c->alloc < max + 1) {
235 if ((res = mp_grow (c, max + 1)) != MP_OKAY) {
240 /* get old used digit count and set new one */
245 register mp_digit u, *tmpa, *tmpb, *tmpc;
248 /* alias for digit pointers */
261 for (i = 0; i < min; i++) {
262 /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
263 *tmpc = *tmpa++ + *tmpb++ + u;
265 /* U = carry bit of T[i] */
266 u = *tmpc >> ((mp_digit)DIGIT_BIT);
268 /* take away carry bit from T[i] */
272 /* now copy higher words if any, that is in A+B
273 * if A or B has more digits add those in
276 for (; i < max; i++) {
277 /* T[i] = X[i] + U */
278 *tmpc = x->dp[i] + u;
280 /* U = carry bit of T[i] */
281 u = *tmpc >> ((mp_digit)DIGIT_BIT);
283 /* take away carry bit from T[i] */
291 /* clear digits above oldused */
292 for (i = c->used; i < olduse; i++) {
302 /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
303 static int s_mp_sub (mp_int * a, mp_int * b, mp_int * c)
305 int olduse, res, min, max;
312 if (c->alloc < max) {
313 if ((res = mp_grow (c, max)) != MP_OKAY) {
321 register mp_digit u, *tmpa, *tmpb, *tmpc;
324 /* alias for digit pointers */
329 /* set carry to zero */
331 for (i = 0; i < min; i++) {
332 /* T[i] = A[i] - B[i] - U */
333 *tmpc = *tmpa++ - *tmpb++ - u;
335 /* U = carry bit of T[i]
336 * Note this saves performing an AND operation since
337 * if a carry does occur it will propagate all the way to the
338 * MSB. As a result a single shift is enough to get the carry
340 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
342 /* Clear carry from T[i] */
346 /* now copy higher words if any, e.g. if A has more digits than B */
347 for (; i < max; i++) {
348 /* T[i] = A[i] - U */
351 /* U = carry bit of T[i] */
352 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
354 /* Clear carry from T[i] */
358 /* clear digits above used (since we may not have grown result above) */
359 for (i = c->used; i < olduse; i++) {
369 /* init a new mp_int */
370 static int mp_init (mp_int * a)
374 /* allocate memory required and clear it */
375 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * MP_PREC);
380 /* set the digits to zero */
381 for (i = 0; i < MP_PREC; i++) {
385 /* set the used to zero, allocated digits to the default precision
386 * and sign to positive */
395 /* clear one (frees) */
396 static void mp_clear (mp_int * a)
400 /* only do anything if a hasn't been freed previously */
402 /* first zero the digits */
403 for (i = 0; i < a->used; i++) {
410 /* reset members to make debugging easier */
412 a->alloc = a->used = 0;
418 /* high level addition (handles signs) */
419 static int mp_add (mp_int * a, mp_int * b, mp_int * c)
423 /* get sign of both inputs */
427 /* handle two cases, not four */
429 /* both positive or both negative */
430 /* add their magnitudes, copy the sign */
432 res = s_mp_add (a, b, c);
434 /* one positive, the other negative */
435 /* subtract the one with the greater magnitude from */
436 /* the one of the lesser magnitude. The result gets */
437 /* the sign of the one with the greater magnitude. */
438 if (mp_cmp_mag (a, b) == MP_LT) {
440 res = s_mp_sub (b, a, c);
443 res = s_mp_sub (a, b, c);
450 /* high level subtraction (handles signs) */
451 static int mp_sub (mp_int * a, mp_int * b, mp_int * c)
459 /* subtract a negative from a positive, OR */
460 /* subtract a positive from a negative. */
461 /* In either case, ADD their magnitudes, */
462 /* and use the sign of the first number. */
464 res = s_mp_add (a, b, c);
466 /* subtract a positive from a positive, OR */
467 /* subtract a negative from a negative. */
468 /* First, take the difference between their */
469 /* magnitudes, then... */
470 if (mp_cmp_mag (a, b) != MP_LT) {
471 /* Copy the sign from the first */
473 /* The first has a larger or equal magnitude */
474 res = s_mp_sub (a, b, c);
476 /* The result has the *opposite* sign from */
477 /* the first number. */
478 c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
479 /* The second has a larger magnitude */
480 res = s_mp_sub (b, a, c);
487 /* high level multiplication (handles sign) */
488 static int mp_mul (mp_int * a, mp_int * b, mp_int * c)
491 neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
494 #ifdef BN_MP_TOOM_MUL_C
495 if (MIN (a->used, b->used) >= TOOM_MUL_CUTOFF) {
496 res = mp_toom_mul(a, b, c);
499 #ifdef BN_MP_KARATSUBA_MUL_C
501 if (MIN (a->used, b->used) >= KARATSUBA_MUL_CUTOFF) {
502 res = mp_karatsuba_mul (a, b, c);
506 /* can we use the fast multiplier?
508 * The fast multiplier can be used if the output will
509 * have less than MP_WARRAY digits and the number of
510 * digits won't affect carry propagation
512 #ifdef BN_FAST_S_MP_MUL_DIGS_C
513 int digs = a->used + b->used + 1;
515 if ((digs < MP_WARRAY) &&
516 MIN(a->used, b->used) <=
517 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
518 res = fast_s_mp_mul_digs (a, b, c, digs);
521 #ifdef BN_S_MP_MUL_DIGS_C
522 res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */
524 #error mp_mul could fail
529 c->sign = (c->used > 0) ? neg : MP_ZPOS;
534 /* d = a * b (mod c) */
535 static int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
540 if ((res = mp_init (&t)) != MP_OKAY) {
544 if ((res = mp_mul (a, b, &t)) != MP_OKAY) {
548 res = mp_mod (&t, c, d);
554 /* c = a mod b, 0 <= c < b */
555 static int mp_mod (mp_int * a, mp_int * b, mp_int * c)
560 if ((res = mp_init (&t)) != MP_OKAY) {
564 if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) {
569 if (t.sign != b->sign) {
570 res = mp_add (b, &t, c);
581 /* this is a shell function that calls either the normal or Montgomery
582 * exptmod functions. Originally the call to the montgomery code was
583 * embedded in the normal function but that wasted a lot of stack space
584 * for nothing (since 99% of the time the Montgomery code would be called)
586 static int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
590 /* modulus P must be positive */
591 if (P->sign == MP_NEG) {
595 /* if exponent X is negative we have to recurse */
596 if (X->sign == MP_NEG) {
597 #ifdef LTM_NO_NEG_EXP
599 #else /* LTM_NO_NEG_EXP */
600 #ifdef BN_MP_INVMOD_C
604 /* first compute 1/G mod P */
605 if ((err = mp_init(&tmpG)) != MP_OKAY) {
608 if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
614 if ((err = mp_init(&tmpX)) != MP_OKAY) {
618 if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
619 mp_clear_multi(&tmpG, &tmpX, NULL);
623 /* and now compute (1/G)**|X| instead of G**X [X < 0] */
624 err = mp_exptmod(&tmpG, &tmpX, P, Y);
625 mp_clear_multi(&tmpG, &tmpX, NULL);
628 #error mp_exptmod would always fail
632 #endif /* LTM_NO_NEG_EXP */
635 /* modified diminished radix reduction */
636 #if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && defined(BN_S_MP_EXPTMOD_C)
637 if (mp_reduce_is_2k_l(P) == MP_YES) {
638 return s_mp_exptmod(G, X, P, Y, 1);
642 #ifdef BN_MP_DR_IS_MODULUS_C
643 /* is it a DR modulus? */
644 dr = mp_dr_is_modulus(P);
650 #ifdef BN_MP_REDUCE_IS_2K_C
651 /* if not, is it a unrestricted DR modulus? */
653 dr = mp_reduce_is_2k(P) << 1;
657 /* if the modulus is odd or dr != 0 use the montgomery method */
658 #ifdef BN_MP_EXPTMOD_FAST_C
659 if (mp_isodd (P) == 1 || dr != 0) {
660 return mp_exptmod_fast (G, X, P, Y, dr);
663 #ifdef BN_S_MP_EXPTMOD_C
664 /* otherwise use the generic Barrett reduction technique */
665 return s_mp_exptmod (G, X, P, Y, 0);
667 #error mp_exptmod could fail
668 /* no exptmod for evens */
671 #ifdef BN_MP_EXPTMOD_FAST_C
677 /* compare two ints (signed)*/
678 static int mp_cmp (mp_int * a, mp_int * b)
680 /* compare based on sign */
681 if (a->sign != b->sign) {
682 if (a->sign == MP_NEG) {
690 if (a->sign == MP_NEG) {
691 /* if negative compare opposite direction */
692 return mp_cmp_mag(b, a);
694 return mp_cmp_mag(a, b);
699 /* compare a digit */
700 static int mp_cmp_d(mp_int * a, mp_digit b)
702 /* compare based on sign */
703 if (a->sign == MP_NEG) {
707 /* compare based on magnitude */
712 /* compare the only digit of a to b */
715 } else if (a->dp[0] < b) {
723 #ifndef LTM_NO_NEG_EXP
724 /* hac 14.61, pp608 */
725 static int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
727 /* b cannot be negative */
728 if (b->sign == MP_NEG || mp_iszero(b) == 1) {
732 #ifdef BN_FAST_MP_INVMOD_C
733 /* if the modulus is odd we can use a faster routine instead */
734 if (mp_isodd (b) == 1) {
735 return fast_mp_invmod (a, b, c);
739 #ifdef BN_MP_INVMOD_SLOW_C
740 return mp_invmod_slow(a, b, c);
743 #ifndef BN_FAST_MP_INVMOD_C
744 #ifndef BN_MP_INVMOD_SLOW_C
745 #error mp_invmod would always fail
750 #endif /* LTM_NO_NEG_EXP */
753 /* get the size for an unsigned equivalent */
754 static int mp_unsigned_bin_size (mp_int * a)
756 int size = mp_count_bits (a);
757 return (size / 8 + ((size & 7) != 0 ? 1 : 0));
761 #ifndef LTM_NO_NEG_EXP
762 /* hac 14.61, pp608 */
763 static int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c)
765 mp_int x, y, u, v, A, B, C, D;
768 /* b cannot be negative */
769 if (b->sign == MP_NEG || mp_iszero(b) == 1) {
774 if ((res = mp_init_multi(&x, &y, &u, &v,
775 &A, &B, &C, &D, NULL)) != MP_OKAY) {
780 if ((res = mp_mod(a, b, &x)) != MP_OKAY) {
783 if ((res = mp_copy (b, &y)) != MP_OKAY) {
787 /* 2. [modified] if x,y are both even then return an error! */
788 if (mp_iseven (&x) == 1 && mp_iseven (&y) == 1) {
793 /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
794 if ((res = mp_copy (&x, &u)) != MP_OKAY) {
797 if ((res = mp_copy (&y, &v)) != MP_OKAY) {
804 /* 4. while u is even do */
805 while (mp_iseven (&u) == 1) {
807 if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
810 /* 4.2 if A or B is odd then */
811 if (mp_isodd (&A) == 1 || mp_isodd (&B) == 1) {
812 /* A = (A+y)/2, B = (B-x)/2 */
813 if ((res = mp_add (&A, &y, &A)) != MP_OKAY) {
816 if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
820 /* A = A/2, B = B/2 */
821 if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
824 if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
829 /* 5. while v is even do */
830 while (mp_iseven (&v) == 1) {
832 if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
835 /* 5.2 if C or D is odd then */
836 if (mp_isodd (&C) == 1 || mp_isodd (&D) == 1) {
837 /* C = (C+y)/2, D = (D-x)/2 */
838 if ((res = mp_add (&C, &y, &C)) != MP_OKAY) {
841 if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
845 /* C = C/2, D = D/2 */
846 if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
849 if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
854 /* 6. if u >= v then */
855 if (mp_cmp (&u, &v) != MP_LT) {
856 /* u = u - v, A = A - C, B = B - D */
857 if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
861 if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
865 if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
869 /* v - v - u, C = C - A, D = D - B */
870 if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
874 if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
878 if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
883 /* if not zero goto step 4 */
884 if (mp_iszero (&u) == 0)
887 /* now a = C, b = D, gcd == g*v */
889 /* if v != 1 then there is no inverse */
890 if (mp_cmp_d (&v, 1) != MP_EQ) {
896 while (mp_cmp_d(&C, 0) == MP_LT) {
897 if ((res = mp_add(&C, b, &C)) != MP_OKAY) {
903 while (mp_cmp_mag(&C, b) != MP_LT) {
904 if ((res = mp_sub(&C, b, &C)) != MP_OKAY) {
909 /* C is now the inverse */
912 LBL_ERR:mp_clear_multi (&x, &y, &u, &v, &A, &B, &C, &D, NULL);
915 #endif /* LTM_NO_NEG_EXP */
918 /* compare maginitude of two ints (unsigned) */
919 static int mp_cmp_mag (mp_int * a, mp_int * b)
922 mp_digit *tmpa, *tmpb;
924 /* compare based on # of non-zero digits */
925 if (a->used > b->used) {
929 if (a->used < b->used) {
934 tmpa = a->dp + (a->used - 1);
937 tmpb = b->dp + (a->used - 1);
939 /* compare based on digits */
940 for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
953 /* reads a unsigned char array, assumes the msb is stored first [big endian] */
954 static int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
958 /* make sure there are at least two digits */
960 if ((res = mp_grow(a, 2)) != MP_OKAY) {
968 /* read the bytes in */
970 if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) {
978 a->dp[0] = (*b & MP_MASK);
979 a->dp[1] |= ((*b++ >> 7U) & 1);
988 /* store in unsigned [big endian] format */
989 static int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
994 if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
999 while (mp_iszero (&t) == 0) {
1001 b[x++] = (unsigned char) (t.dp[0] & 255);
1003 b[x++] = (unsigned char) (t.dp[0] | ((t.dp[1] & 0x01) << 7));
1005 if ((res = mp_div_2d (&t, 8, &t, NULL)) != MP_OKAY) {
1016 /* shift right by a certain bit count (store quotient in c, optional remainder in d) */
1017 static int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
1024 /* if the shift count is <= 0 then we do no work */
1026 res = mp_copy (a, c);
1033 if ((res = mp_init (&t)) != MP_OKAY) {
1037 /* get the remainder */
1039 if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
1046 if ((res = mp_copy (a, c)) != MP_OKAY) {
1051 /* shift by as many digits in the bit count */
1052 if (b >= (int)DIGIT_BIT) {
1053 mp_rshd (c, b / DIGIT_BIT);
1056 /* shift any bit count < DIGIT_BIT */
1057 D = (mp_digit) (b % DIGIT_BIT);
1059 register mp_digit *tmpc, mask, shift;
1062 mask = (((mp_digit)1) << D) - 1;
1065 shift = DIGIT_BIT - D;
1068 tmpc = c->dp + (c->used - 1);
1072 for (x = c->used - 1; x >= 0; x--) {
1073 /* get the lower bits of this word in a temp */
1076 /* shift the current word and mix in the carry bits from the previous word */
1077 *tmpc = (*tmpc >> D) | (r << shift);
1080 /* set the carry to the carry bits of the current word found above */
1093 static int mp_init_copy (mp_int * a, mp_int * b)
1097 if ((res = mp_init (a)) != MP_OKAY) {
1100 return mp_copy (b, a);
1105 static void mp_zero (mp_int * a)
1114 for (n = 0; n < a->alloc; n++) {
1121 static int mp_copy (mp_int * a, mp_int * b)
1125 /* if dst == src do nothing */
1131 if (b->alloc < a->used) {
1132 if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1137 /* zero b and copy the parameters over */
1139 register mp_digit *tmpa, *tmpb;
1141 /* pointer aliases */
1149 /* copy all the digits */
1150 for (n = 0; n < a->used; n++) {
1154 /* clear high digits */
1155 for (; n < b->used; n++) {
1160 /* copy used count and sign */
1167 /* shift right a certain amount of digits */
1168 static void mp_rshd (mp_int * a, int b)
1172 /* if b <= 0 then ignore it */
1177 /* if b > used then simply zero it and return */
1184 register mp_digit *bottom, *top;
1186 /* shift the digits down */
1191 /* top [offset into digits] */
1194 /* this is implemented as a sliding window where
1195 * the window is b-digits long and digits from
1196 * the top of the window are copied to the bottom
1200 b-2 | b-1 | b0 | b1 | b2 | ... | bb | ---->
1202 \-------------------/ ---->
1204 for (x = 0; x < (a->used - b); x++) {
1208 /* zero the top digits */
1209 for (; x < a->used; x++) {
1214 /* remove excess digits */
1219 /* swap the elements of two integers, for cases where you can't simply swap the
1220 * mp_int pointers around
1222 static void mp_exch (mp_int * a, mp_int * b)
1232 /* trim unused digits
1234 * This is used to ensure that leading zero digits are
1235 * trimed and the leading "used" digit will be non-zero
1236 * Typically very fast. Also fixes the sign if there
1237 * are no more leading digits
1239 static void mp_clamp (mp_int * a)
1241 /* decrease used while the most significant digit is
1244 while (a->used > 0 && a->dp[a->used - 1] == 0) {
1248 /* reset the sign flag if used == 0 */
1255 /* grow as required */
1256 static int mp_grow (mp_int * a, int size)
1261 /* if the alloc size is smaller alloc more ram */
1262 if (a->alloc < size) {
1263 /* ensure there are always at least MP_PREC digits extra on top */
1264 size += (MP_PREC * 2) - (size % MP_PREC);
1266 /* reallocate the array a->dp
1268 * We store the return in a temporary variable
1269 * in case the operation failed we don't want
1270 * to overwrite the dp member of a.
1272 tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size);
1274 /* reallocation failed but "a" is still valid [can be freed] */
1278 /* reallocation succeeded so set a->dp */
1281 /* zero excess digits */
1284 for (; i < a->alloc; i++) {
1295 * Simple function copies the input and fixes the sign to positive
1297 static int mp_abs (mp_int * a, mp_int * b)
1303 if ((res = mp_copy (a, b)) != MP_OKAY) {
1308 /* force the sign of b to positive */
1316 /* set to a digit */
1317 static void mp_set (mp_int * a, mp_digit b)
1320 a->dp[0] = b & MP_MASK;
1321 a->used = (a->dp[0] != 0) ? 1 : 0;
1325 #ifndef LTM_NO_NEG_EXP
1327 static int mp_div_2(mp_int * a, mp_int * b)
1329 int x, res, oldused;
1332 if (b->alloc < a->used) {
1333 if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1341 register mp_digit r, rr, *tmpa, *tmpb;
1344 tmpa = a->dp + b->used - 1;
1347 tmpb = b->dp + b->used - 1;
1351 for (x = b->used - 1; x >= 0; x--) {
1352 /* get the carry for the next iteration */
1355 /* shift the current digit, add in carry and store */
1356 *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
1358 /* forward carry to next iteration */
1362 /* zero excess digits */
1363 tmpb = b->dp + b->used;
1364 for (x = b->used; x < oldused; x++) {
1372 #endif /* LTM_NO_NEG_EXP */
1375 /* shift left by a certain bit count */
1376 static int mp_mul_2d (mp_int * a, int b, mp_int * c)
1383 if ((res = mp_copy (a, c)) != MP_OKAY) {
1388 if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) {
1389 if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) {
1394 /* shift by as many digits in the bit count */
1395 if (b >= (int)DIGIT_BIT) {
1396 if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) {
1401 /* shift any bit count < DIGIT_BIT */
1402 d = (mp_digit) (b % DIGIT_BIT);
1404 register mp_digit *tmpc, shift, mask, r, rr;
1407 /* bitmask for carries */
1408 mask = (((mp_digit)1) << d) - 1;
1410 /* shift for msbs */
1411 shift = DIGIT_BIT - d;
1418 for (x = 0; x < c->used; x++) {
1419 /* get the higher bits of the current word */
1420 rr = (*tmpc >> shift) & mask;
1422 /* shift the current word and OR in the carry */
1423 *tmpc = ((*tmpc << d) | r) & MP_MASK;
1426 /* set the carry to the carry bits of the current word */
1430 /* set final carry */
1432 c->dp[(c->used)++] = r;
1440 #ifdef BN_MP_INIT_MULTI_C
1441 static int mp_init_multi(mp_int *mp, ...)
1443 mp_err res = MP_OKAY; /* Assume ok until proven otherwise */
1444 int n = 0; /* Number of ok inits */
1445 mp_int* cur_arg = mp;
1448 va_start(args, mp); /* init args to next argument from caller */
1449 while (cur_arg != NULL) {
1450 if (mp_init(cur_arg) != MP_OKAY) {
1451 /* Oops - error! Back-track and mp_clear what we already
1452 succeeded in init-ing, then return error.
1456 /* end the current list */
1459 /* now start cleaning up */
1461 va_start(clean_args, mp);
1464 cur_arg = va_arg(clean_args, mp_int*);
1471 cur_arg = va_arg(args, mp_int*);
1474 return res; /* Assumed ok, if error flagged above. */
1479 #ifdef BN_MP_CLEAR_MULTI_C
1480 static void mp_clear_multi(mp_int *mp, ...)
1482 mp_int* next_mp = mp;
1485 while (next_mp != NULL) {
1487 next_mp = va_arg(args, mp_int*);
1494 /* shift left a certain amount of digits */
1495 static int mp_lshd (mp_int * a, int b)
1499 /* if its less than zero return */
1504 /* grow to fit the new digits */
1505 if (a->alloc < a->used + b) {
1506 if ((res = mp_grow (a, a->used + b)) != MP_OKAY) {
1512 register mp_digit *top, *bottom;
1514 /* increment the used by the shift amount then copy upwards */
1518 top = a->dp + a->used - 1;
1521 bottom = a->dp + a->used - 1 - b;
1523 /* much like mp_rshd this is implemented using a sliding window
1524 * except the window goes the otherway around. Copying from
1525 * the bottom to the top. see bn_mp_rshd.c for more info.
1527 for (x = a->used - 1; x >= b; x--) {
1531 /* zero the lower digits */
1533 for (x = 0; x < b; x++) {
1541 /* returns the number of bits in an int */
1542 static int mp_count_bits (mp_int * a)
1552 /* get number of digits and add that */
1553 r = (a->used - 1) * DIGIT_BIT;
1555 /* take the last digit and count the bits in it */
1556 q = a->dp[a->used - 1];
1557 while (q > ((mp_digit) 0)) {
1559 q >>= ((mp_digit) 1);
1565 /* calc a value mod 2**b */
1566 static int mp_mod_2d (mp_int * a, int b, mp_int * c)
1570 /* if b is <= 0 then zero the int */
1576 /* if the modulus is larger than the value than return */
1577 if (b >= (int) (a->used * DIGIT_BIT)) {
1578 res = mp_copy (a, c);
1583 if ((res = mp_copy (a, c)) != MP_OKAY) {
1587 /* zero digits above the last digit of the modulus */
1588 for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x++) {
1591 /* clear the digit that is not completely outside/inside the modulus */
1592 c->dp[b / DIGIT_BIT] &=
1593 (mp_digit) ((((mp_digit) 1) << (((mp_digit) b) % DIGIT_BIT)) - ((mp_digit) 1));
1599 #ifdef BN_MP_DIV_SMALL
1601 /* slower bit-bang division... also smaller */
1602 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d)
1604 mp_int ta, tb, tq, q;
1607 /* is divisor zero ? */
1608 if (mp_iszero (b) == 1) {
1612 /* if a < b then q=0, r = a */
1613 if (mp_cmp_mag (a, b) == MP_LT) {
1615 res = mp_copy (a, d);
1625 /* init our temps */
1626 if ((res = mp_init_multi(&ta, &tb, &tq, &q, NULL) != MP_OKAY)) {
1632 n = mp_count_bits(a) - mp_count_bits(b);
1633 if (((res = mp_abs(a, &ta)) != MP_OKAY) ||
1634 ((res = mp_abs(b, &tb)) != MP_OKAY) ||
1635 ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) ||
1636 ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) {
1641 if (mp_cmp(&tb, &ta) != MP_GT) {
1642 if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) ||
1643 ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) {
1647 if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) ||
1648 ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) {
1653 /* now q == quotient and ta == remainder */
1655 n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG);
1658 c->sign = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2;
1662 d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n;
1665 mp_clear_multi(&ta, &tb, &tq, &q, NULL);
1671 /* integer signed division.
1672 * c*b + d == a [e.g. a/b, c=quotient, d=remainder]
1673 * HAC pp.598 Algorithm 14.20
1675 * Note that the description in HAC is horribly
1676 * incomplete. For example, it doesn't consider
1677 * the case where digits are removed from 'x' in
1678 * the inner loop. It also doesn't consider the
1679 * case that y has fewer than three digits, etc..
1681 * The overall algorithm is as described as
1682 * 14.20 from HAC but fixed to treat these cases.
1684 static int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
1686 mp_int q, x, y, t1, t2;
1687 int res, n, t, i, norm, neg;
1689 /* is divisor zero ? */
1690 if (mp_iszero (b) == 1) {
1694 /* if a < b then q=0, r = a */
1695 if (mp_cmp_mag (a, b) == MP_LT) {
1697 res = mp_copy (a, d);
1707 if ((res = mp_init_size (&q, a->used + 2)) != MP_OKAY) {
1710 q.used = a->used + 2;
1712 if ((res = mp_init (&t1)) != MP_OKAY) {
1716 if ((res = mp_init (&t2)) != MP_OKAY) {
1720 if ((res = mp_init_copy (&x, a)) != MP_OKAY) {
1724 if ((res = mp_init_copy (&y, b)) != MP_OKAY) {
1729 neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
1730 x.sign = y.sign = MP_ZPOS;
1732 /* normalize both x and y, ensure that y >= b/2, [b == 2**DIGIT_BIT] */
1733 norm = mp_count_bits(&y) % DIGIT_BIT;
1734 if (norm < (int)(DIGIT_BIT-1)) {
1735 norm = (DIGIT_BIT-1) - norm;
1736 if ((res = mp_mul_2d (&x, norm, &x)) != MP_OKAY) {
1739 if ((res = mp_mul_2d (&y, norm, &y)) != MP_OKAY) {
1746 /* note hac does 0 based, so if used==5 then its 0,1,2,3,4, e.g. use 4 */
1750 /* while (x >= y*b**n-t) do { q[n-t] += 1; x -= y*b**{n-t} } */
1751 if ((res = mp_lshd (&y, n - t)) != MP_OKAY) { /* y = y*b**{n-t} */
1755 while (mp_cmp (&x, &y) != MP_LT) {
1757 if ((res = mp_sub (&x, &y, &x)) != MP_OKAY) {
1762 /* reset y by shifting it back down */
1763 mp_rshd (&y, n - t);
1765 /* step 3. for i from n down to (t + 1) */
1766 for (i = n; i >= (t + 1); i--) {
1771 /* step 3.1 if xi == yt then set q{i-t-1} to b-1,
1772 * otherwise set q{i-t-1} to (xi*b + x{i-1})/yt */
1773 if (x.dp[i] == y.dp[t]) {
1774 q.dp[i - t - 1] = ((((mp_digit)1) << DIGIT_BIT) - 1);
1777 tmp = ((mp_word) x.dp[i]) << ((mp_word) DIGIT_BIT);
1778 tmp |= ((mp_word) x.dp[i - 1]);
1779 tmp /= ((mp_word) y.dp[t]);
1780 if (tmp > (mp_word) MP_MASK)
1782 q.dp[i - t - 1] = (mp_digit) (tmp & (mp_word) (MP_MASK));
1785 /* while (q{i-t-1} * (yt * b + y{t-1})) >
1786 xi * b**2 + xi-1 * b + xi-2
1790 q.dp[i - t - 1] = (q.dp[i - t - 1] + 1) & MP_MASK;
1792 q.dp[i - t - 1] = (q.dp[i - t - 1] - 1) & MP_MASK;
1794 /* find left hand */
1796 t1.dp[0] = (t - 1 < 0) ? 0 : y.dp[t - 1];
1799 if ((res = mp_mul_d (&t1, q.dp[i - t - 1], &t1)) != MP_OKAY) {
1803 /* find right hand */
1804 t2.dp[0] = (i - 2 < 0) ? 0 : x.dp[i - 2];
1805 t2.dp[1] = (i - 1 < 0) ? 0 : x.dp[i - 1];
1808 } while (mp_cmp_mag(&t1, &t2) == MP_GT);
1810 /* step 3.3 x = x - q{i-t-1} * y * b**{i-t-1} */
1811 if ((res = mp_mul_d (&y, q.dp[i - t - 1], &t1)) != MP_OKAY) {
1815 if ((res = mp_lshd (&t1, i - t - 1)) != MP_OKAY) {
1819 if ((res = mp_sub (&x, &t1, &x)) != MP_OKAY) {
1823 /* if x < 0 then { x = x + y*b**{i-t-1}; q{i-t-1} -= 1; } */
1824 if (x.sign == MP_NEG) {
1825 if ((res = mp_copy (&y, &t1)) != MP_OKAY) {
1828 if ((res = mp_lshd (&t1, i - t - 1)) != MP_OKAY) {
1831 if ((res = mp_add (&x, &t1, &x)) != MP_OKAY) {
1835 q.dp[i - t - 1] = (q.dp[i - t - 1] - 1UL) & MP_MASK;
1839 /* now q is the quotient and x is the remainder
1840 * [which we have to normalize]
1843 /* get sign before writing to c */
1844 x.sign = x.used == 0 ? MP_ZPOS : a->sign;
1853 mp_div_2d (&x, norm, &x, NULL);
1859 LBL_Y:mp_clear (&y);
1860 LBL_X:mp_clear (&x);
1861 LBL_T2:mp_clear (&t2);
1862 LBL_T1:mp_clear (&t1);
1863 LBL_Q:mp_clear (&q);
1873 #define TAB_SIZE 256
1876 static int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
1878 mp_int M[TAB_SIZE], res, mu;
1880 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
1881 int (*redux)(mp_int*,mp_int*,mp_int*);
1883 /* find window size */
1884 x = mp_count_bits (X);
1887 } else if (x <= 36) {
1889 } else if (x <= 140) {
1891 } else if (x <= 450) {
1893 } else if (x <= 1303) {
1895 } else if (x <= 3529) {
1908 /* init first cell */
1909 if ((err = mp_init(&M[1])) != MP_OKAY) {
1913 /* now init the second half of the array */
1914 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
1915 if ((err = mp_init(&M[x])) != MP_OKAY) {
1916 for (y = 1<<(winsize-1); y < x; y++) {
1924 /* create mu, used for Barrett reduction */
1925 if ((err = mp_init (&mu)) != MP_OKAY) {
1930 if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) {
1935 if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) {
1938 redux = mp_reduce_2k_l;
1943 * The M table contains powers of the base,
1944 * e.g. M[x] = G**x mod P
1946 * The first half of the table is not
1947 * computed though accept for M[0] and M[1]
1949 if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) {
1953 /* compute the value at M[1<<(winsize-1)] by squaring
1954 * M[1] (winsize-1) times
1956 if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
1960 for (x = 0; x < (winsize - 1); x++) {
1962 if ((err = mp_sqr (&M[1 << (winsize - 1)],
1963 &M[1 << (winsize - 1)])) != MP_OKAY) {
1967 /* reduce modulo P */
1968 if ((err = redux (&M[1 << (winsize - 1)], P, &mu)) != MP_OKAY) {
1973 /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
1974 * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
1976 for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
1977 if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
1980 if ((err = redux (&M[x], P, &mu)) != MP_OKAY) {
1986 if ((err = mp_init (&res)) != MP_OKAY) {
1991 /* set initial mode and bit cnt */
1995 digidx = X->used - 1;
2000 /* grab next digit as required */
2001 if (--bitcnt == 0) {
2002 /* if digidx == -1 we are out of digits */
2006 /* read next digit and reset the bitcnt */
2007 buf = X->dp[digidx--];
2008 bitcnt = (int) DIGIT_BIT;
2011 /* grab the next msb from the exponent */
2012 y = (buf >> (mp_digit)(DIGIT_BIT - 1)) & 1;
2013 buf <<= (mp_digit)1;
2015 /* if the bit is zero and mode == 0 then we ignore it
2016 * These represent the leading zero bits before the first 1 bit
2017 * in the exponent. Technically this opt is not required but it
2018 * does lower the # of trivial squaring/reductions used
2020 if (mode == 0 && y == 0) {
2024 /* if the bit is zero and mode == 1 then we square */
2025 if (mode == 1 && y == 0) {
2026 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2029 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2035 /* else we add it to the window */
2036 bitbuf |= (y << (winsize - ++bitcpy));
2039 if (bitcpy == winsize) {
2040 /* ok window is filled so square as required and multiply */
2042 for (x = 0; x < winsize; x++) {
2043 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2046 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2052 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
2055 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2059 /* empty window and reset */
2066 /* if bits remain then square/multiply */
2067 if (mode == 2 && bitcpy > 0) {
2068 /* square then multiply if the bit is set */
2069 for (x = 0; x < bitcpy; x++) {
2070 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2073 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2078 if ((bitbuf & (1 << winsize)) != 0) {
2080 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
2083 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2092 LBL_RES:mp_clear (&res);
2093 LBL_MU:mp_clear (&mu);
2096 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
2103 /* computes b = a*a */
2104 static int mp_sqr (mp_int * a, mp_int * b)
2108 #ifdef BN_MP_TOOM_SQR_C
2109 /* use Toom-Cook? */
2110 if (a->used >= TOOM_SQR_CUTOFF) {
2111 res = mp_toom_sqr(a, b);
2115 #ifdef BN_MP_KARATSUBA_SQR_C
2116 if (a->used >= KARATSUBA_SQR_CUTOFF) {
2117 res = mp_karatsuba_sqr (a, b);
2121 #ifdef BN_FAST_S_MP_SQR_C
2122 /* can we use the fast comba multiplier? */
2123 if ((a->used * 2 + 1) < MP_WARRAY &&
2125 (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) {
2126 res = fast_s_mp_sqr (a, b);
2129 #ifdef BN_S_MP_SQR_C
2130 res = s_mp_sqr (a, b);
2132 #error mp_sqr could fail
2141 /* reduces a modulo n where n is of the form 2**p - d
2142 This differs from reduce_2k since "d" can be larger
2143 than a single digit.
2145 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
2150 if ((res = mp_init(&q)) != MP_OKAY) {
2154 p = mp_count_bits(n);
2156 /* q = a/2**p, a = a mod 2**p */
2157 if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
2162 if ((res = mp_mul(&q, d, &q)) != MP_OKAY) {
2167 if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
2171 if (mp_cmp_mag(a, n) != MP_LT) {
2182 /* determines the setup value */
2183 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d)
2188 if ((res = mp_init(&tmp)) != MP_OKAY) {
2192 if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
2196 if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
2206 /* computes a = 2**b
2208 * Simple algorithm which zeroes the int, grows it then just sets one bit
2211 static int mp_2expt (mp_int * a, int b)
2215 /* zero a as per default */
2218 /* grow a to accommodate the single bit */
2219 if ((res = mp_grow (a, b / DIGIT_BIT + 1)) != MP_OKAY) {
2223 /* set the used count of where the bit will go */
2224 a->used = b / DIGIT_BIT + 1;
2226 /* put the single bit in its place */
2227 a->dp[b / DIGIT_BIT] = ((mp_digit)1) << (b % DIGIT_BIT);
2233 /* pre-calculate the value required for Barrett reduction
2234 * For a given modulus "b" it calulates the value required in "a"
2236 static int mp_reduce_setup (mp_int * a, mp_int * b)
2240 if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) {
2243 return mp_div (a, b, a, NULL);
2247 /* reduces x mod m, assumes 0 < x < m**2, mu is
2248 * precomputed via mp_reduce_setup.
2249 * From HAC pp.604 Algorithm 14.42
2251 static int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
2254 int res, um = m->used;
2257 if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
2261 /* q1 = x / b**(k-1) */
2262 mp_rshd (&q, um - 1);
2264 /* according to HAC this optimization is ok */
2265 if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) {
2266 if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) {
2270 #ifdef BN_S_MP_MUL_HIGH_DIGS_C
2271 if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
2274 #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C)
2275 if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
2280 #error mp_reduce would always fail
2287 /* q3 = q2 / b**(k+1) */
2288 mp_rshd (&q, um + 1);
2290 /* x = x mod b**(k+1), quick (no division) */
2291 if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
2295 /* q = q * m mod b**(k+1), quick (no division) */
2296 if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) {
2301 if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
2305 /* If x < 0, add b**(k+1) to it */
2306 if (mp_cmp_d (x, 0) == MP_LT) {
2308 if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) {
2311 if ((res = mp_add (x, &q, x)) != MP_OKAY) {
2316 /* Back off if it's too big */
2317 while (mp_cmp (x, m) != MP_LT) {
2318 if ((res = s_mp_sub (x, m, x)) != MP_OKAY) {
2330 /* multiplies |a| * |b| and only computes up to digs digits of result
2331 * HAC pp. 595, Algorithm 14.12 Modified so you can control how
2332 * many digits of output are created.
2334 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2337 int res, pa, pb, ix, iy;
2340 mp_digit tmpx, *tmpt, *tmpy;
2342 /* can we use the fast multiplier? */
2343 if (((digs) < MP_WARRAY) &&
2344 MIN (a->used, b->used) <
2345 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2346 return fast_s_mp_mul_digs (a, b, c, digs);
2349 if ((res = mp_init_size (&t, digs)) != MP_OKAY) {
2354 /* compute the digits of the product directly */
2356 for (ix = 0; ix < pa; ix++) {
2357 /* set the carry to zero */
2360 /* limit ourselves to making digs digits of output */
2361 pb = MIN (b->used, digs - ix);
2363 /* setup some aliases */
2364 /* copy of the digit from a used within the nested loop */
2367 /* an alias for the destination shifted ix places */
2370 /* an alias for the digits of b */
2373 /* compute the columns of the output and propagate the carry */
2374 for (iy = 0; iy < pb; iy++) {
2375 /* compute the column as a mp_word */
2376 r = ((mp_word)*tmpt) +
2377 ((mp_word)tmpx) * ((mp_word)*tmpy++) +
2380 /* the new column is the lower part of the result */
2381 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2383 /* get the carry word from the result */
2384 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2386 /* set carry if it is placed below digs */
2387 if (ix + iy < digs) {
2400 /* Fast (comba) multiplier
2402 * This is the fast column-array [comba] multiplier. It is
2403 * designed to compute the columns of the product first
2404 * then handle the carries afterwards. This has the effect
2405 * of making the nested loops that compute the columns very
2406 * simple and schedulable on super-scalar processors.
2408 * This has been modified to produce a variable number of
2409 * digits of output so if say only a half-product is required
2410 * you don't have to compute the upper half (a feature
2411 * required for fast Barrett reduction).
2413 * Based on Algorithm 14.12 on pp.595 of HAC.
2416 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2418 int olduse, res, pa, ix, iz;
2419 mp_digit W[MP_WARRAY];
2420 register mp_word _W;
2422 /* grow the destination as required */
2423 if (c->alloc < digs) {
2424 if ((res = mp_grow (c, digs)) != MP_OKAY) {
2429 /* number of output digits to produce */
2430 pa = MIN(digs, a->used + b->used);
2432 /* clear the carry */
2434 for (ix = 0; ix < pa; ix++) {
2437 mp_digit *tmpx, *tmpy;
2439 /* get offsets into the two bignums */
2440 ty = MIN(b->used-1, ix);
2443 /* setup temp aliases */
2447 /* this is the number of times the loop will iterrate, essentially
2448 while (tx++ < a->used && ty-- >= 0) { ... }
2450 iy = MIN(a->used-tx, ty+1);
2453 for (iz = 0; iz < iy; ++iz) {
2454 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
2459 W[ix] = ((mp_digit)_W) & MP_MASK;
2461 /* make next carry */
2462 _W = _W >> ((mp_word)DIGIT_BIT);
2470 register mp_digit *tmpc;
2472 for (ix = 0; ix < pa+1; ix++) {
2473 /* now extract the previous digit [below the carry] */
2477 /* clear unused digits [that existed in the old copy of c] */
2478 for (; ix < olduse; ix++) {
2487 /* init an mp_init for a given size */
2488 static int mp_init_size (mp_int * a, int size)
2492 /* pad size so there are always extra digits */
2493 size += (MP_PREC * 2) - (size % MP_PREC);
2496 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size);
2497 if (a->dp == NULL) {
2501 /* set the members */
2506 /* zero the digits */
2507 for (x = 0; x < size; x++) {
2515 /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
2516 static int s_mp_sqr (mp_int * a, mp_int * b)
2519 int res, ix, iy, pa;
2521 mp_digit u, tmpx, *tmpt;
2524 if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
2528 /* default used is maximum possible size */
2531 for (ix = 0; ix < pa; ix++) {
2532 /* first calculate the digit at 2*ix */
2533 /* calculate double precision result */
2534 r = ((mp_word) t.dp[2*ix]) +
2535 ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]);
2537 /* store lower part in result */
2538 t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
2541 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2543 /* left hand side of A[ix] * A[iy] */
2546 /* alias for where to store the results */
2547 tmpt = t.dp + (2*ix + 1);
2549 for (iy = ix + 1; iy < pa; iy++) {
2550 /* first calculate the product */
2551 r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
2553 /* now calculate the double precision result, note we use
2554 * addition instead of *2 since it's easier to optimize
2556 r = ((mp_word) *tmpt) + r + r + ((mp_word) u);
2558 /* store lower part */
2559 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2562 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2564 /* propagate upwards */
2565 while (u != ((mp_digit) 0)) {
2566 r = ((mp_word) *tmpt) + ((mp_word) u);
2567 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2568 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2579 /* multiplies |a| * |b| and does not compute the lower digs digits
2580 * [meant to get the higher part of the product]
2582 static int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2585 int res, pa, pb, ix, iy;
2588 mp_digit tmpx, *tmpt, *tmpy;
2590 /* can we use the fast multiplier? */
2591 #ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C
2592 if (((a->used + b->used + 1) < MP_WARRAY)
2593 && MIN (a->used, b->used) < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2594 return fast_s_mp_mul_high_digs (a, b, c, digs);
2598 if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) {
2601 t.used = a->used + b->used + 1;
2605 for (ix = 0; ix < pa; ix++) {
2606 /* clear the carry */
2609 /* left hand side of A[ix] * B[iy] */
2612 /* alias to the address of where the digits will be stored */
2613 tmpt = &(t.dp[digs]);
2615 /* alias for where to read the right hand side from */
2616 tmpy = b->dp + (digs - ix);
2618 for (iy = digs - ix; iy < pb; iy++) {
2619 /* calculate the double precision result */
2620 r = ((mp_word)*tmpt) +
2621 ((mp_word)tmpx) * ((mp_word)*tmpy++) +
2624 /* get the lower part */
2625 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2627 /* carry the carry */
2628 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2639 #ifdef BN_MP_MONTGOMERY_SETUP_C
2640 /* setups the montgomery reduction stuff */
2642 mp_montgomery_setup (mp_int * n, mp_digit * rho)
2646 /* fast inversion mod 2**k
2648 * Based on the fact that
2650 * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
2651 * => 2*X*A - X*X*A*A = 1
2652 * => 2*(1) - (1) = 1
2660 x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
2661 x *= 2 - b * x; /* here x*a==1 mod 2**8 */
2662 #if !defined(MP_8BIT)
2663 x *= 2 - b * x; /* here x*a==1 mod 2**16 */
2665 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
2666 x *= 2 - b * x; /* here x*a==1 mod 2**32 */
2669 x *= 2 - b * x; /* here x*a==1 mod 2**64 */
2672 /* rho = -1/m mod b */
2673 *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK;
2680 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2681 /* computes xR**-1 == x (mod N) via Montgomery Reduction
2683 * This is an optimized implementation of montgomery_reduce
2684 * which uses the comba method to quickly calculate the columns of the
2687 * Based on Algorithm 14.32 on pp.601 of HAC.
2689 static int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
2691 int ix, res, olduse;
2692 mp_word W[MP_WARRAY];
2694 /* get old used count */
2697 /* grow a as required */
2698 if (x->alloc < n->used + 1) {
2699 if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) {
2704 /* first we have to get the digits of the input into
2705 * an array of double precision words W[...]
2708 register mp_word *_W;
2709 register mp_digit *tmpx;
2711 /* alias for the W[] array */
2714 /* alias for the digits of x*/
2717 /* copy the digits of a into W[0..a->used-1] */
2718 for (ix = 0; ix < x->used; ix++) {
2722 /* zero the high words of W[a->used..m->used*2] */
2723 for (; ix < n->used * 2 + 1; ix++) {
2728 /* now we proceed to zero successive digits
2729 * from the least significant upwards
2731 for (ix = 0; ix < n->used; ix++) {
2732 /* mu = ai * m' mod b
2734 * We avoid a double precision multiplication (which isn't required)
2735 * by casting the value down to a mp_digit. Note this requires
2736 * that W[ix-1] have the carry cleared (see after the inner loop)
2738 register mp_digit mu;
2739 mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK);
2741 /* a = a + mu * m * b**i
2743 * This is computed in place and on the fly. The multiplication
2744 * by b**i is handled by offseting which columns the results
2747 * Note the comba method normally doesn't handle carries in the
2748 * inner loop In this case we fix the carry from the previous
2749 * column since the Montgomery reduction requires digits of the
2750 * result (so far) [see above] to work. This is
2751 * handled by fixing up one carry after the inner loop. The
2752 * carry fixups are done in order so after these loops the
2753 * first m->used words of W[] have the carries fixed
2757 register mp_digit *tmpn;
2758 register mp_word *_W;
2760 /* alias for the digits of the modulus */
2763 /* Alias for the columns set by an offset of ix */
2767 for (iy = 0; iy < n->used; iy++) {
2768 *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++);
2772 /* now fix carry for next digit, W[ix+1] */
2773 W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT);
2776 /* now we have to propagate the carries and
2777 * shift the words downward [all those least
2778 * significant digits we zeroed].
2781 register mp_digit *tmpx;
2782 register mp_word *_W, *_W1;
2784 /* nox fix rest of carries */
2786 /* alias for current word */
2789 /* alias for next word, where the carry goes */
2792 for (; ix <= n->used * 2 + 1; ix++) {
2793 *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT);
2796 /* copy out, A = A/b**n
2798 * The result is A/b**n but instead of converting from an
2799 * array of mp_word to mp_digit than calling mp_rshd
2800 * we just copy them in the right order
2803 /* alias for destination word */
2806 /* alias for shifted double precision result */
2809 for (ix = 0; ix < n->used + 1; ix++) {
2810 *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK));
2813 /* zero oldused digits, if the input a was larger than
2814 * m->used+1 we'll have to clear the digits
2816 for (; ix < olduse; ix++) {
2821 /* set the max used and clamp */
2822 x->used = n->used + 1;
2825 /* if A >= m then A = A - m */
2826 if (mp_cmp_mag (x, n) != MP_LT) {
2827 return s_mp_sub (x, n, x);
2834 #ifdef BN_MP_MUL_2_C
2836 static int mp_mul_2(mp_int * a, mp_int * b)
2838 int x, res, oldused;
2840 /* grow to accommodate result */
2841 if (b->alloc < a->used + 1) {
2842 if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) {
2851 register mp_digit r, rr, *tmpa, *tmpb;
2853 /* alias for source */
2856 /* alias for dest */
2861 for (x = 0; x < a->used; x++) {
2863 /* get what will be the *next* carry bit from the
2864 * MSB of the current digit
2866 rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1));
2868 /* now shift up this digit, add in the carry [from the previous] */
2869 *tmpb++ = ((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK;
2871 /* copy the carry that would be from the source
2872 * digit into the next iteration
2877 /* new leading digit? */
2879 /* add a MSB which is always 1 at this point */
2884 /* now zero any excess digits on the destination
2885 * that we didn't write to
2887 tmpb = b->dp + b->used;
2888 for (x = b->used; x < oldused; x++) {
2898 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
2900 * shifts with subtractions when the result is greater than b.
2902 * The method is slightly modified to shift B unconditionally up to just under
2903 * the leading bit of b. This saves a lot of multiple precision shifting.
2905 static int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
2909 /* how many bits of last digit does b use */
2910 bits = mp_count_bits (b) % DIGIT_BIT;
2913 if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) {
2922 /* now compute C = A * B mod b */
2923 for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
2924 if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
2927 if (mp_cmp_mag (a, b) != MP_LT) {
2928 if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
2939 #ifdef BN_MP_EXPTMOD_FAST_C
2940 /* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
2942 * Uses a left-to-right k-ary sliding window to compute the modular exponentiation.
2943 * The value of k changes based on the size of the exponent.
2945 * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
2948 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
2950 mp_int M[TAB_SIZE], res;
2952 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
2954 /* use a pointer to the reduction algorithm. This allows us to use
2955 * one of many reduction algorithms without modding the guts of
2956 * the code with if statements everywhere.
2958 int (*redux)(mp_int*,mp_int*,mp_digit);
2960 /* find window size */
2961 x = mp_count_bits (X);
2964 } else if (x <= 36) {
2966 } else if (x <= 140) {
2968 } else if (x <= 450) {
2970 } else if (x <= 1303) {
2972 } else if (x <= 3529) {
2985 /* init first cell */
2986 if ((err = mp_init(&M[1])) != MP_OKAY) {
2990 /* now init the second half of the array */
2991 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
2992 if ((err = mp_init(&M[x])) != MP_OKAY) {
2993 for (y = 1<<(winsize-1); y < x; y++) {
3001 /* determine and setup reduction code */
3003 #ifdef BN_MP_MONTGOMERY_SETUP_C
3004 /* now setup montgomery */
3005 if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
3013 /* automatically pick the comba one if available (saves quite a few calls/ifs) */
3014 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
3015 if (((P->used * 2 + 1) < MP_WARRAY) &&
3016 P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
3017 redux = fast_mp_montgomery_reduce;
3021 #ifdef BN_MP_MONTGOMERY_REDUCE_C
3022 /* use slower baseline Montgomery method */
3023 redux = mp_montgomery_reduce;
3029 } else if (redmode == 1) {
3030 #if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C)
3031 /* setup DR reduction for moduli of the form B**k - b */
3032 mp_dr_setup(P, &mp);
3033 redux = mp_dr_reduce;
3039 #if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C)
3040 /* setup DR reduction for moduli of the form 2**k - b */
3041 if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) {
3044 redux = mp_reduce_2k;
3052 if ((err = mp_init (&res)) != MP_OKAY) {
3060 * The first half of the table is not computed though accept for M[0] and M[1]
3064 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
3065 /* now we need R mod m */
3066 if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) {
3074 /* now set M[1] to G * R mod m */
3075 if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
3080 if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
3085 /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times */
3086 if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
3090 for (x = 0; x < (winsize - 1); x++) {
3091 if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) {
3094 if ((err = redux (&M[1 << (winsize - 1)], P, mp)) != MP_OKAY) {
3099 /* create upper table */
3100 for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
3101 if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
3104 if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
3109 /* set initial mode and bit cnt */
3113 digidx = X->used - 1;
3118 /* grab next digit as required */
3119 if (--bitcnt == 0) {
3120 /* if digidx == -1 we are out of digits so break */
3124 /* read next digit and reset bitcnt */
3125 buf = X->dp[digidx--];
3126 bitcnt = (int)DIGIT_BIT;
3129 /* grab the next msb from the exponent */
3130 y = (mp_digit)(buf >> (DIGIT_BIT - 1)) & 1;
3131 buf <<= (mp_digit)1;
3133 /* if the bit is zero and mode == 0 then we ignore it
3134 * These represent the leading zero bits before the first 1 bit
3135 * in the exponent. Technically this opt is not required but it
3136 * does lower the # of trivial squaring/reductions used
3138 if (mode == 0 && y == 0) {
3142 /* if the bit is zero and mode == 1 then we square */
3143 if (mode == 1 && y == 0) {
3144 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3147 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3153 /* else we add it to the window */
3154 bitbuf |= (y << (winsize - ++bitcpy));
3157 if (bitcpy == winsize) {
3158 /* ok window is filled so square as required and multiply */
3160 for (x = 0; x < winsize; x++) {
3161 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3164 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3170 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
3173 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3177 /* empty window and reset */
3184 /* if bits remain then square/multiply */
3185 if (mode == 2 && bitcpy > 0) {
3186 /* square then multiply if the bit is set */
3187 for (x = 0; x < bitcpy; x++) {
3188 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3191 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3195 /* get next bit of the window */
3197 if ((bitbuf & (1 << winsize)) != 0) {
3199 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
3202 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3210 /* fixup result if Montgomery reduction is used
3211 * recall that any value in a Montgomery system is
3212 * actually multiplied by R mod n. So we have
3213 * to reduce one more time to cancel out the factor
3216 if ((err = redux(&res, P, mp)) != MP_OKAY) {
3221 /* swap res with Y */
3224 LBL_RES:mp_clear (&res);
3227 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
3235 #ifdef BN_FAST_S_MP_SQR_C
3236 /* the jist of squaring...
3237 * you do like mult except the offset of the tmpx [one that
3238 * starts closer to zero] can't equal the offset of tmpy.
3239 * So basically you set up iy like before then you min it with
3240 * (ty-tx) so that it never happens. You double all those
3241 * you add in the inner loop
3243 After that loop you do the squares and add them in.
3246 static int fast_s_mp_sqr (mp_int * a, mp_int * b)
3248 int olduse, res, pa, ix, iz;
3249 mp_digit W[MP_WARRAY], *tmpx;
3252 /* grow the destination as required */
3253 pa = a->used + a->used;
3254 if (b->alloc < pa) {
3255 if ((res = mp_grow (b, pa)) != MP_OKAY) {
3260 /* number of output digits to produce */
3262 for (ix = 0; ix < pa; ix++) {
3270 /* get offsets into the two bignums */
3271 ty = MIN(a->used-1, ix);
3274 /* setup temp aliases */
3278 /* this is the number of times the loop will iterrate, essentially
3279 while (tx++ < a->used && ty-- >= 0) { ... }
3281 iy = MIN(a->used-tx, ty+1);
3283 /* now for squaring tx can never equal ty
3284 * we halve the distance since they approach at a rate of 2x
3285 * and we have to round because odd cases need to be executed
3287 iy = MIN(iy, (ty-tx+1)>>1);
3290 for (iz = 0; iz < iy; iz++) {
3291 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
3294 /* double the inner product and add carry */
3297 /* even columns have the square term in them */
3299 _W += ((mp_word)a->dp[ix>>1])*((mp_word)a->dp[ix>>1]);
3303 W[ix] = (mp_digit)(_W & MP_MASK);
3305 /* make next carry */
3306 W1 = _W >> ((mp_word)DIGIT_BIT);
3311 b->used = a->used+a->used;
3316 for (ix = 0; ix < pa; ix++) {
3317 *tmpb++ = W[ix] & MP_MASK;
3320 /* clear unused digits [that existed in the old copy of c] */
3321 for (; ix < olduse; ix++) {
3331 #ifdef BN_MP_MUL_D_C
3332 /* multiply by a digit */
3334 mp_mul_d (mp_int * a, mp_digit b, mp_int * c)
3336 mp_digit u, *tmpa, *tmpc;
3338 int ix, res, olduse;
3340 /* make sure c is big enough to hold a*b */
3341 if (c->alloc < a->used + 1) {
3342 if ((res = mp_grow (c, a->used + 1)) != MP_OKAY) {
3347 /* get the original destinations used count */
3353 /* alias for a->dp [source] */
3356 /* alias for c->dp [dest] */
3362 /* compute columns */
3363 for (ix = 0; ix < a->used; ix++) {
3364 /* compute product and carry sum for this term */
3365 r = ((mp_word) u) + ((mp_word)*tmpa++) * ((mp_word)b);
3367 /* mask off higher bits to get a single digit */
3368 *tmpc++ = (mp_digit) (r & ((mp_word) MP_MASK));
3370 /* send carry into next iteration */
3371 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
3374 /* store final carry [if any] and increment ix offset */
3378 /* now zero digits above the top */
3379 while (ix++ < olduse) {
3383 /* set used count */
3384 c->used = a->used + 1;