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
45 /* About 0.25 kB of code, but ~1.7kB of stack space! */
46 #define BN_FAST_S_MP_MUL_DIGS_C
50 #define BN_MP_DIV_SMALL
51 #define BN_MP_INIT_MULTI_C
52 #define BN_MP_CLEAR_MULTI_C
56 /* Current uses do not require support for negative exponent in exptmod, so we
57 * can save about 1.5 kB in leaving out invmod. */
58 #define LTM_NO_NEG_EXP
63 #define MIN(x,y) ((x)<(y)?(x):(y))
67 #define MAX(x,y) ((x)>(y)?(x):(y))
73 typedef unsigned long mp_digit;
74 typedef unsigned long mp_word __attribute__((mode(TI)));
79 typedef unsigned long mp_digit;
87 #define XMALLOC os_malloc
89 #define XREALLOC os_realloc
92 #define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))
94 #define MP_LT -1 /* less than */
95 #define MP_EQ 0 /* equal to */
96 #define MP_GT 1 /* greater than */
98 #define MP_ZPOS 0 /* positive integer */
99 #define MP_NEG 1 /* negative */
101 #define MP_OKAY 0 /* ok result */
102 #define MP_MEM -2 /* out of mem */
103 #define MP_VAL -3 /* invalid input */
105 #define MP_YES 1 /* yes response */
106 #define MP_NO 0 /* no response */
110 /* define this to use lower memory usage routines (exptmods mostly) */
113 /* default precision */
116 #define MP_PREC 32 /* default digits of precision */
118 #define MP_PREC 8 /* default digits of precision */
122 /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
123 #define MP_WARRAY (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1))
125 /* the infamous mp_int structure */
127 int used, alloc, sign;
132 /* ---> Basic Manipulations <--- */
133 #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
134 #define mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO)
135 #define mp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO)
138 /* prototypes for copied functions */
139 #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
140 static int s_mp_exptmod(mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode);
141 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
142 static int s_mp_sqr(mp_int * a, mp_int * b);
143 static int s_mp_mul_high_digs(mp_int * a, mp_int * b, mp_int * c, int digs);
145 #ifdef BN_FAST_S_MP_MUL_DIGS_C
146 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
149 #ifdef BN_MP_INIT_MULTI_C
150 static int mp_init_multi(mp_int *mp, ...);
152 #ifdef BN_MP_CLEAR_MULTI_C
153 static void mp_clear_multi(mp_int *mp, ...);
155 static int mp_lshd(mp_int * a, int b);
156 static void mp_set(mp_int * a, mp_digit b);
157 static void mp_clamp(mp_int * a);
158 static void mp_exch(mp_int * a, mp_int * b);
159 static void mp_rshd(mp_int * a, int b);
160 static void mp_zero(mp_int * a);
161 static int mp_mod_2d(mp_int * a, int b, mp_int * c);
162 static int mp_div_2d(mp_int * a, int b, mp_int * c, mp_int * d);
163 static int mp_init_copy(mp_int * a, mp_int * b);
164 static int mp_mul_2d(mp_int * a, int b, mp_int * c);
165 #ifndef LTM_NO_NEG_EXP
166 static int mp_div_2(mp_int * a, mp_int * b);
167 static int mp_invmod(mp_int * a, mp_int * b, mp_int * c);
168 static int mp_invmod_slow(mp_int * a, mp_int * b, mp_int * c);
169 #endif /* LTM_NO_NEG_EXP */
170 static int mp_copy(mp_int * a, mp_int * b);
171 static int mp_count_bits(mp_int * a);
172 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d);
173 static int mp_mod(mp_int * a, mp_int * b, mp_int * c);
174 static int mp_grow(mp_int * a, int size);
175 static int mp_cmp_mag(mp_int * a, mp_int * b);
177 static int mp_abs(mp_int * a, mp_int * b);
179 static int mp_sqr(mp_int * a, mp_int * b);
180 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d);
181 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d);
182 static int mp_2expt(mp_int * a, int b);
183 static int mp_reduce_setup(mp_int * a, mp_int * b);
184 static int mp_reduce(mp_int * x, mp_int * m, mp_int * mu);
185 static int mp_init_size(mp_int * a, int size);
186 #ifdef BN_MP_EXPTMOD_FAST_C
187 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode);
188 #endif /* BN_MP_EXPTMOD_FAST_C */
189 #ifdef BN_FAST_S_MP_SQR_C
190 static int fast_s_mp_sqr (mp_int * a, mp_int * b);
191 #endif /* BN_FAST_S_MP_SQR_C */
193 static int mp_mul_d (mp_int * a, mp_digit b, mp_int * c);
194 #endif /* BN_MP_MUL_D_C */
198 /* functions from bn_<func name>.c */
201 /* reverse an array, used for radix code */
202 static void bn_reverse (unsigned char *s, int len)
219 /* low level addition, based on HAC pp.594, Algorithm 14.7 */
220 static int s_mp_add (mp_int * a, mp_int * b, mp_int * c)
223 int olduse, res, min, max;
225 /* find sizes, we let |a| <= |b| which means we have to sort
226 * them. "x" will point to the input with the most digits
228 if (a->used > b->used) {
239 if (c->alloc < max + 1) {
240 if ((res = mp_grow (c, max + 1)) != MP_OKAY) {
245 /* get old used digit count and set new one */
250 register mp_digit u, *tmpa, *tmpb, *tmpc;
253 /* alias for digit pointers */
266 for (i = 0; i < min; i++) {
267 /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
268 *tmpc = *tmpa++ + *tmpb++ + u;
270 /* U = carry bit of T[i] */
271 u = *tmpc >> ((mp_digit)DIGIT_BIT);
273 /* take away carry bit from T[i] */
277 /* now copy higher words if any, that is in A+B
278 * if A or B has more digits add those in
281 for (; i < max; i++) {
282 /* T[i] = X[i] + U */
283 *tmpc = x->dp[i] + u;
285 /* U = carry bit of T[i] */
286 u = *tmpc >> ((mp_digit)DIGIT_BIT);
288 /* take away carry bit from T[i] */
296 /* clear digits above oldused */
297 for (i = c->used; i < olduse; i++) {
307 /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
308 static int s_mp_sub (mp_int * a, mp_int * b, mp_int * c)
310 int olduse, res, min, max;
317 if (c->alloc < max) {
318 if ((res = mp_grow (c, max)) != MP_OKAY) {
326 register mp_digit u, *tmpa, *tmpb, *tmpc;
329 /* alias for digit pointers */
334 /* set carry to zero */
336 for (i = 0; i < min; i++) {
337 /* T[i] = A[i] - B[i] - U */
338 *tmpc = *tmpa++ - *tmpb++ - u;
340 /* U = carry bit of T[i]
341 * Note this saves performing an AND operation since
342 * if a carry does occur it will propagate all the way to the
343 * MSB. As a result a single shift is enough to get the carry
345 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
347 /* Clear carry from T[i] */
351 /* now copy higher words if any, e.g. if A has more digits than B */
352 for (; i < max; i++) {
353 /* T[i] = A[i] - U */
356 /* U = carry bit of T[i] */
357 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
359 /* Clear carry from T[i] */
363 /* clear digits above used (since we may not have grown result above) */
364 for (i = c->used; i < olduse; i++) {
374 /* init a new mp_int */
375 static int mp_init (mp_int * a)
379 /* allocate memory required and clear it */
380 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * MP_PREC);
385 /* set the digits to zero */
386 for (i = 0; i < MP_PREC; i++) {
390 /* set the used to zero, allocated digits to the default precision
391 * and sign to positive */
400 /* clear one (frees) */
401 static void mp_clear (mp_int * a)
405 /* only do anything if a hasn't been freed previously */
407 /* first zero the digits */
408 for (i = 0; i < a->used; i++) {
415 /* reset members to make debugging easier */
417 a->alloc = a->used = 0;
423 /* high level addition (handles signs) */
424 static int mp_add (mp_int * a, mp_int * b, mp_int * c)
428 /* get sign of both inputs */
432 /* handle two cases, not four */
434 /* both positive or both negative */
435 /* add their magnitudes, copy the sign */
437 res = s_mp_add (a, b, c);
439 /* one positive, the other negative */
440 /* subtract the one with the greater magnitude from */
441 /* the one of the lesser magnitude. The result gets */
442 /* the sign of the one with the greater magnitude. */
443 if (mp_cmp_mag (a, b) == MP_LT) {
445 res = s_mp_sub (b, a, c);
448 res = s_mp_sub (a, b, c);
455 /* high level subtraction (handles signs) */
456 static int mp_sub (mp_int * a, mp_int * b, mp_int * c)
464 /* subtract a negative from a positive, OR */
465 /* subtract a positive from a negative. */
466 /* In either case, ADD their magnitudes, */
467 /* and use the sign of the first number. */
469 res = s_mp_add (a, b, c);
471 /* subtract a positive from a positive, OR */
472 /* subtract a negative from a negative. */
473 /* First, take the difference between their */
474 /* magnitudes, then... */
475 if (mp_cmp_mag (a, b) != MP_LT) {
476 /* Copy the sign from the first */
478 /* The first has a larger or equal magnitude */
479 res = s_mp_sub (a, b, c);
481 /* The result has the *opposite* sign from */
482 /* the first number. */
483 c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
484 /* The second has a larger magnitude */
485 res = s_mp_sub (b, a, c);
492 /* high level multiplication (handles sign) */
493 static int mp_mul (mp_int * a, mp_int * b, mp_int * c)
496 neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
499 #ifdef BN_MP_TOOM_MUL_C
500 if (MIN (a->used, b->used) >= TOOM_MUL_CUTOFF) {
501 res = mp_toom_mul(a, b, c);
504 #ifdef BN_MP_KARATSUBA_MUL_C
506 if (MIN (a->used, b->used) >= KARATSUBA_MUL_CUTOFF) {
507 res = mp_karatsuba_mul (a, b, c);
511 /* can we use the fast multiplier?
513 * The fast multiplier can be used if the output will
514 * have less than MP_WARRAY digits and the number of
515 * digits won't affect carry propagation
517 #ifdef BN_FAST_S_MP_MUL_DIGS_C
518 int digs = a->used + b->used + 1;
520 if ((digs < MP_WARRAY) &&
521 MIN(a->used, b->used) <=
522 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
523 res = fast_s_mp_mul_digs (a, b, c, digs);
526 #ifdef BN_S_MP_MUL_DIGS_C
527 res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */
529 #error mp_mul could fail
534 c->sign = (c->used > 0) ? neg : MP_ZPOS;
539 /* d = a * b (mod c) */
540 static int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
545 if ((res = mp_init (&t)) != MP_OKAY) {
549 if ((res = mp_mul (a, b, &t)) != MP_OKAY) {
553 res = mp_mod (&t, c, d);
559 /* c = a mod b, 0 <= c < b */
560 static int mp_mod (mp_int * a, mp_int * b, mp_int * c)
565 if ((res = mp_init (&t)) != MP_OKAY) {
569 if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) {
574 if (t.sign != b->sign) {
575 res = mp_add (b, &t, c);
586 /* this is a shell function that calls either the normal or Montgomery
587 * exptmod functions. Originally the call to the montgomery code was
588 * embedded in the normal function but that wasted a lot of stack space
589 * for nothing (since 99% of the time the Montgomery code would be called)
591 static int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
595 /* modulus P must be positive */
596 if (P->sign == MP_NEG) {
600 /* if exponent X is negative we have to recurse */
601 if (X->sign == MP_NEG) {
602 #ifdef LTM_NO_NEG_EXP
604 #else /* LTM_NO_NEG_EXP */
605 #ifdef BN_MP_INVMOD_C
609 /* first compute 1/G mod P */
610 if ((err = mp_init(&tmpG)) != MP_OKAY) {
613 if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
619 if ((err = mp_init(&tmpX)) != MP_OKAY) {
623 if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
624 mp_clear_multi(&tmpG, &tmpX, NULL);
628 /* and now compute (1/G)**|X| instead of G**X [X < 0] */
629 err = mp_exptmod(&tmpG, &tmpX, P, Y);
630 mp_clear_multi(&tmpG, &tmpX, NULL);
633 #error mp_exptmod would always fail
637 #endif /* LTM_NO_NEG_EXP */
640 /* modified diminished radix reduction */
641 #if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && defined(BN_S_MP_EXPTMOD_C)
642 if (mp_reduce_is_2k_l(P) == MP_YES) {
643 return s_mp_exptmod(G, X, P, Y, 1);
647 #ifdef BN_MP_DR_IS_MODULUS_C
648 /* is it a DR modulus? */
649 dr = mp_dr_is_modulus(P);
655 #ifdef BN_MP_REDUCE_IS_2K_C
656 /* if not, is it a unrestricted DR modulus? */
658 dr = mp_reduce_is_2k(P) << 1;
662 /* if the modulus is odd or dr != 0 use the montgomery method */
663 #ifdef BN_MP_EXPTMOD_FAST_C
664 if (mp_isodd (P) == 1 || dr != 0) {
665 return mp_exptmod_fast (G, X, P, Y, dr);
668 #ifdef BN_S_MP_EXPTMOD_C
669 /* otherwise use the generic Barrett reduction technique */
670 return s_mp_exptmod (G, X, P, Y, 0);
672 #error mp_exptmod could fail
673 /* no exptmod for evens */
676 #ifdef BN_MP_EXPTMOD_FAST_C
680 /* avoid compiler warnings about possibly unused variable */
685 /* compare two ints (signed)*/
686 static int mp_cmp (mp_int * a, mp_int * b)
688 /* compare based on sign */
689 if (a->sign != b->sign) {
690 if (a->sign == MP_NEG) {
698 if (a->sign == MP_NEG) {
699 /* if negative compare opposite direction */
700 return mp_cmp_mag(b, a);
702 return mp_cmp_mag(a, b);
707 /* compare a digit */
708 static int mp_cmp_d(mp_int * a, mp_digit b)
710 /* compare based on sign */
711 if (a->sign == MP_NEG) {
715 /* compare based on magnitude */
720 /* compare the only digit of a to b */
723 } else if (a->dp[0] < b) {
731 #ifndef LTM_NO_NEG_EXP
732 /* hac 14.61, pp608 */
733 static int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
735 /* b cannot be negative */
736 if (b->sign == MP_NEG || mp_iszero(b) == 1) {
740 #ifdef BN_FAST_MP_INVMOD_C
741 /* if the modulus is odd we can use a faster routine instead */
742 if (mp_isodd (b) == 1) {
743 return fast_mp_invmod (a, b, c);
747 #ifdef BN_MP_INVMOD_SLOW_C
748 return mp_invmod_slow(a, b, c);
751 #ifndef BN_FAST_MP_INVMOD_C
752 #ifndef BN_MP_INVMOD_SLOW_C
753 #error mp_invmod would always fail
758 #endif /* LTM_NO_NEG_EXP */
761 /* get the size for an unsigned equivalent */
762 static int mp_unsigned_bin_size (mp_int * a)
764 int size = mp_count_bits (a);
765 return (size / 8 + ((size & 7) != 0 ? 1 : 0));
769 #ifndef LTM_NO_NEG_EXP
770 /* hac 14.61, pp608 */
771 static int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c)
773 mp_int x, y, u, v, A, B, C, D;
776 /* b cannot be negative */
777 if (b->sign == MP_NEG || mp_iszero(b) == 1) {
782 if ((res = mp_init_multi(&x, &y, &u, &v,
783 &A, &B, &C, &D, NULL)) != MP_OKAY) {
788 if ((res = mp_mod(a, b, &x)) != MP_OKAY) {
791 if ((res = mp_copy (b, &y)) != MP_OKAY) {
795 /* 2. [modified] if x,y are both even then return an error! */
796 if (mp_iseven (&x) == 1 && mp_iseven (&y) == 1) {
801 /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
802 if ((res = mp_copy (&x, &u)) != MP_OKAY) {
805 if ((res = mp_copy (&y, &v)) != MP_OKAY) {
812 /* 4. while u is even do */
813 while (mp_iseven (&u) == 1) {
815 if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
818 /* 4.2 if A or B is odd then */
819 if (mp_isodd (&A) == 1 || mp_isodd (&B) == 1) {
820 /* A = (A+y)/2, B = (B-x)/2 */
821 if ((res = mp_add (&A, &y, &A)) != MP_OKAY) {
824 if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
828 /* A = A/2, B = B/2 */
829 if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
832 if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
837 /* 5. while v is even do */
838 while (mp_iseven (&v) == 1) {
840 if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
843 /* 5.2 if C or D is odd then */
844 if (mp_isodd (&C) == 1 || mp_isodd (&D) == 1) {
845 /* C = (C+y)/2, D = (D-x)/2 */
846 if ((res = mp_add (&C, &y, &C)) != MP_OKAY) {
849 if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
853 /* C = C/2, D = D/2 */
854 if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
857 if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
862 /* 6. if u >= v then */
863 if (mp_cmp (&u, &v) != MP_LT) {
864 /* u = u - v, A = A - C, B = B - D */
865 if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
869 if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
873 if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
877 /* v - v - u, C = C - A, D = D - B */
878 if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
882 if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
886 if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
891 /* if not zero goto step 4 */
892 if (mp_iszero (&u) == 0)
895 /* now a = C, b = D, gcd == g*v */
897 /* if v != 1 then there is no inverse */
898 if (mp_cmp_d (&v, 1) != MP_EQ) {
904 while (mp_cmp_d(&C, 0) == MP_LT) {
905 if ((res = mp_add(&C, b, &C)) != MP_OKAY) {
911 while (mp_cmp_mag(&C, b) != MP_LT) {
912 if ((res = mp_sub(&C, b, &C)) != MP_OKAY) {
917 /* C is now the inverse */
920 LBL_ERR:mp_clear_multi (&x, &y, &u, &v, &A, &B, &C, &D, NULL);
923 #endif /* LTM_NO_NEG_EXP */
926 /* compare maginitude of two ints (unsigned) */
927 static int mp_cmp_mag (mp_int * a, mp_int * b)
930 mp_digit *tmpa, *tmpb;
932 /* compare based on # of non-zero digits */
933 if (a->used > b->used) {
937 if (a->used < b->used) {
942 tmpa = a->dp + (a->used - 1);
945 tmpb = b->dp + (a->used - 1);
947 /* compare based on digits */
948 for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
961 /* reads a unsigned char array, assumes the msb is stored first [big endian] */
962 static int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
966 /* make sure there are at least two digits */
968 if ((res = mp_grow(a, 2)) != MP_OKAY) {
976 /* read the bytes in */
978 if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) {
986 a->dp[0] = (*b & MP_MASK);
987 a->dp[1] |= ((*b++ >> 7U) & 1);
996 /* store in unsigned [big endian] format */
997 static int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
1002 if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
1007 while (mp_iszero (&t) == 0) {
1009 b[x++] = (unsigned char) (t.dp[0] & 255);
1011 b[x++] = (unsigned char) (t.dp[0] | ((t.dp[1] & 0x01) << 7));
1013 if ((res = mp_div_2d (&t, 8, &t, NULL)) != MP_OKAY) {
1024 /* shift right by a certain bit count (store quotient in c, optional remainder in d) */
1025 static int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
1032 /* if the shift count is <= 0 then we do no work */
1034 res = mp_copy (a, c);
1041 if ((res = mp_init (&t)) != MP_OKAY) {
1045 /* get the remainder */
1047 if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
1054 if ((res = mp_copy (a, c)) != MP_OKAY) {
1059 /* shift by as many digits in the bit count */
1060 if (b >= (int)DIGIT_BIT) {
1061 mp_rshd (c, b / DIGIT_BIT);
1064 /* shift any bit count < DIGIT_BIT */
1065 D = (mp_digit) (b % DIGIT_BIT);
1067 register mp_digit *tmpc, mask, shift;
1070 mask = (((mp_digit)1) << D) - 1;
1073 shift = DIGIT_BIT - D;
1076 tmpc = c->dp + (c->used - 1);
1080 for (x = c->used - 1; x >= 0; x--) {
1081 /* get the lower bits of this word in a temp */
1084 /* shift the current word and mix in the carry bits from the previous word */
1085 *tmpc = (*tmpc >> D) | (r << shift);
1088 /* set the carry to the carry bits of the current word found above */
1101 static int mp_init_copy (mp_int * a, mp_int * b)
1105 if ((res = mp_init (a)) != MP_OKAY) {
1108 return mp_copy (b, a);
1113 static void mp_zero (mp_int * a)
1122 for (n = 0; n < a->alloc; n++) {
1129 static int mp_copy (mp_int * a, mp_int * b)
1133 /* if dst == src do nothing */
1139 if (b->alloc < a->used) {
1140 if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1145 /* zero b and copy the parameters over */
1147 register mp_digit *tmpa, *tmpb;
1149 /* pointer aliases */
1157 /* copy all the digits */
1158 for (n = 0; n < a->used; n++) {
1162 /* clear high digits */
1163 for (; n < b->used; n++) {
1168 /* copy used count and sign */
1175 /* shift right a certain amount of digits */
1176 static void mp_rshd (mp_int * a, int b)
1180 /* if b <= 0 then ignore it */
1185 /* if b > used then simply zero it and return */
1192 register mp_digit *bottom, *top;
1194 /* shift the digits down */
1199 /* top [offset into digits] */
1202 /* this is implemented as a sliding window where
1203 * the window is b-digits long and digits from
1204 * the top of the window are copied to the bottom
1208 b-2 | b-1 | b0 | b1 | b2 | ... | bb | ---->
1210 \-------------------/ ---->
1212 for (x = 0; x < (a->used - b); x++) {
1216 /* zero the top digits */
1217 for (; x < a->used; x++) {
1222 /* remove excess digits */
1227 /* swap the elements of two integers, for cases where you can't simply swap the
1228 * mp_int pointers around
1230 static void mp_exch (mp_int * a, mp_int * b)
1240 /* trim unused digits
1242 * This is used to ensure that leading zero digits are
1243 * trimed and the leading "used" digit will be non-zero
1244 * Typically very fast. Also fixes the sign if there
1245 * are no more leading digits
1247 static void mp_clamp (mp_int * a)
1249 /* decrease used while the most significant digit is
1252 while (a->used > 0 && a->dp[a->used - 1] == 0) {
1256 /* reset the sign flag if used == 0 */
1263 /* grow as required */
1264 static int mp_grow (mp_int * a, int size)
1269 /* if the alloc size is smaller alloc more ram */
1270 if (a->alloc < size) {
1271 /* ensure there are always at least MP_PREC digits extra on top */
1272 size += (MP_PREC * 2) - (size % MP_PREC);
1274 /* reallocate the array a->dp
1276 * We store the return in a temporary variable
1277 * in case the operation failed we don't want
1278 * to overwrite the dp member of a.
1280 tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size);
1282 /* reallocation failed but "a" is still valid [can be freed] */
1286 /* reallocation succeeded so set a->dp */
1289 /* zero excess digits */
1292 for (; i < a->alloc; i++) {
1303 * Simple function copies the input and fixes the sign to positive
1305 static int mp_abs (mp_int * a, mp_int * b)
1311 if ((res = mp_copy (a, b)) != MP_OKAY) {
1316 /* force the sign of b to positive */
1324 /* set to a digit */
1325 static void mp_set (mp_int * a, mp_digit b)
1328 a->dp[0] = b & MP_MASK;
1329 a->used = (a->dp[0] != 0) ? 1 : 0;
1333 #ifndef LTM_NO_NEG_EXP
1335 static int mp_div_2(mp_int * a, mp_int * b)
1337 int x, res, oldused;
1340 if (b->alloc < a->used) {
1341 if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1349 register mp_digit r, rr, *tmpa, *tmpb;
1352 tmpa = a->dp + b->used - 1;
1355 tmpb = b->dp + b->used - 1;
1359 for (x = b->used - 1; x >= 0; x--) {
1360 /* get the carry for the next iteration */
1363 /* shift the current digit, add in carry and store */
1364 *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
1366 /* forward carry to next iteration */
1370 /* zero excess digits */
1371 tmpb = b->dp + b->used;
1372 for (x = b->used; x < oldused; x++) {
1380 #endif /* LTM_NO_NEG_EXP */
1383 /* shift left by a certain bit count */
1384 static int mp_mul_2d (mp_int * a, int b, mp_int * c)
1391 if ((res = mp_copy (a, c)) != MP_OKAY) {
1396 if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) {
1397 if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) {
1402 /* shift by as many digits in the bit count */
1403 if (b >= (int)DIGIT_BIT) {
1404 if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) {
1409 /* shift any bit count < DIGIT_BIT */
1410 d = (mp_digit) (b % DIGIT_BIT);
1412 register mp_digit *tmpc, shift, mask, r, rr;
1415 /* bitmask for carries */
1416 mask = (((mp_digit)1) << d) - 1;
1418 /* shift for msbs */
1419 shift = DIGIT_BIT - d;
1426 for (x = 0; x < c->used; x++) {
1427 /* get the higher bits of the current word */
1428 rr = (*tmpc >> shift) & mask;
1430 /* shift the current word and OR in the carry */
1431 *tmpc = ((*tmpc << d) | r) & MP_MASK;
1434 /* set the carry to the carry bits of the current word */
1438 /* set final carry */
1440 c->dp[(c->used)++] = r;
1448 #ifdef BN_MP_INIT_MULTI_C
1449 static int mp_init_multi(mp_int *mp, ...)
1451 mp_err res = MP_OKAY; /* Assume ok until proven otherwise */
1452 int n = 0; /* Number of ok inits */
1453 mp_int* cur_arg = mp;
1456 va_start(args, mp); /* init args to next argument from caller */
1457 while (cur_arg != NULL) {
1458 if (mp_init(cur_arg) != MP_OKAY) {
1459 /* Oops - error! Back-track and mp_clear what we already
1460 succeeded in init-ing, then return error.
1464 /* end the current list */
1467 /* now start cleaning up */
1469 va_start(clean_args, mp);
1472 cur_arg = va_arg(clean_args, mp_int*);
1478 cur_arg = va_arg(args, mp_int*);
1481 return res; /* Assumed ok, if error flagged above. */
1486 #ifdef BN_MP_CLEAR_MULTI_C
1487 static void mp_clear_multi(mp_int *mp, ...)
1489 mp_int* next_mp = mp;
1492 while (next_mp != NULL) {
1494 next_mp = va_arg(args, mp_int*);
1501 /* shift left a certain amount of digits */
1502 static int mp_lshd (mp_int * a, int b)
1506 /* if its less than zero return */
1511 /* grow to fit the new digits */
1512 if (a->alloc < a->used + b) {
1513 if ((res = mp_grow (a, a->used + b)) != MP_OKAY) {
1519 register mp_digit *top, *bottom;
1521 /* increment the used by the shift amount then copy upwards */
1525 top = a->dp + a->used - 1;
1528 bottom = a->dp + a->used - 1 - b;
1530 /* much like mp_rshd this is implemented using a sliding window
1531 * except the window goes the otherway around. Copying from
1532 * the bottom to the top. see bn_mp_rshd.c for more info.
1534 for (x = a->used - 1; x >= b; x--) {
1538 /* zero the lower digits */
1540 for (x = 0; x < b; x++) {
1548 /* returns the number of bits in an int */
1549 static int mp_count_bits (mp_int * a)
1559 /* get number of digits and add that */
1560 r = (a->used - 1) * DIGIT_BIT;
1562 /* take the last digit and count the bits in it */
1563 q = a->dp[a->used - 1];
1564 while (q > ((mp_digit) 0)) {
1566 q >>= ((mp_digit) 1);
1572 /* calc a value mod 2**b */
1573 static int mp_mod_2d (mp_int * a, int b, mp_int * c)
1577 /* if b is <= 0 then zero the int */
1583 /* if the modulus is larger than the value than return */
1584 if (b >= (int) (a->used * DIGIT_BIT)) {
1585 res = mp_copy (a, c);
1590 if ((res = mp_copy (a, c)) != MP_OKAY) {
1594 /* zero digits above the last digit of the modulus */
1595 for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x++) {
1598 /* clear the digit that is not completely outside/inside the modulus */
1599 c->dp[b / DIGIT_BIT] &=
1600 (mp_digit) ((((mp_digit) 1) << (((mp_digit) b) % DIGIT_BIT)) - ((mp_digit) 1));
1606 #ifdef BN_MP_DIV_SMALL
1608 /* slower bit-bang division... also smaller */
1609 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d)
1611 mp_int ta, tb, tq, q;
1614 /* is divisor zero ? */
1615 if (mp_iszero (b) == 1) {
1619 /* if a < b then q=0, r = a */
1620 if (mp_cmp_mag (a, b) == MP_LT) {
1622 res = mp_copy (a, d);
1632 /* init our temps */
1633 if ((res = mp_init_multi(&ta, &tb, &tq, &q, NULL)) != MP_OKAY) {
1639 n = mp_count_bits(a) - mp_count_bits(b);
1640 if (((res = mp_abs(a, &ta)) != MP_OKAY) ||
1641 ((res = mp_abs(b, &tb)) != MP_OKAY) ||
1642 ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) ||
1643 ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) {
1648 if (mp_cmp(&tb, &ta) != MP_GT) {
1649 if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) ||
1650 ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) {
1654 if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) ||
1655 ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) {
1660 /* now q == quotient and ta == remainder */
1662 n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG);
1665 c->sign = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2;
1669 d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n;
1672 mp_clear_multi(&ta, &tb, &tq, &q, NULL);
1678 /* integer signed division.
1679 * c*b + d == a [e.g. a/b, c=quotient, d=remainder]
1680 * HAC pp.598 Algorithm 14.20
1682 * Note that the description in HAC is horribly
1683 * incomplete. For example, it doesn't consider
1684 * the case where digits are removed from 'x' in
1685 * the inner loop. It also doesn't consider the
1686 * case that y has fewer than three digits, etc..
1688 * The overall algorithm is as described as
1689 * 14.20 from HAC but fixed to treat these cases.
1691 static int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
1693 mp_int q, x, y, t1, t2;
1694 int res, n, t, i, norm, neg;
1696 /* is divisor zero ? */
1697 if (mp_iszero (b) == 1) {
1701 /* if a < b then q=0, r = a */
1702 if (mp_cmp_mag (a, b) == MP_LT) {
1704 res = mp_copy (a, d);
1714 if ((res = mp_init_size (&q, a->used + 2)) != MP_OKAY) {
1717 q.used = a->used + 2;
1719 if ((res = mp_init (&t1)) != MP_OKAY) {
1723 if ((res = mp_init (&t2)) != MP_OKAY) {
1727 if ((res = mp_init_copy (&x, a)) != MP_OKAY) {
1731 if ((res = mp_init_copy (&y, b)) != MP_OKAY) {
1736 neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
1737 x.sign = y.sign = MP_ZPOS;
1739 /* normalize both x and y, ensure that y >= b/2, [b == 2**DIGIT_BIT] */
1740 norm = mp_count_bits(&y) % DIGIT_BIT;
1741 if (norm < (int)(DIGIT_BIT-1)) {
1742 norm = (DIGIT_BIT-1) - norm;
1743 if ((res = mp_mul_2d (&x, norm, &x)) != MP_OKAY) {
1746 if ((res = mp_mul_2d (&y, norm, &y)) != MP_OKAY) {
1753 /* note hac does 0 based, so if used==5 then its 0,1,2,3,4, e.g. use 4 */
1757 /* while (x >= y*b**n-t) do { q[n-t] += 1; x -= y*b**{n-t} } */
1758 if ((res = mp_lshd (&y, n - t)) != MP_OKAY) { /* y = y*b**{n-t} */
1762 while (mp_cmp (&x, &y) != MP_LT) {
1764 if ((res = mp_sub (&x, &y, &x)) != MP_OKAY) {
1769 /* reset y by shifting it back down */
1770 mp_rshd (&y, n - t);
1772 /* step 3. for i from n down to (t + 1) */
1773 for (i = n; i >= (t + 1); i--) {
1778 /* step 3.1 if xi == yt then set q{i-t-1} to b-1,
1779 * otherwise set q{i-t-1} to (xi*b + x{i-1})/yt */
1780 if (x.dp[i] == y.dp[t]) {
1781 q.dp[i - t - 1] = ((((mp_digit)1) << DIGIT_BIT) - 1);
1784 tmp = ((mp_word) x.dp[i]) << ((mp_word) DIGIT_BIT);
1785 tmp |= ((mp_word) x.dp[i - 1]);
1786 tmp /= ((mp_word) y.dp[t]);
1787 if (tmp > (mp_word) MP_MASK)
1789 q.dp[i - t - 1] = (mp_digit) (tmp & (mp_word) (MP_MASK));
1792 /* while (q{i-t-1} * (yt * b + y{t-1})) >
1793 xi * b**2 + xi-1 * b + xi-2
1797 q.dp[i - t - 1] = (q.dp[i - t - 1] + 1) & MP_MASK;
1799 q.dp[i - t - 1] = (q.dp[i - t - 1] - 1) & MP_MASK;
1801 /* find left hand */
1803 t1.dp[0] = (t - 1 < 0) ? 0 : y.dp[t - 1];
1806 if ((res = mp_mul_d (&t1, q.dp[i - t - 1], &t1)) != MP_OKAY) {
1810 /* find right hand */
1811 t2.dp[0] = (i - 2 < 0) ? 0 : x.dp[i - 2];
1812 t2.dp[1] = (i - 1 < 0) ? 0 : x.dp[i - 1];
1815 } while (mp_cmp_mag(&t1, &t2) == MP_GT);
1817 /* step 3.3 x = x - q{i-t-1} * y * b**{i-t-1} */
1818 if ((res = mp_mul_d (&y, q.dp[i - t - 1], &t1)) != MP_OKAY) {
1822 if ((res = mp_lshd (&t1, i - t - 1)) != MP_OKAY) {
1826 if ((res = mp_sub (&x, &t1, &x)) != MP_OKAY) {
1830 /* if x < 0 then { x = x + y*b**{i-t-1}; q{i-t-1} -= 1; } */
1831 if (x.sign == MP_NEG) {
1832 if ((res = mp_copy (&y, &t1)) != MP_OKAY) {
1835 if ((res = mp_lshd (&t1, i - t - 1)) != MP_OKAY) {
1838 if ((res = mp_add (&x, &t1, &x)) != MP_OKAY) {
1842 q.dp[i - t - 1] = (q.dp[i - t - 1] - 1UL) & MP_MASK;
1846 /* now q is the quotient and x is the remainder
1847 * [which we have to normalize]
1850 /* get sign before writing to c */
1851 x.sign = x.used == 0 ? MP_ZPOS : a->sign;
1860 mp_div_2d (&x, norm, &x, NULL);
1866 LBL_Y:mp_clear (&y);
1867 LBL_X:mp_clear (&x);
1868 LBL_T2:mp_clear (&t2);
1869 LBL_T1:mp_clear (&t1);
1870 LBL_Q:mp_clear (&q);
1880 #define TAB_SIZE 256
1883 static int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
1885 mp_int M[TAB_SIZE], res, mu;
1887 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
1888 int (*redux)(mp_int*,mp_int*,mp_int*);
1890 /* find window size */
1891 x = mp_count_bits (X);
1894 } else if (x <= 36) {
1896 } else if (x <= 140) {
1898 } else if (x <= 450) {
1900 } else if (x <= 1303) {
1902 } else if (x <= 3529) {
1915 /* init first cell */
1916 if ((err = mp_init(&M[1])) != MP_OKAY) {
1920 /* now init the second half of the array */
1921 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
1922 if ((err = mp_init(&M[x])) != MP_OKAY) {
1923 for (y = 1<<(winsize-1); y < x; y++) {
1931 /* create mu, used for Barrett reduction */
1932 if ((err = mp_init (&mu)) != MP_OKAY) {
1937 if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) {
1942 if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) {
1945 redux = mp_reduce_2k_l;
1950 * The M table contains powers of the base,
1951 * e.g. M[x] = G**x mod P
1953 * The first half of the table is not
1954 * computed though accept for M[0] and M[1]
1956 if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) {
1960 /* compute the value at M[1<<(winsize-1)] by squaring
1961 * M[1] (winsize-1) times
1963 if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
1967 for (x = 0; x < (winsize - 1); x++) {
1969 if ((err = mp_sqr (&M[1 << (winsize - 1)],
1970 &M[1 << (winsize - 1)])) != MP_OKAY) {
1974 /* reduce modulo P */
1975 if ((err = redux (&M[1 << (winsize - 1)], P, &mu)) != MP_OKAY) {
1980 /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
1981 * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
1983 for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
1984 if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
1987 if ((err = redux (&M[x], P, &mu)) != MP_OKAY) {
1993 if ((err = mp_init (&res)) != MP_OKAY) {
1998 /* set initial mode and bit cnt */
2002 digidx = X->used - 1;
2007 /* grab next digit as required */
2008 if (--bitcnt == 0) {
2009 /* if digidx == -1 we are out of digits */
2013 /* read next digit and reset the bitcnt */
2014 buf = X->dp[digidx--];
2015 bitcnt = (int) DIGIT_BIT;
2018 /* grab the next msb from the exponent */
2019 y = (buf >> (mp_digit)(DIGIT_BIT - 1)) & 1;
2020 buf <<= (mp_digit)1;
2022 /* if the bit is zero and mode == 0 then we ignore it
2023 * These represent the leading zero bits before the first 1 bit
2024 * in the exponent. Technically this opt is not required but it
2025 * does lower the # of trivial squaring/reductions used
2027 if (mode == 0 && y == 0) {
2031 /* if the bit is zero and mode == 1 then we square */
2032 if (mode == 1 && y == 0) {
2033 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2036 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2042 /* else we add it to the window */
2043 bitbuf |= (y << (winsize - ++bitcpy));
2046 if (bitcpy == winsize) {
2047 /* ok window is filled so square as required and multiply */
2049 for (x = 0; x < winsize; x++) {
2050 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2053 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2059 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
2062 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2066 /* empty window and reset */
2073 /* if bits remain then square/multiply */
2074 if (mode == 2 && bitcpy > 0) {
2075 /* square then multiply if the bit is set */
2076 for (x = 0; x < bitcpy; x++) {
2077 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2080 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2085 if ((bitbuf & (1 << winsize)) != 0) {
2087 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
2090 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
2099 LBL_RES:mp_clear (&res);
2100 LBL_MU:mp_clear (&mu);
2103 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
2110 /* computes b = a*a */
2111 static int mp_sqr (mp_int * a, mp_int * b)
2115 #ifdef BN_MP_TOOM_SQR_C
2116 /* use Toom-Cook? */
2117 if (a->used >= TOOM_SQR_CUTOFF) {
2118 res = mp_toom_sqr(a, b);
2122 #ifdef BN_MP_KARATSUBA_SQR_C
2123 if (a->used >= KARATSUBA_SQR_CUTOFF) {
2124 res = mp_karatsuba_sqr (a, b);
2128 #ifdef BN_FAST_S_MP_SQR_C
2129 /* can we use the fast comba multiplier? */
2130 if ((a->used * 2 + 1) < MP_WARRAY &&
2132 (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) {
2133 res = fast_s_mp_sqr (a, b);
2136 #ifdef BN_S_MP_SQR_C
2137 res = s_mp_sqr (a, b);
2139 #error mp_sqr could fail
2148 /* reduces a modulo n where n is of the form 2**p - d
2149 This differs from reduce_2k since "d" can be larger
2150 than a single digit.
2152 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
2157 if ((res = mp_init(&q)) != MP_OKAY) {
2161 p = mp_count_bits(n);
2163 /* q = a/2**p, a = a mod 2**p */
2164 if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
2169 if ((res = mp_mul(&q, d, &q)) != MP_OKAY) {
2174 if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
2178 if (mp_cmp_mag(a, n) != MP_LT) {
2189 /* determines the setup value */
2190 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d)
2195 if ((res = mp_init(&tmp)) != MP_OKAY) {
2199 if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
2203 if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
2213 /* computes a = 2**b
2215 * Simple algorithm which zeroes the int, grows it then just sets one bit
2218 static int mp_2expt (mp_int * a, int b)
2222 /* zero a as per default */
2225 /* grow a to accommodate the single bit */
2226 if ((res = mp_grow (a, b / DIGIT_BIT + 1)) != MP_OKAY) {
2230 /* set the used count of where the bit will go */
2231 a->used = b / DIGIT_BIT + 1;
2233 /* put the single bit in its place */
2234 a->dp[b / DIGIT_BIT] = ((mp_digit)1) << (b % DIGIT_BIT);
2240 /* pre-calculate the value required for Barrett reduction
2241 * For a given modulus "b" it calulates the value required in "a"
2243 static int mp_reduce_setup (mp_int * a, mp_int * b)
2247 if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) {
2250 return mp_div (a, b, a, NULL);
2254 /* reduces x mod m, assumes 0 < x < m**2, mu is
2255 * precomputed via mp_reduce_setup.
2256 * From HAC pp.604 Algorithm 14.42
2258 static int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
2261 int res, um = m->used;
2264 if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
2268 /* q1 = x / b**(k-1) */
2269 mp_rshd (&q, um - 1);
2271 /* according to HAC this optimization is ok */
2272 if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) {
2273 if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) {
2277 #ifdef BN_S_MP_MUL_HIGH_DIGS_C
2278 if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
2281 #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C)
2282 if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
2287 #error mp_reduce would always fail
2294 /* q3 = q2 / b**(k+1) */
2295 mp_rshd (&q, um + 1);
2297 /* x = x mod b**(k+1), quick (no division) */
2298 if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
2302 /* q = q * m mod b**(k+1), quick (no division) */
2303 if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) {
2308 if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
2312 /* If x < 0, add b**(k+1) to it */
2313 if (mp_cmp_d (x, 0) == MP_LT) {
2315 if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) {
2318 if ((res = mp_add (x, &q, x)) != MP_OKAY) {
2323 /* Back off if it's too big */
2324 while (mp_cmp (x, m) != MP_LT) {
2325 if ((res = s_mp_sub (x, m, x)) != MP_OKAY) {
2337 /* multiplies |a| * |b| and only computes up to digs digits of result
2338 * HAC pp. 595, Algorithm 14.12 Modified so you can control how
2339 * many digits of output are created.
2341 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2344 int res, pa, pb, ix, iy;
2347 mp_digit tmpx, *tmpt, *tmpy;
2349 #ifdef BN_FAST_S_MP_MUL_DIGS_C
2350 /* can we use the fast multiplier? */
2351 if (((digs) < MP_WARRAY) &&
2352 MIN (a->used, b->used) <
2353 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2354 return fast_s_mp_mul_digs (a, b, c, digs);
2358 if ((res = mp_init_size (&t, digs)) != MP_OKAY) {
2363 /* compute the digits of the product directly */
2365 for (ix = 0; ix < pa; ix++) {
2366 /* set the carry to zero */
2369 /* limit ourselves to making digs digits of output */
2370 pb = MIN (b->used, digs - ix);
2372 /* setup some aliases */
2373 /* copy of the digit from a used within the nested loop */
2376 /* an alias for the destination shifted ix places */
2379 /* an alias for the digits of b */
2382 /* compute the columns of the output and propagate the carry */
2383 for (iy = 0; iy < pb; iy++) {
2384 /* compute the column as a mp_word */
2385 r = ((mp_word)*tmpt) +
2386 ((mp_word)tmpx) * ((mp_word)*tmpy++) +
2389 /* the new column is the lower part of the result */
2390 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2392 /* get the carry word from the result */
2393 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2395 /* set carry if it is placed below digs */
2396 if (ix + iy < digs) {
2409 #ifdef BN_FAST_S_MP_MUL_DIGS_C
2410 /* Fast (comba) multiplier
2412 * This is the fast column-array [comba] multiplier. It is
2413 * designed to compute the columns of the product first
2414 * then handle the carries afterwards. This has the effect
2415 * of making the nested loops that compute the columns very
2416 * simple and schedulable on super-scalar processors.
2418 * This has been modified to produce a variable number of
2419 * digits of output so if say only a half-product is required
2420 * you don't have to compute the upper half (a feature
2421 * required for fast Barrett reduction).
2423 * Based on Algorithm 14.12 on pp.595 of HAC.
2426 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2428 int olduse, res, pa, ix, iz;
2429 mp_digit W[MP_WARRAY];
2430 register mp_word _W;
2432 /* grow the destination as required */
2433 if (c->alloc < digs) {
2434 if ((res = mp_grow (c, digs)) != MP_OKAY) {
2439 /* number of output digits to produce */
2440 pa = MIN(digs, a->used + b->used);
2442 /* clear the carry */
2444 for (ix = 0; ix < pa; ix++) {
2447 mp_digit *tmpx, *tmpy;
2449 /* get offsets into the two bignums */
2450 ty = MIN(b->used-1, ix);
2453 /* setup temp aliases */
2457 /* this is the number of times the loop will iterrate, essentially
2458 while (tx++ < a->used && ty-- >= 0) { ... }
2460 iy = MIN(a->used-tx, ty+1);
2463 for (iz = 0; iz < iy; ++iz) {
2464 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
2469 W[ix] = ((mp_digit)_W) & MP_MASK;
2471 /* make next carry */
2472 _W = _W >> ((mp_word)DIGIT_BIT);
2480 register mp_digit *tmpc;
2482 for (ix = 0; ix < pa+1; ix++) {
2483 /* now extract the previous digit [below the carry] */
2487 /* clear unused digits [that existed in the old copy of c] */
2488 for (; ix < olduse; ix++) {
2495 #endif /* BN_FAST_S_MP_MUL_DIGS_C */
2498 /* init an mp_init for a given size */
2499 static int mp_init_size (mp_int * a, int size)
2503 /* pad size so there are always extra digits */
2504 size += (MP_PREC * 2) - (size % MP_PREC);
2507 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size);
2508 if (a->dp == NULL) {
2512 /* set the members */
2517 /* zero the digits */
2518 for (x = 0; x < size; x++) {
2526 /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
2527 static int s_mp_sqr (mp_int * a, mp_int * b)
2530 int res, ix, iy, pa;
2532 mp_digit u, tmpx, *tmpt;
2535 if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
2539 /* default used is maximum possible size */
2542 for (ix = 0; ix < pa; ix++) {
2543 /* first calculate the digit at 2*ix */
2544 /* calculate double precision result */
2545 r = ((mp_word) t.dp[2*ix]) +
2546 ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]);
2548 /* store lower part in result */
2549 t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
2552 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2554 /* left hand side of A[ix] * A[iy] */
2557 /* alias for where to store the results */
2558 tmpt = t.dp + (2*ix + 1);
2560 for (iy = ix + 1; iy < pa; iy++) {
2561 /* first calculate the product */
2562 r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
2564 /* now calculate the double precision result, note we use
2565 * addition instead of *2 since it's easier to optimize
2567 r = ((mp_word) *tmpt) + r + r + ((mp_word) u);
2569 /* store lower part */
2570 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2573 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2575 /* propagate upwards */
2576 while (u != ((mp_digit) 0)) {
2577 r = ((mp_word) *tmpt) + ((mp_word) u);
2578 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2579 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2590 /* multiplies |a| * |b| and does not compute the lower digs digits
2591 * [meant to get the higher part of the product]
2593 static int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2596 int res, pa, pb, ix, iy;
2599 mp_digit tmpx, *tmpt, *tmpy;
2601 /* can we use the fast multiplier? */
2602 #ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C
2603 if (((a->used + b->used + 1) < MP_WARRAY)
2604 && MIN (a->used, b->used) < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2605 return fast_s_mp_mul_high_digs (a, b, c, digs);
2609 if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) {
2612 t.used = a->used + b->used + 1;
2616 for (ix = 0; ix < pa; ix++) {
2617 /* clear the carry */
2620 /* left hand side of A[ix] * B[iy] */
2623 /* alias to the address of where the digits will be stored */
2624 tmpt = &(t.dp[digs]);
2626 /* alias for where to read the right hand side from */
2627 tmpy = b->dp + (digs - ix);
2629 for (iy = digs - ix; iy < pb; iy++) {
2630 /* calculate the double precision result */
2631 r = ((mp_word)*tmpt) +
2632 ((mp_word)tmpx) * ((mp_word)*tmpy++) +
2635 /* get the lower part */
2636 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2638 /* carry the carry */
2639 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2650 #ifdef BN_MP_MONTGOMERY_SETUP_C
2651 /* setups the montgomery reduction stuff */
2653 mp_montgomery_setup (mp_int * n, mp_digit * rho)
2657 /* fast inversion mod 2**k
2659 * Based on the fact that
2661 * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
2662 * => 2*X*A - X*X*A*A = 1
2663 * => 2*(1) - (1) = 1
2671 x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
2672 x *= 2 - b * x; /* here x*a==1 mod 2**8 */
2673 #if !defined(MP_8BIT)
2674 x *= 2 - b * x; /* here x*a==1 mod 2**16 */
2676 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
2677 x *= 2 - b * x; /* here x*a==1 mod 2**32 */
2680 x *= 2 - b * x; /* here x*a==1 mod 2**64 */
2683 /* rho = -1/m mod b */
2684 *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK;
2691 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2692 /* computes xR**-1 == x (mod N) via Montgomery Reduction
2694 * This is an optimized implementation of montgomery_reduce
2695 * which uses the comba method to quickly calculate the columns of the
2698 * Based on Algorithm 14.32 on pp.601 of HAC.
2700 static int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
2702 int ix, res, olduse;
2703 mp_word W[MP_WARRAY];
2705 /* get old used count */
2708 /* grow a as required */
2709 if (x->alloc < n->used + 1) {
2710 if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) {
2715 /* first we have to get the digits of the input into
2716 * an array of double precision words W[...]
2719 register mp_word *_W;
2720 register mp_digit *tmpx;
2722 /* alias for the W[] array */
2725 /* alias for the digits of x*/
2728 /* copy the digits of a into W[0..a->used-1] */
2729 for (ix = 0; ix < x->used; ix++) {
2733 /* zero the high words of W[a->used..m->used*2] */
2734 for (; ix < n->used * 2 + 1; ix++) {
2739 /* now we proceed to zero successive digits
2740 * from the least significant upwards
2742 for (ix = 0; ix < n->used; ix++) {
2743 /* mu = ai * m' mod b
2745 * We avoid a double precision multiplication (which isn't required)
2746 * by casting the value down to a mp_digit. Note this requires
2747 * that W[ix-1] have the carry cleared (see after the inner loop)
2749 register mp_digit mu;
2750 mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK);
2752 /* a = a + mu * m * b**i
2754 * This is computed in place and on the fly. The multiplication
2755 * by b**i is handled by offseting which columns the results
2758 * Note the comba method normally doesn't handle carries in the
2759 * inner loop In this case we fix the carry from the previous
2760 * column since the Montgomery reduction requires digits of the
2761 * result (so far) [see above] to work. This is
2762 * handled by fixing up one carry after the inner loop. The
2763 * carry fixups are done in order so after these loops the
2764 * first m->used words of W[] have the carries fixed
2768 register mp_digit *tmpn;
2769 register mp_word *_W;
2771 /* alias for the digits of the modulus */
2774 /* Alias for the columns set by an offset of ix */
2778 for (iy = 0; iy < n->used; iy++) {
2779 *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++);
2783 /* now fix carry for next digit, W[ix+1] */
2784 W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT);
2787 /* now we have to propagate the carries and
2788 * shift the words downward [all those least
2789 * significant digits we zeroed].
2792 register mp_digit *tmpx;
2793 register mp_word *_W, *_W1;
2795 /* nox fix rest of carries */
2797 /* alias for current word */
2800 /* alias for next word, where the carry goes */
2803 for (; ix <= n->used * 2 + 1; ix++) {
2804 *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT);
2807 /* copy out, A = A/b**n
2809 * The result is A/b**n but instead of converting from an
2810 * array of mp_word to mp_digit than calling mp_rshd
2811 * we just copy them in the right order
2814 /* alias for destination word */
2817 /* alias for shifted double precision result */
2820 for (ix = 0; ix < n->used + 1; ix++) {
2821 *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK));
2824 /* zero oldused digits, if the input a was larger than
2825 * m->used+1 we'll have to clear the digits
2827 for (; ix < olduse; ix++) {
2832 /* set the max used and clamp */
2833 x->used = n->used + 1;
2836 /* if A >= m then A = A - m */
2837 if (mp_cmp_mag (x, n) != MP_LT) {
2838 return s_mp_sub (x, n, x);
2845 #ifdef BN_MP_MUL_2_C
2847 static int mp_mul_2(mp_int * a, mp_int * b)
2849 int x, res, oldused;
2851 /* grow to accommodate result */
2852 if (b->alloc < a->used + 1) {
2853 if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) {
2862 register mp_digit r, rr, *tmpa, *tmpb;
2864 /* alias for source */
2867 /* alias for dest */
2872 for (x = 0; x < a->used; x++) {
2874 /* get what will be the *next* carry bit from the
2875 * MSB of the current digit
2877 rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1));
2879 /* now shift up this digit, add in the carry [from the previous] */
2880 *tmpb++ = ((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK;
2882 /* copy the carry that would be from the source
2883 * digit into the next iteration
2888 /* new leading digit? */
2890 /* add a MSB which is always 1 at this point */
2895 /* now zero any excess digits on the destination
2896 * that we didn't write to
2898 tmpb = b->dp + b->used;
2899 for (x = b->used; x < oldused; x++) {
2909 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
2911 * shifts with subtractions when the result is greater than b.
2913 * The method is slightly modified to shift B unconditionally up to just under
2914 * the leading bit of b. This saves a lot of multiple precision shifting.
2916 static int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
2920 /* how many bits of last digit does b use */
2921 bits = mp_count_bits (b) % DIGIT_BIT;
2924 if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) {
2933 /* now compute C = A * B mod b */
2934 for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
2935 if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
2938 if (mp_cmp_mag (a, b) != MP_LT) {
2939 if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
2950 #ifdef BN_MP_EXPTMOD_FAST_C
2951 /* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
2953 * Uses a left-to-right k-ary sliding window to compute the modular exponentiation.
2954 * The value of k changes based on the size of the exponent.
2956 * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
2959 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
2961 mp_int M[TAB_SIZE], res;
2963 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
2965 /* use a pointer to the reduction algorithm. This allows us to use
2966 * one of many reduction algorithms without modding the guts of
2967 * the code with if statements everywhere.
2969 int (*redux)(mp_int*,mp_int*,mp_digit);
2971 /* find window size */
2972 x = mp_count_bits (X);
2975 } else if (x <= 36) {
2977 } else if (x <= 140) {
2979 } else if (x <= 450) {
2981 } else if (x <= 1303) {
2983 } else if (x <= 3529) {
2996 /* init first cell */
2997 if ((err = mp_init(&M[1])) != MP_OKAY) {
3001 /* now init the second half of the array */
3002 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
3003 if ((err = mp_init(&M[x])) != MP_OKAY) {
3004 for (y = 1<<(winsize-1); y < x; y++) {
3012 /* determine and setup reduction code */
3014 #ifdef BN_MP_MONTGOMERY_SETUP_C
3015 /* now setup montgomery */
3016 if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
3024 /* automatically pick the comba one if available (saves quite a few calls/ifs) */
3025 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
3026 if (((P->used * 2 + 1) < MP_WARRAY) &&
3027 P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
3028 redux = fast_mp_montgomery_reduce;
3032 #ifdef BN_MP_MONTGOMERY_REDUCE_C
3033 /* use slower baseline Montgomery method */
3034 redux = mp_montgomery_reduce;
3040 } else if (redmode == 1) {
3041 #if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C)
3042 /* setup DR reduction for moduli of the form B**k - b */
3043 mp_dr_setup(P, &mp);
3044 redux = mp_dr_reduce;
3050 #if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C)
3051 /* setup DR reduction for moduli of the form 2**k - b */
3052 if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) {
3055 redux = mp_reduce_2k;
3063 if ((err = mp_init (&res)) != MP_OKAY) {
3071 * The first half of the table is not computed though accept for M[0] and M[1]
3075 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
3076 /* now we need R mod m */
3077 if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) {
3085 /* now set M[1] to G * R mod m */
3086 if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
3091 if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
3096 /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times */
3097 if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
3101 for (x = 0; x < (winsize - 1); x++) {
3102 if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) {
3105 if ((err = redux (&M[1 << (winsize - 1)], P, mp)) != MP_OKAY) {
3110 /* create upper table */
3111 for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
3112 if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
3115 if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
3120 /* set initial mode and bit cnt */
3124 digidx = X->used - 1;
3129 /* grab next digit as required */
3130 if (--bitcnt == 0) {
3131 /* if digidx == -1 we are out of digits so break */
3135 /* read next digit and reset bitcnt */
3136 buf = X->dp[digidx--];
3137 bitcnt = (int)DIGIT_BIT;
3140 /* grab the next msb from the exponent */
3141 y = (mp_digit)(buf >> (DIGIT_BIT - 1)) & 1;
3142 buf <<= (mp_digit)1;
3144 /* if the bit is zero and mode == 0 then we ignore it
3145 * These represent the leading zero bits before the first 1 bit
3146 * in the exponent. Technically this opt is not required but it
3147 * does lower the # of trivial squaring/reductions used
3149 if (mode == 0 && y == 0) {
3153 /* if the bit is zero and mode == 1 then we square */
3154 if (mode == 1 && y == 0) {
3155 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3158 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3164 /* else we add it to the window */
3165 bitbuf |= (y << (winsize - ++bitcpy));
3168 if (bitcpy == winsize) {
3169 /* ok window is filled so square as required and multiply */
3171 for (x = 0; x < winsize; x++) {
3172 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3175 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3181 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
3184 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3188 /* empty window and reset */
3195 /* if bits remain then square/multiply */
3196 if (mode == 2 && bitcpy > 0) {
3197 /* square then multiply if the bit is set */
3198 for (x = 0; x < bitcpy; x++) {
3199 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3202 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3206 /* get next bit of the window */
3208 if ((bitbuf & (1 << winsize)) != 0) {
3210 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
3213 if ((err = redux (&res, P, mp)) != MP_OKAY) {
3221 /* fixup result if Montgomery reduction is used
3222 * recall that any value in a Montgomery system is
3223 * actually multiplied by R mod n. So we have
3224 * to reduce one more time to cancel out the factor
3227 if ((err = redux(&res, P, mp)) != MP_OKAY) {
3232 /* swap res with Y */
3235 LBL_RES:mp_clear (&res);
3238 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
3246 #ifdef BN_FAST_S_MP_SQR_C
3247 /* the jist of squaring...
3248 * you do like mult except the offset of the tmpx [one that
3249 * starts closer to zero] can't equal the offset of tmpy.
3250 * So basically you set up iy like before then you min it with
3251 * (ty-tx) so that it never happens. You double all those
3252 * you add in the inner loop
3254 After that loop you do the squares and add them in.
3257 static int fast_s_mp_sqr (mp_int * a, mp_int * b)
3259 int olduse, res, pa, ix, iz;
3260 mp_digit W[MP_WARRAY], *tmpx;
3263 /* grow the destination as required */
3264 pa = a->used + a->used;
3265 if (b->alloc < pa) {
3266 if ((res = mp_grow (b, pa)) != MP_OKAY) {
3271 /* number of output digits to produce */
3273 for (ix = 0; ix < pa; ix++) {
3281 /* get offsets into the two bignums */
3282 ty = MIN(a->used-1, ix);
3285 /* setup temp aliases */
3289 /* this is the number of times the loop will iterrate, essentially
3290 while (tx++ < a->used && ty-- >= 0) { ... }
3292 iy = MIN(a->used-tx, ty+1);
3294 /* now for squaring tx can never equal ty
3295 * we halve the distance since they approach at a rate of 2x
3296 * and we have to round because odd cases need to be executed
3298 iy = MIN(iy, (ty-tx+1)>>1);
3301 for (iz = 0; iz < iy; iz++) {
3302 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
3305 /* double the inner product and add carry */
3308 /* even columns have the square term in them */
3310 _W += ((mp_word)a->dp[ix>>1])*((mp_word)a->dp[ix>>1]);
3314 W[ix] = (mp_digit)(_W & MP_MASK);
3316 /* make next carry */
3317 W1 = _W >> ((mp_word)DIGIT_BIT);
3322 b->used = a->used+a->used;
3327 for (ix = 0; ix < pa; ix++) {
3328 *tmpb++ = W[ix] & MP_MASK;
3331 /* clear unused digits [that existed in the old copy of c] */
3332 for (; ix < olduse; ix++) {
3342 #ifdef BN_MP_MUL_D_C
3343 /* multiply by a digit */
3345 mp_mul_d (mp_int * a, mp_digit b, mp_int * c)
3347 mp_digit u, *tmpa, *tmpc;
3349 int ix, res, olduse;
3351 /* make sure c is big enough to hold a*b */
3352 if (c->alloc < a->used + 1) {
3353 if ((res = mp_grow (c, a->used + 1)) != MP_OKAY) {
3358 /* get the original destinations used count */
3364 /* alias for a->dp [source] */
3367 /* alias for c->dp [dest] */
3373 /* compute columns */
3374 for (ix = 0; ix < a->used; ix++) {
3375 /* compute product and carry sum for this term */
3376 r = ((mp_word) u) + ((mp_word)*tmpa++) * ((mp_word)b);
3378 /* mask off higher bits to get a single digit */
3379 *tmpc++ = (mp_digit) (r & ((mp_word) MP_MASK));
3381 /* send carry into next iteration */
3382 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
3385 /* store final carry [if any] and increment ix offset */
3389 /* now zero digits above the top */
3390 while (ix++ < olduse) {
3394 /* set used count */
3395 c->used = a->used + 1;