2 * Minimal code for RSA support from LibTomMath 0.3.9
3 * http://math.libtomcrypt.com/
4 * http://math.libtomcrypt.com/files/ltm-0.39.tar.bz2
5 * This library was released in public domain by Tom St Denis.
7 * The combination in this file may not use all of the optimized algorithms
8 * from LibTomMath and may be considerable slower than the LibTomMath with its
9 * default settings. The main purpose of having this version here is to make it
10 * easier to build bignum.c wrapper without having to install and build an
13 * If CONFIG_INTERNAL_LIBTOMMATH is defined, bignum.c includes this
14 * libtommath.c file instead of using the external LibTomMath library.
21 #define BN_MP_INVMOD_C
22 #define BN_S_MP_EXPTMOD_C /* Note: #undef in tommath_superclass.h; this would
23 * require BN_MP_EXPTMOD_FAST_C instead */
24 #define BN_S_MP_MUL_DIGS_C
25 #define BN_MP_INVMOD_SLOW_C
27 #define BN_S_MP_MUL_HIGH_DIGS_C /* Note: #undef in tommath_superclass.h; this
28 * would require other than mp_reduce */
30 #ifdef LTM_FAST_EXPTMOD
31 /* Include faster exptmod (Montgomery) at the cost of about 2.5 kB in code */
32 #define BN_MP_EXPTMOD_FAST_C
33 #define BN_MP_MONTGOMERY_SETUP_C
34 #define BN_FAST_MP_MONTGOMERY_REDUCE_C
35 #define BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
37 #endif /* LTM_FAST_EXPTMOD */
40 /* Include faster sqr at the cost of about 0.5 kB in code */
41 #define BN_FAST_S_MP_SQR_C
42 #endif /* LTM_FAST_SQR */
44 /* Current uses do not require support for negative exponent in exptmod, so we
45 * can save about 1.5 kB in leaving out invmod. */
46 #define LTM_NO_NEG_EXP
51 #define MIN(x,y) ((x)<(y)?(x):(y))
55 #define MAX(x,y) ((x)>(y)?(x):(y))
60 typedef unsigned long mp_digit;
67 #define XMALLOC os_malloc
69 #define XREALLOC os_realloc
72 #define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))
74 #define MP_LT -1 /* less than */
75 #define MP_EQ 0 /* equal to */
76 #define MP_GT 1 /* greater than */
78 #define MP_ZPOS 0 /* positive integer */
79 #define MP_NEG 1 /* negative */
81 #define MP_OKAY 0 /* ok result */
82 #define MP_MEM -2 /* out of mem */
83 #define MP_VAL -3 /* invalid input */
85 #define MP_YES 1 /* yes response */
86 #define MP_NO 0 /* no response */
90 /* define this to use lower memory usage routines (exptmods mostly) */
93 /* default precision */
96 #define MP_PREC 32 /* default digits of precision */
98 #define MP_PREC 8 /* default digits of precision */
102 /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
103 #define MP_WARRAY (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1))
105 /* the infamous mp_int structure */
107 int used, alloc, sign;
112 /* ---> Basic Manipulations <--- */
113 #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
114 #define mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO)
115 #define mp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO)
118 /* prototypes for copied functions */
119 #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
120 static int s_mp_exptmod(mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode);
121 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
122 static int s_mp_sqr(mp_int * a, mp_int * b);
123 static int s_mp_mul_high_digs(mp_int * a, mp_int * b, mp_int * c, int digs);
125 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs);
127 static int mp_init_multi(mp_int *mp, ...);
128 static void mp_clear_multi(mp_int *mp, ...);
129 static int mp_lshd(mp_int * a, int b);
130 static void mp_set(mp_int * a, mp_digit b);
131 static void mp_clamp(mp_int * a);
132 static void mp_exch(mp_int * a, mp_int * b);
133 static void mp_rshd(mp_int * a, int b);
134 static void mp_zero(mp_int * a);
135 static int mp_mod_2d(mp_int * a, int b, mp_int * c);
136 static int mp_div_2d(mp_int * a, int b, mp_int * c, mp_int * d);
137 static int mp_init_copy(mp_int * a, mp_int * b);
138 static int mp_mul_2d(mp_int * a, int b, mp_int * c);
139 #ifndef LTM_NO_NEG_EXP
140 static int mp_div_2(mp_int * a, mp_int * b);
141 static int mp_invmod(mp_int * a, mp_int * b, mp_int * c);
142 static int mp_invmod_slow(mp_int * a, mp_int * b, mp_int * c);
143 #endif /* LTM_NO_NEG_EXP */
144 static int mp_copy(mp_int * a, mp_int * b);
145 static int mp_count_bits(mp_int * a);
146 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d);
147 static int mp_mod(mp_int * a, mp_int * b, mp_int * c);
148 static int mp_grow(mp_int * a, int size);
149 static int mp_cmp_mag(mp_int * a, mp_int * b);
150 static int mp_abs(mp_int * a, mp_int * b);
151 static int mp_sqr(mp_int * a, mp_int * b);
152 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d);
153 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d);
154 static int mp_2expt(mp_int * a, int b);
155 static int mp_reduce_setup(mp_int * a, mp_int * b);
156 static int mp_reduce(mp_int * x, mp_int * m, mp_int * mu);
157 static int mp_init_size(mp_int * a, int size);
158 #ifdef BN_MP_EXPTMOD_FAST_C
159 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode);
160 #endif /* BN_MP_EXPTMOD_FAST_C */
161 #ifdef BN_FAST_S_MP_SQR_C
162 static int fast_s_mp_sqr (mp_int * a, mp_int * b);
163 #endif /* BN_FAST_S_MP_SQR_C */
167 /* functions from bn_<func name>.c */
170 /* reverse an array, used for radix code */
171 static void bn_reverse (unsigned char *s, int len)
188 /* low level addition, based on HAC pp.594, Algorithm 14.7 */
189 static int s_mp_add (mp_int * a, mp_int * b, mp_int * c)
192 int olduse, res, min, max;
194 /* find sizes, we let |a| <= |b| which means we have to sort
195 * them. "x" will point to the input with the most digits
197 if (a->used > b->used) {
208 if (c->alloc < max + 1) {
209 if ((res = mp_grow (c, max + 1)) != MP_OKAY) {
214 /* get old used digit count and set new one */
219 register mp_digit u, *tmpa, *tmpb, *tmpc;
222 /* alias for digit pointers */
235 for (i = 0; i < min; i++) {
236 /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
237 *tmpc = *tmpa++ + *tmpb++ + u;
239 /* U = carry bit of T[i] */
240 u = *tmpc >> ((mp_digit)DIGIT_BIT);
242 /* take away carry bit from T[i] */
246 /* now copy higher words if any, that is in A+B
247 * if A or B has more digits add those in
250 for (; i < max; i++) {
251 /* T[i] = X[i] + U */
252 *tmpc = x->dp[i] + u;
254 /* U = carry bit of T[i] */
255 u = *tmpc >> ((mp_digit)DIGIT_BIT);
257 /* take away carry bit from T[i] */
265 /* clear digits above oldused */
266 for (i = c->used; i < olduse; i++) {
276 /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
277 static int s_mp_sub (mp_int * a, mp_int * b, mp_int * c)
279 int olduse, res, min, max;
286 if (c->alloc < max) {
287 if ((res = mp_grow (c, max)) != MP_OKAY) {
295 register mp_digit u, *tmpa, *tmpb, *tmpc;
298 /* alias for digit pointers */
303 /* set carry to zero */
305 for (i = 0; i < min; i++) {
306 /* T[i] = A[i] - B[i] - U */
307 *tmpc = *tmpa++ - *tmpb++ - u;
309 /* U = carry bit of T[i]
310 * Note this saves performing an AND operation since
311 * if a carry does occur it will propagate all the way to the
312 * MSB. As a result a single shift is enough to get the carry
314 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
316 /* Clear carry from T[i] */
320 /* now copy higher words if any, e.g. if A has more digits than B */
321 for (; i < max; i++) {
322 /* T[i] = A[i] - U */
325 /* U = carry bit of T[i] */
326 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
328 /* Clear carry from T[i] */
332 /* clear digits above used (since we may not have grown result above) */
333 for (i = c->used; i < olduse; i++) {
343 /* init a new mp_int */
344 static int mp_init (mp_int * a)
348 /* allocate memory required and clear it */
349 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * MP_PREC);
354 /* set the digits to zero */
355 for (i = 0; i < MP_PREC; i++) {
359 /* set the used to zero, allocated digits to the default precision
360 * and sign to positive */
369 /* clear one (frees) */
370 static void mp_clear (mp_int * a)
374 /* only do anything if a hasn't been freed previously */
376 /* first zero the digits */
377 for (i = 0; i < a->used; i++) {
384 /* reset members to make debugging easier */
386 a->alloc = a->used = 0;
392 /* high level addition (handles signs) */
393 static int mp_add (mp_int * a, mp_int * b, mp_int * c)
397 /* get sign of both inputs */
401 /* handle two cases, not four */
403 /* both positive or both negative */
404 /* add their magnitudes, copy the sign */
406 res = s_mp_add (a, b, c);
408 /* one positive, the other negative */
409 /* subtract the one with the greater magnitude from */
410 /* the one of the lesser magnitude. The result gets */
411 /* the sign of the one with the greater magnitude. */
412 if (mp_cmp_mag (a, b) == MP_LT) {
414 res = s_mp_sub (b, a, c);
417 res = s_mp_sub (a, b, c);
424 /* high level subtraction (handles signs) */
425 static int mp_sub (mp_int * a, mp_int * b, mp_int * c)
433 /* subtract a negative from a positive, OR */
434 /* subtract a positive from a negative. */
435 /* In either case, ADD their magnitudes, */
436 /* and use the sign of the first number. */
438 res = s_mp_add (a, b, c);
440 /* subtract a positive from a positive, OR */
441 /* subtract a negative from a negative. */
442 /* First, take the difference between their */
443 /* magnitudes, then... */
444 if (mp_cmp_mag (a, b) != MP_LT) {
445 /* Copy the sign from the first */
447 /* The first has a larger or equal magnitude */
448 res = s_mp_sub (a, b, c);
450 /* The result has the *opposite* sign from */
451 /* the first number. */
452 c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
453 /* The second has a larger magnitude */
454 res = s_mp_sub (b, a, c);
461 /* high level multiplication (handles sign) */
462 static int mp_mul (mp_int * a, mp_int * b, mp_int * c)
465 neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
468 #ifdef BN_MP_TOOM_MUL_C
469 if (MIN (a->used, b->used) >= TOOM_MUL_CUTOFF) {
470 res = mp_toom_mul(a, b, c);
473 #ifdef BN_MP_KARATSUBA_MUL_C
475 if (MIN (a->used, b->used) >= KARATSUBA_MUL_CUTOFF) {
476 res = mp_karatsuba_mul (a, b, c);
480 /* can we use the fast multiplier?
482 * The fast multiplier can be used if the output will
483 * have less than MP_WARRAY digits and the number of
484 * digits won't affect carry propagation
486 #ifdef BN_FAST_S_MP_MUL_DIGS_C
487 int digs = a->used + b->used + 1;
489 if ((digs < MP_WARRAY) &&
490 MIN(a->used, b->used) <=
491 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
492 res = fast_s_mp_mul_digs (a, b, c, digs);
495 #ifdef BN_S_MP_MUL_DIGS_C
496 res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */
498 #error mp_mul could fail
503 c->sign = (c->used > 0) ? neg : MP_ZPOS;
508 /* d = a * b (mod c) */
509 static int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
514 if ((res = mp_init (&t)) != MP_OKAY) {
518 if ((res = mp_mul (a, b, &t)) != MP_OKAY) {
522 res = mp_mod (&t, c, d);
528 /* c = a mod b, 0 <= c < b */
529 static int mp_mod (mp_int * a, mp_int * b, mp_int * c)
534 if ((res = mp_init (&t)) != MP_OKAY) {
538 if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) {
543 if (t.sign != b->sign) {
544 res = mp_add (b, &t, c);
555 /* this is a shell function that calls either the normal or Montgomery
556 * exptmod functions. Originally the call to the montgomery code was
557 * embedded in the normal function but that wasted alot of stack space
558 * for nothing (since 99% of the time the Montgomery code would be called)
560 static int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
564 /* modulus P must be positive */
565 if (P->sign == MP_NEG) {
569 /* if exponent X is negative we have to recurse */
570 if (X->sign == MP_NEG) {
571 #ifdef LTM_NO_NEG_EXP
573 #else /* LTM_NO_NEG_EXP */
574 #ifdef BN_MP_INVMOD_C
578 /* first compute 1/G mod P */
579 if ((err = mp_init(&tmpG)) != MP_OKAY) {
582 if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
588 if ((err = mp_init(&tmpX)) != MP_OKAY) {
592 if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
593 mp_clear_multi(&tmpG, &tmpX, NULL);
597 /* and now compute (1/G)**|X| instead of G**X [X < 0] */
598 err = mp_exptmod(&tmpG, &tmpX, P, Y);
599 mp_clear_multi(&tmpG, &tmpX, NULL);
602 #error mp_exptmod would always fail
606 #endif /* LTM_NO_NEG_EXP */
609 /* modified diminished radix reduction */
610 #if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && defined(BN_S_MP_EXPTMOD_C)
611 if (mp_reduce_is_2k_l(P) == MP_YES) {
612 return s_mp_exptmod(G, X, P, Y, 1);
616 #ifdef BN_MP_DR_IS_MODULUS_C
617 /* is it a DR modulus? */
618 dr = mp_dr_is_modulus(P);
624 #ifdef BN_MP_REDUCE_IS_2K_C
625 /* if not, is it a unrestricted DR modulus? */
627 dr = mp_reduce_is_2k(P) << 1;
631 /* if the modulus is odd or dr != 0 use the montgomery method */
632 #ifdef BN_MP_EXPTMOD_FAST_C
633 if (mp_isodd (P) == 1 || dr != 0) {
634 return mp_exptmod_fast (G, X, P, Y, dr);
637 #ifdef BN_S_MP_EXPTMOD_C
638 /* otherwise use the generic Barrett reduction technique */
639 return s_mp_exptmod (G, X, P, Y, 0);
641 #error mp_exptmod could fail
642 /* no exptmod for evens */
645 #ifdef BN_MP_EXPTMOD_FAST_C
651 /* compare two ints (signed)*/
652 static int mp_cmp (mp_int * a, mp_int * b)
654 /* compare based on sign */
655 if (a->sign != b->sign) {
656 if (a->sign == MP_NEG) {
664 if (a->sign == MP_NEG) {
665 /* if negative compare opposite direction */
666 return mp_cmp_mag(b, a);
668 return mp_cmp_mag(a, b);
673 /* compare a digit */
674 static int mp_cmp_d(mp_int * a, mp_digit b)
676 /* compare based on sign */
677 if (a->sign == MP_NEG) {
681 /* compare based on magnitude */
686 /* compare the only digit of a to b */
689 } else if (a->dp[0] < b) {
697 #ifndef LTM_NO_NEG_EXP
698 /* hac 14.61, pp608 */
699 static int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
701 /* b cannot be negative */
702 if (b->sign == MP_NEG || mp_iszero(b) == 1) {
706 #ifdef BN_FAST_MP_INVMOD_C
707 /* if the modulus is odd we can use a faster routine instead */
708 if (mp_isodd (b) == 1) {
709 return fast_mp_invmod (a, b, c);
713 #ifdef BN_MP_INVMOD_SLOW_C
714 return mp_invmod_slow(a, b, c);
717 #ifndef BN_FAST_MP_INVMOD_C
718 #ifndef BN_MP_INVMOD_SLOW_C
719 #error mp_invmod would always fail
724 #endif /* LTM_NO_NEG_EXP */
727 /* get the size for an unsigned equivalent */
728 static int mp_unsigned_bin_size (mp_int * a)
730 int size = mp_count_bits (a);
731 return (size / 8 + ((size & 7) != 0 ? 1 : 0));
735 #ifndef LTM_NO_NEG_EXP
736 /* hac 14.61, pp608 */
737 static int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c)
739 mp_int x, y, u, v, A, B, C, D;
742 /* b cannot be negative */
743 if (b->sign == MP_NEG || mp_iszero(b) == 1) {
748 if ((res = mp_init_multi(&x, &y, &u, &v,
749 &A, &B, &C, &D, NULL)) != MP_OKAY) {
754 if ((res = mp_mod(a, b, &x)) != MP_OKAY) {
757 if ((res = mp_copy (b, &y)) != MP_OKAY) {
761 /* 2. [modified] if x,y are both even then return an error! */
762 if (mp_iseven (&x) == 1 && mp_iseven (&y) == 1) {
767 /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
768 if ((res = mp_copy (&x, &u)) != MP_OKAY) {
771 if ((res = mp_copy (&y, &v)) != MP_OKAY) {
778 /* 4. while u is even do */
779 while (mp_iseven (&u) == 1) {
781 if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
784 /* 4.2 if A or B is odd then */
785 if (mp_isodd (&A) == 1 || mp_isodd (&B) == 1) {
786 /* A = (A+y)/2, B = (B-x)/2 */
787 if ((res = mp_add (&A, &y, &A)) != MP_OKAY) {
790 if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
794 /* A = A/2, B = B/2 */
795 if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
798 if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
803 /* 5. while v is even do */
804 while (mp_iseven (&v) == 1) {
806 if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
809 /* 5.2 if C or D is odd then */
810 if (mp_isodd (&C) == 1 || mp_isodd (&D) == 1) {
811 /* C = (C+y)/2, D = (D-x)/2 */
812 if ((res = mp_add (&C, &y, &C)) != MP_OKAY) {
815 if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
819 /* C = C/2, D = D/2 */
820 if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
823 if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
828 /* 6. if u >= v then */
829 if (mp_cmp (&u, &v) != MP_LT) {
830 /* u = u - v, A = A - C, B = B - D */
831 if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
835 if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
839 if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
843 /* v - v - u, C = C - A, D = D - B */
844 if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
848 if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
852 if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
857 /* if not zero goto step 4 */
858 if (mp_iszero (&u) == 0)
861 /* now a = C, b = D, gcd == g*v */
863 /* if v != 1 then there is no inverse */
864 if (mp_cmp_d (&v, 1) != MP_EQ) {
870 while (mp_cmp_d(&C, 0) == MP_LT) {
871 if ((res = mp_add(&C, b, &C)) != MP_OKAY) {
877 while (mp_cmp_mag(&C, b) != MP_LT) {
878 if ((res = mp_sub(&C, b, &C)) != MP_OKAY) {
883 /* C is now the inverse */
886 LBL_ERR:mp_clear_multi (&x, &y, &u, &v, &A, &B, &C, &D, NULL);
889 #endif /* LTM_NO_NEG_EXP */
892 /* compare maginitude of two ints (unsigned) */
893 static int mp_cmp_mag (mp_int * a, mp_int * b)
896 mp_digit *tmpa, *tmpb;
898 /* compare based on # of non-zero digits */
899 if (a->used > b->used) {
903 if (a->used < b->used) {
908 tmpa = a->dp + (a->used - 1);
911 tmpb = b->dp + (a->used - 1);
913 /* compare based on digits */
914 for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
927 /* reads a unsigned char array, assumes the msb is stored first [big endian] */
928 static int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
932 /* make sure there are at least two digits */
934 if ((res = mp_grow(a, 2)) != MP_OKAY) {
942 /* read the bytes in */
944 if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) {
952 a->dp[0] = (*b & MP_MASK);
953 a->dp[1] |= ((*b++ >> 7U) & 1);
962 /* store in unsigned [big endian] format */
963 static int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
968 if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
973 while (mp_iszero (&t) == 0) {
975 b[x++] = (unsigned char) (t.dp[0] & 255);
977 b[x++] = (unsigned char) (t.dp[0] | ((t.dp[1] & 0x01) << 7));
979 if ((res = mp_div_2d (&t, 8, &t, NULL)) != MP_OKAY) {
990 /* shift right by a certain bit count (store quotient in c, optional remainder in d) */
991 static int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
998 /* if the shift count is <= 0 then we do no work */
1000 res = mp_copy (a, c);
1007 if ((res = mp_init (&t)) != MP_OKAY) {
1011 /* get the remainder */
1013 if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
1020 if ((res = mp_copy (a, c)) != MP_OKAY) {
1025 /* shift by as many digits in the bit count */
1026 if (b >= (int)DIGIT_BIT) {
1027 mp_rshd (c, b / DIGIT_BIT);
1030 /* shift any bit count < DIGIT_BIT */
1031 D = (mp_digit) (b % DIGIT_BIT);
1033 register mp_digit *tmpc, mask, shift;
1036 mask = (((mp_digit)1) << D) - 1;
1039 shift = DIGIT_BIT - D;
1042 tmpc = c->dp + (c->used - 1);
1046 for (x = c->used - 1; x >= 0; x--) {
1047 /* get the lower bits of this word in a temp */
1050 /* shift the current word and mix in the carry bits from the previous word */
1051 *tmpc = (*tmpc >> D) | (r << shift);
1054 /* set the carry to the carry bits of the current word found above */
1067 static int mp_init_copy (mp_int * a, mp_int * b)
1071 if ((res = mp_init (a)) != MP_OKAY) {
1074 return mp_copy (b, a);
1079 static void mp_zero (mp_int * a)
1088 for (n = 0; n < a->alloc; n++) {
1095 static int mp_copy (mp_int * a, mp_int * b)
1099 /* if dst == src do nothing */
1105 if (b->alloc < a->used) {
1106 if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1111 /* zero b and copy the parameters over */
1113 register mp_digit *tmpa, *tmpb;
1115 /* pointer aliases */
1123 /* copy all the digits */
1124 for (n = 0; n < a->used; n++) {
1128 /* clear high digits */
1129 for (; n < b->used; n++) {
1134 /* copy used count and sign */
1141 /* shift right a certain amount of digits */
1142 static void mp_rshd (mp_int * a, int b)
1146 /* if b <= 0 then ignore it */
1151 /* if b > used then simply zero it and return */
1158 register mp_digit *bottom, *top;
1160 /* shift the digits down */
1165 /* top [offset into digits] */
1168 /* this is implemented as a sliding window where
1169 * the window is b-digits long and digits from
1170 * the top of the window are copied to the bottom
1174 b-2 | b-1 | b0 | b1 | b2 | ... | bb | ---->
1176 \-------------------/ ---->
1178 for (x = 0; x < (a->used - b); x++) {
1182 /* zero the top digits */
1183 for (; x < a->used; x++) {
1188 /* remove excess digits */
1193 /* swap the elements of two integers, for cases where you can't simply swap the
1194 * mp_int pointers around
1196 static void mp_exch (mp_int * a, mp_int * b)
1206 /* trim unused digits
1208 * This is used to ensure that leading zero digits are
1209 * trimed and the leading "used" digit will be non-zero
1210 * Typically very fast. Also fixes the sign if there
1211 * are no more leading digits
1213 static void mp_clamp (mp_int * a)
1215 /* decrease used while the most significant digit is
1218 while (a->used > 0 && a->dp[a->used - 1] == 0) {
1222 /* reset the sign flag if used == 0 */
1229 /* grow as required */
1230 static int mp_grow (mp_int * a, int size)
1235 /* if the alloc size is smaller alloc more ram */
1236 if (a->alloc < size) {
1237 /* ensure there are always at least MP_PREC digits extra on top */
1238 size += (MP_PREC * 2) - (size % MP_PREC);
1240 /* reallocate the array a->dp
1242 * We store the return in a temporary variable
1243 * in case the operation failed we don't want
1244 * to overwrite the dp member of a.
1246 tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size);
1248 /* reallocation failed but "a" is still valid [can be freed] */
1252 /* reallocation succeeded so set a->dp */
1255 /* zero excess digits */
1258 for (; i < a->alloc; i++) {
1268 * Simple function copies the input and fixes the sign to positive
1270 static int mp_abs (mp_int * a, mp_int * b)
1276 if ((res = mp_copy (a, b)) != MP_OKAY) {
1281 /* force the sign of b to positive */
1288 /* set to a digit */
1289 static void mp_set (mp_int * a, mp_digit b)
1292 a->dp[0] = b & MP_MASK;
1293 a->used = (a->dp[0] != 0) ? 1 : 0;
1297 #ifndef LTM_NO_NEG_EXP
1299 static int mp_div_2(mp_int * a, mp_int * b)
1301 int x, res, oldused;
1304 if (b->alloc < a->used) {
1305 if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1313 register mp_digit r, rr, *tmpa, *tmpb;
1316 tmpa = a->dp + b->used - 1;
1319 tmpb = b->dp + b->used - 1;
1323 for (x = b->used - 1; x >= 0; x--) {
1324 /* get the carry for the next iteration */
1327 /* shift the current digit, add in carry and store */
1328 *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
1330 /* forward carry to next iteration */
1334 /* zero excess digits */
1335 tmpb = b->dp + b->used;
1336 for (x = b->used; x < oldused; x++) {
1344 #endif /* LTM_NO_NEG_EXP */
1347 /* shift left by a certain bit count */
1348 static int mp_mul_2d (mp_int * a, int b, mp_int * c)
1355 if ((res = mp_copy (a, c)) != MP_OKAY) {
1360 if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) {
1361 if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) {
1366 /* shift by as many digits in the bit count */
1367 if (b >= (int)DIGIT_BIT) {
1368 if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) {
1373 /* shift any bit count < DIGIT_BIT */
1374 d = (mp_digit) (b % DIGIT_BIT);
1376 register mp_digit *tmpc, shift, mask, r, rr;
1379 /* bitmask for carries */
1380 mask = (((mp_digit)1) << d) - 1;
1382 /* shift for msbs */
1383 shift = DIGIT_BIT - d;
1390 for (x = 0; x < c->used; x++) {
1391 /* get the higher bits of the current word */
1392 rr = (*tmpc >> shift) & mask;
1394 /* shift the current word and OR in the carry */
1395 *tmpc = ((*tmpc << d) | r) & MP_MASK;
1398 /* set the carry to the carry bits of the current word */
1402 /* set final carry */
1404 c->dp[(c->used)++] = r;
1412 static int mp_init_multi(mp_int *mp, ...)
1414 mp_err res = MP_OKAY; /* Assume ok until proven otherwise */
1415 int n = 0; /* Number of ok inits */
1416 mp_int* cur_arg = mp;
1419 va_start(args, mp); /* init args to next argument from caller */
1420 while (cur_arg != NULL) {
1421 if (mp_init(cur_arg) != MP_OKAY) {
1422 /* Oops - error! Back-track and mp_clear what we already
1423 succeeded in init-ing, then return error.
1427 /* end the current list */
1430 /* now start cleaning up */
1432 va_start(clean_args, mp);
1435 cur_arg = va_arg(clean_args, mp_int*);
1442 cur_arg = va_arg(args, mp_int*);
1445 return res; /* Assumed ok, if error flagged above. */
1449 static void mp_clear_multi(mp_int *mp, ...)
1451 mp_int* next_mp = mp;
1454 while (next_mp != NULL) {
1456 next_mp = va_arg(args, mp_int*);
1462 /* shift left a certain amount of digits */
1463 static int mp_lshd (mp_int * a, int b)
1467 /* if its less than zero return */
1472 /* grow to fit the new digits */
1473 if (a->alloc < a->used + b) {
1474 if ((res = mp_grow (a, a->used + b)) != MP_OKAY) {
1480 register mp_digit *top, *bottom;
1482 /* increment the used by the shift amount then copy upwards */
1486 top = a->dp + a->used - 1;
1489 bottom = a->dp + a->used - 1 - b;
1491 /* much like mp_rshd this is implemented using a sliding window
1492 * except the window goes the otherway around. Copying from
1493 * the bottom to the top. see bn_mp_rshd.c for more info.
1495 for (x = a->used - 1; x >= b; x--) {
1499 /* zero the lower digits */
1501 for (x = 0; x < b; x++) {
1509 /* returns the number of bits in an int */
1510 static int mp_count_bits (mp_int * a)
1520 /* get number of digits and add that */
1521 r = (a->used - 1) * DIGIT_BIT;
1523 /* take the last digit and count the bits in it */
1524 q = a->dp[a->used - 1];
1525 while (q > ((mp_digit) 0)) {
1527 q >>= ((mp_digit) 1);
1533 /* calc a value mod 2**b */
1534 static int mp_mod_2d (mp_int * a, int b, mp_int * c)
1538 /* if b is <= 0 then zero the int */
1544 /* if the modulus is larger than the value than return */
1545 if (b >= (int) (a->used * DIGIT_BIT)) {
1546 res = mp_copy (a, c);
1551 if ((res = mp_copy (a, c)) != MP_OKAY) {
1555 /* zero digits above the last digit of the modulus */
1556 for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x++) {
1559 /* clear the digit that is not completely outside/inside the modulus */
1560 c->dp[b / DIGIT_BIT] &=
1561 (mp_digit) ((((mp_digit) 1) << (((mp_digit) b) % DIGIT_BIT)) - ((mp_digit) 1));
1567 /* slower bit-bang division... also smaller */
1568 static int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d)
1570 mp_int ta, tb, tq, q;
1573 /* is divisor zero ? */
1574 if (mp_iszero (b) == 1) {
1578 /* if a < b then q=0, r = a */
1579 if (mp_cmp_mag (a, b) == MP_LT) {
1581 res = mp_copy (a, d);
1591 /* init our temps */
1592 if ((res = mp_init_multi(&ta, &tb, &tq, &q, NULL) != MP_OKAY)) {
1598 n = mp_count_bits(a) - mp_count_bits(b);
1599 if (((res = mp_abs(a, &ta)) != MP_OKAY) ||
1600 ((res = mp_abs(b, &tb)) != MP_OKAY) ||
1601 ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) ||
1602 ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) {
1607 if (mp_cmp(&tb, &ta) != MP_GT) {
1608 if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) ||
1609 ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) {
1613 if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) ||
1614 ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) {
1619 /* now q == quotient and ta == remainder */
1621 n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG);
1624 c->sign = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2;
1628 d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n;
1631 mp_clear_multi(&ta, &tb, &tq, &q, NULL);
1639 #define TAB_SIZE 256
1642 static int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
1644 mp_int M[TAB_SIZE], res, mu;
1646 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
1647 int (*redux)(mp_int*,mp_int*,mp_int*);
1649 /* find window size */
1650 x = mp_count_bits (X);
1653 } else if (x <= 36) {
1655 } else if (x <= 140) {
1657 } else if (x <= 450) {
1659 } else if (x <= 1303) {
1661 } else if (x <= 3529) {
1674 /* init first cell */
1675 if ((err = mp_init(&M[1])) != MP_OKAY) {
1679 /* now init the second half of the array */
1680 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
1681 if ((err = mp_init(&M[x])) != MP_OKAY) {
1682 for (y = 1<<(winsize-1); y < x; y++) {
1690 /* create mu, used for Barrett reduction */
1691 if ((err = mp_init (&mu)) != MP_OKAY) {
1696 if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) {
1701 if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) {
1704 redux = mp_reduce_2k_l;
1709 * The M table contains powers of the base,
1710 * e.g. M[x] = G**x mod P
1712 * The first half of the table is not
1713 * computed though accept for M[0] and M[1]
1715 if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) {
1719 /* compute the value at M[1<<(winsize-1)] by squaring
1720 * M[1] (winsize-1) times
1722 if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
1726 for (x = 0; x < (winsize - 1); x++) {
1728 if ((err = mp_sqr (&M[1 << (winsize - 1)],
1729 &M[1 << (winsize - 1)])) != MP_OKAY) {
1733 /* reduce modulo P */
1734 if ((err = redux (&M[1 << (winsize - 1)], P, &mu)) != MP_OKAY) {
1739 /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
1740 * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
1742 for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
1743 if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
1746 if ((err = redux (&M[x], P, &mu)) != MP_OKAY) {
1752 if ((err = mp_init (&res)) != MP_OKAY) {
1757 /* set initial mode and bit cnt */
1761 digidx = X->used - 1;
1766 /* grab next digit as required */
1767 if (--bitcnt == 0) {
1768 /* if digidx == -1 we are out of digits */
1772 /* read next digit and reset the bitcnt */
1773 buf = X->dp[digidx--];
1774 bitcnt = (int) DIGIT_BIT;
1777 /* grab the next msb from the exponent */
1778 y = (buf >> (mp_digit)(DIGIT_BIT - 1)) & 1;
1779 buf <<= (mp_digit)1;
1781 /* if the bit is zero and mode == 0 then we ignore it
1782 * These represent the leading zero bits before the first 1 bit
1783 * in the exponent. Technically this opt is not required but it
1784 * does lower the # of trivial squaring/reductions used
1786 if (mode == 0 && y == 0) {
1790 /* if the bit is zero and mode == 1 then we square */
1791 if (mode == 1 && y == 0) {
1792 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
1795 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1801 /* else we add it to the window */
1802 bitbuf |= (y << (winsize - ++bitcpy));
1805 if (bitcpy == winsize) {
1806 /* ok window is filled so square as required and multiply */
1808 for (x = 0; x < winsize; x++) {
1809 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
1812 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1818 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
1821 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1825 /* empty window and reset */
1832 /* if bits remain then square/multiply */
1833 if (mode == 2 && bitcpy > 0) {
1834 /* square then multiply if the bit is set */
1835 for (x = 0; x < bitcpy; x++) {
1836 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
1839 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1844 if ((bitbuf & (1 << winsize)) != 0) {
1846 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
1849 if ((err = redux (&res, P, &mu)) != MP_OKAY) {
1858 LBL_RES:mp_clear (&res);
1859 LBL_MU:mp_clear (&mu);
1862 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
1869 /* computes b = a*a */
1870 static int mp_sqr (mp_int * a, mp_int * b)
1874 #ifdef BN_MP_TOOM_SQR_C
1875 /* use Toom-Cook? */
1876 if (a->used >= TOOM_SQR_CUTOFF) {
1877 res = mp_toom_sqr(a, b);
1881 #ifdef BN_MP_KARATSUBA_SQR_C
1882 if (a->used >= KARATSUBA_SQR_CUTOFF) {
1883 res = mp_karatsuba_sqr (a, b);
1887 #ifdef BN_FAST_S_MP_SQR_C
1888 /* can we use the fast comba multiplier? */
1889 if ((a->used * 2 + 1) < MP_WARRAY &&
1891 (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) {
1892 res = fast_s_mp_sqr (a, b);
1895 #ifdef BN_S_MP_SQR_C
1896 res = s_mp_sqr (a, b);
1898 #error mp_sqr could fail
1907 /* reduces a modulo n where n is of the form 2**p - d
1908 This differs from reduce_2k since "d" can be larger
1909 than a single digit.
1911 static int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
1916 if ((res = mp_init(&q)) != MP_OKAY) {
1920 p = mp_count_bits(n);
1922 /* q = a/2**p, a = a mod 2**p */
1923 if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
1928 if ((res = mp_mul(&q, d, &q)) != MP_OKAY) {
1933 if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
1937 if (mp_cmp_mag(a, n) != MP_LT) {
1948 /* determines the setup value */
1949 static int mp_reduce_2k_setup_l(mp_int *a, mp_int *d)
1954 if ((res = mp_init(&tmp)) != MP_OKAY) {
1958 if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
1962 if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
1972 /* computes a = 2**b
1974 * Simple algorithm which zeroes the int, grows it then just sets one bit
1977 static int mp_2expt (mp_int * a, int b)
1981 /* zero a as per default */
1984 /* grow a to accomodate the single bit */
1985 if ((res = mp_grow (a, b / DIGIT_BIT + 1)) != MP_OKAY) {
1989 /* set the used count of where the bit will go */
1990 a->used = b / DIGIT_BIT + 1;
1992 /* put the single bit in its place */
1993 a->dp[b / DIGIT_BIT] = ((mp_digit)1) << (b % DIGIT_BIT);
1999 /* pre-calculate the value required for Barrett reduction
2000 * For a given modulus "b" it calulates the value required in "a"
2002 static int mp_reduce_setup (mp_int * a, mp_int * b)
2006 if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) {
2009 return mp_div (a, b, a, NULL);
2013 /* reduces x mod m, assumes 0 < x < m**2, mu is
2014 * precomputed via mp_reduce_setup.
2015 * From HAC pp.604 Algorithm 14.42
2017 static int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
2020 int res, um = m->used;
2023 if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
2027 /* q1 = x / b**(k-1) */
2028 mp_rshd (&q, um - 1);
2030 /* according to HAC this optimization is ok */
2031 if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) {
2032 if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) {
2036 #ifdef BN_S_MP_MUL_HIGH_DIGS_C
2037 if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
2040 #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C)
2041 if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
2046 #error mp_reduce would always fail
2053 /* q3 = q2 / b**(k+1) */
2054 mp_rshd (&q, um + 1);
2056 /* x = x mod b**(k+1), quick (no division) */
2057 if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
2061 /* q = q * m mod b**(k+1), quick (no division) */
2062 if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) {
2067 if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
2071 /* If x < 0, add b**(k+1) to it */
2072 if (mp_cmp_d (x, 0) == MP_LT) {
2074 if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) {
2077 if ((res = mp_add (x, &q, x)) != MP_OKAY) {
2082 /* Back off if it's too big */
2083 while (mp_cmp (x, m) != MP_LT) {
2084 if ((res = s_mp_sub (x, m, x)) != MP_OKAY) {
2096 /* multiplies |a| * |b| and only computes upto digs digits of result
2097 * HAC pp. 595, Algorithm 14.12 Modified so you can control how
2098 * many digits of output are created.
2100 static int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2103 int res, pa, pb, ix, iy;
2106 mp_digit tmpx, *tmpt, *tmpy;
2108 /* can we use the fast multiplier? */
2109 if (((digs) < MP_WARRAY) &&
2110 MIN (a->used, b->used) <
2111 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2112 return fast_s_mp_mul_digs (a, b, c, digs);
2115 if ((res = mp_init_size (&t, digs)) != MP_OKAY) {
2120 /* compute the digits of the product directly */
2122 for (ix = 0; ix < pa; ix++) {
2123 /* set the carry to zero */
2126 /* limit ourselves to making digs digits of output */
2127 pb = MIN (b->used, digs - ix);
2129 /* setup some aliases */
2130 /* copy of the digit from a used within the nested loop */
2133 /* an alias for the destination shifted ix places */
2136 /* an alias for the digits of b */
2139 /* compute the columns of the output and propagate the carry */
2140 for (iy = 0; iy < pb; iy++) {
2141 /* compute the column as a mp_word */
2142 r = ((mp_word)*tmpt) +
2143 ((mp_word)tmpx) * ((mp_word)*tmpy++) +
2146 /* the new column is the lower part of the result */
2147 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2149 /* get the carry word from the result */
2150 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2152 /* set carry if it is placed below digs */
2153 if (ix + iy < digs) {
2166 /* Fast (comba) multiplier
2168 * This is the fast column-array [comba] multiplier. It is
2169 * designed to compute the columns of the product first
2170 * then handle the carries afterwards. This has the effect
2171 * of making the nested loops that compute the columns very
2172 * simple and schedulable on super-scalar processors.
2174 * This has been modified to produce a variable number of
2175 * digits of output so if say only a half-product is required
2176 * you don't have to compute the upper half (a feature
2177 * required for fast Barrett reduction).
2179 * Based on Algorithm 14.12 on pp.595 of HAC.
2182 static int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2184 int olduse, res, pa, ix, iz;
2185 mp_digit W[MP_WARRAY];
2186 register mp_word _W;
2188 /* grow the destination as required */
2189 if (c->alloc < digs) {
2190 if ((res = mp_grow (c, digs)) != MP_OKAY) {
2195 /* number of output digits to produce */
2196 pa = MIN(digs, a->used + b->used);
2198 /* clear the carry */
2200 for (ix = 0; ix < pa; ix++) {
2203 mp_digit *tmpx, *tmpy;
2205 /* get offsets into the two bignums */
2206 ty = MIN(b->used-1, ix);
2209 /* setup temp aliases */
2213 /* this is the number of times the loop will iterrate, essentially
2214 while (tx++ < a->used && ty-- >= 0) { ... }
2216 iy = MIN(a->used-tx, ty+1);
2219 for (iz = 0; iz < iy; ++iz) {
2220 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
2225 W[ix] = ((mp_digit)_W) & MP_MASK;
2227 /* make next carry */
2228 _W = _W >> ((mp_word)DIGIT_BIT);
2236 register mp_digit *tmpc;
2238 for (ix = 0; ix < pa+1; ix++) {
2239 /* now extract the previous digit [below the carry] */
2243 /* clear unused digits [that existed in the old copy of c] */
2244 for (; ix < olduse; ix++) {
2253 /* init an mp_init for a given size */
2254 static int mp_init_size (mp_int * a, int size)
2258 /* pad size so there are always extra digits */
2259 size += (MP_PREC * 2) - (size % MP_PREC);
2262 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size);
2263 if (a->dp == NULL) {
2267 /* set the members */
2272 /* zero the digits */
2273 for (x = 0; x < size; x++) {
2281 /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
2282 static int s_mp_sqr (mp_int * a, mp_int * b)
2285 int res, ix, iy, pa;
2287 mp_digit u, tmpx, *tmpt;
2290 if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
2294 /* default used is maximum possible size */
2297 for (ix = 0; ix < pa; ix++) {
2298 /* first calculate the digit at 2*ix */
2299 /* calculate double precision result */
2300 r = ((mp_word) t.dp[2*ix]) +
2301 ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]);
2303 /* store lower part in result */
2304 t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
2307 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2309 /* left hand side of A[ix] * A[iy] */
2312 /* alias for where to store the results */
2313 tmpt = t.dp + (2*ix + 1);
2315 for (iy = ix + 1; iy < pa; iy++) {
2316 /* first calculate the product */
2317 r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
2319 /* now calculate the double precision result, note we use
2320 * addition instead of *2 since it's easier to optimize
2322 r = ((mp_word) *tmpt) + r + r + ((mp_word) u);
2324 /* store lower part */
2325 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2328 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2330 /* propagate upwards */
2331 while (u != ((mp_digit) 0)) {
2332 r = ((mp_word) *tmpt) + ((mp_word) u);
2333 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2334 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2345 /* multiplies |a| * |b| and does not compute the lower digs digits
2346 * [meant to get the higher part of the product]
2348 static int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
2351 int res, pa, pb, ix, iy;
2354 mp_digit tmpx, *tmpt, *tmpy;
2356 /* can we use the fast multiplier? */
2357 #ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C
2358 if (((a->used + b->used + 1) < MP_WARRAY)
2359 && MIN (a->used, b->used) < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2360 return fast_s_mp_mul_high_digs (a, b, c, digs);
2364 if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) {
2367 t.used = a->used + b->used + 1;
2371 for (ix = 0; ix < pa; ix++) {
2372 /* clear the carry */
2375 /* left hand side of A[ix] * B[iy] */
2378 /* alias to the address of where the digits will be stored */
2379 tmpt = &(t.dp[digs]);
2381 /* alias for where to read the right hand side from */
2382 tmpy = b->dp + (digs - ix);
2384 for (iy = digs - ix; iy < pb; iy++) {
2385 /* calculate the double precision result */
2386 r = ((mp_word)*tmpt) +
2387 ((mp_word)tmpx) * ((mp_word)*tmpy++) +
2390 /* get the lower part */
2391 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
2393 /* carry the carry */
2394 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
2405 #ifdef BN_MP_MONTGOMERY_SETUP_C
2406 /* setups the montgomery reduction stuff */
2408 mp_montgomery_setup (mp_int * n, mp_digit * rho)
2412 /* fast inversion mod 2**k
2414 * Based on the fact that
2416 * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
2417 * => 2*X*A - X*X*A*A = 1
2418 * => 2*(1) - (1) = 1
2426 x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
2427 x *= 2 - b * x; /* here x*a==1 mod 2**8 */
2428 #if !defined(MP_8BIT)
2429 x *= 2 - b * x; /* here x*a==1 mod 2**16 */
2431 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
2432 x *= 2 - b * x; /* here x*a==1 mod 2**32 */
2435 x *= 2 - b * x; /* here x*a==1 mod 2**64 */
2438 /* rho = -1/m mod b */
2439 *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK;
2446 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2447 /* computes xR**-1 == x (mod N) via Montgomery Reduction
2449 * This is an optimized implementation of montgomery_reduce
2450 * which uses the comba method to quickly calculate the columns of the
2453 * Based on Algorithm 14.32 on pp.601 of HAC.
2455 int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
2457 int ix, res, olduse;
2458 mp_word W[MP_WARRAY];
2460 /* get old used count */
2463 /* grow a as required */
2464 if (x->alloc < n->used + 1) {
2465 if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) {
2470 /* first we have to get the digits of the input into
2471 * an array of double precision words W[...]
2474 register mp_word *_W;
2475 register mp_digit *tmpx;
2477 /* alias for the W[] array */
2480 /* alias for the digits of x*/
2483 /* copy the digits of a into W[0..a->used-1] */
2484 for (ix = 0; ix < x->used; ix++) {
2488 /* zero the high words of W[a->used..m->used*2] */
2489 for (; ix < n->used * 2 + 1; ix++) {
2494 /* now we proceed to zero successive digits
2495 * from the least significant upwards
2497 for (ix = 0; ix < n->used; ix++) {
2498 /* mu = ai * m' mod b
2500 * We avoid a double precision multiplication (which isn't required)
2501 * by casting the value down to a mp_digit. Note this requires
2502 * that W[ix-1] have the carry cleared (see after the inner loop)
2504 register mp_digit mu;
2505 mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK);
2507 /* a = a + mu * m * b**i
2509 * This is computed in place and on the fly. The multiplication
2510 * by b**i is handled by offseting which columns the results
2513 * Note the comba method normally doesn't handle carries in the
2514 * inner loop In this case we fix the carry from the previous
2515 * column since the Montgomery reduction requires digits of the
2516 * result (so far) [see above] to work. This is
2517 * handled by fixing up one carry after the inner loop. The
2518 * carry fixups are done in order so after these loops the
2519 * first m->used words of W[] have the carries fixed
2523 register mp_digit *tmpn;
2524 register mp_word *_W;
2526 /* alias for the digits of the modulus */
2529 /* Alias for the columns set by an offset of ix */
2533 for (iy = 0; iy < n->used; iy++) {
2534 *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++);
2538 /* now fix carry for next digit, W[ix+1] */
2539 W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT);
2542 /* now we have to propagate the carries and
2543 * shift the words downward [all those least
2544 * significant digits we zeroed].
2547 register mp_digit *tmpx;
2548 register mp_word *_W, *_W1;
2550 /* nox fix rest of carries */
2552 /* alias for current word */
2555 /* alias for next word, where the carry goes */
2558 for (; ix <= n->used * 2 + 1; ix++) {
2559 *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT);
2562 /* copy out, A = A/b**n
2564 * The result is A/b**n but instead of converting from an
2565 * array of mp_word to mp_digit than calling mp_rshd
2566 * we just copy them in the right order
2569 /* alias for destination word */
2572 /* alias for shifted double precision result */
2575 for (ix = 0; ix < n->used + 1; ix++) {
2576 *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK));
2579 /* zero oldused digits, if the input a was larger than
2580 * m->used+1 we'll have to clear the digits
2582 for (; ix < olduse; ix++) {
2587 /* set the max used and clamp */
2588 x->used = n->used + 1;
2591 /* if A >= m then A = A - m */
2592 if (mp_cmp_mag (x, n) != MP_LT) {
2593 return s_mp_sub (x, n, x);
2600 #ifdef BN_MP_MUL_2_C
2602 static int mp_mul_2(mp_int * a, mp_int * b)
2604 int x, res, oldused;
2606 /* grow to accomodate result */
2607 if (b->alloc < a->used + 1) {
2608 if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) {
2617 register mp_digit r, rr, *tmpa, *tmpb;
2619 /* alias for source */
2622 /* alias for dest */
2627 for (x = 0; x < a->used; x++) {
2629 /* get what will be the *next* carry bit from the
2630 * MSB of the current digit
2632 rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1));
2634 /* now shift up this digit, add in the carry [from the previous] */
2635 *tmpb++ = ((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK;
2637 /* copy the carry that would be from the source
2638 * digit into the next iteration
2643 /* new leading digit? */
2645 /* add a MSB which is always 1 at this point */
2650 /* now zero any excess digits on the destination
2651 * that we didn't write to
2653 tmpb = b->dp + b->used;
2654 for (x = b->used; x < oldused; x++) {
2664 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
2666 * shifts with subtractions when the result is greater than b.
2668 * The method is slightly modified to shift B unconditionally upto just under
2669 * the leading bit of b. This saves alot of multiple precision shifting.
2671 static int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
2675 /* how many bits of last digit does b use */
2676 bits = mp_count_bits (b) % DIGIT_BIT;
2679 if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) {
2688 /* now compute C = A * B mod b */
2689 for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
2690 if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
2693 if (mp_cmp_mag (a, b) != MP_LT) {
2694 if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
2705 #ifdef BN_MP_EXPTMOD_FAST_C
2706 /* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
2708 * Uses a left-to-right k-ary sliding window to compute the modular exponentiation.
2709 * The value of k changes based on the size of the exponent.
2711 * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
2714 static int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
2716 mp_int M[TAB_SIZE], res;
2718 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
2720 /* use a pointer to the reduction algorithm. This allows us to use
2721 * one of many reduction algorithms without modding the guts of
2722 * the code with if statements everywhere.
2724 int (*redux)(mp_int*,mp_int*,mp_digit);
2726 /* find window size */
2727 x = mp_count_bits (X);
2730 } else if (x <= 36) {
2732 } else if (x <= 140) {
2734 } else if (x <= 450) {
2736 } else if (x <= 1303) {
2738 } else if (x <= 3529) {
2751 /* init first cell */
2752 if ((err = mp_init(&M[1])) != MP_OKAY) {
2756 /* now init the second half of the array */
2757 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
2758 if ((err = mp_init(&M[x])) != MP_OKAY) {
2759 for (y = 1<<(winsize-1); y < x; y++) {
2767 /* determine and setup reduction code */
2769 #ifdef BN_MP_MONTGOMERY_SETUP_C
2770 /* now setup montgomery */
2771 if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
2779 /* automatically pick the comba one if available (saves quite a few calls/ifs) */
2780 #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2781 if (((P->used * 2 + 1) < MP_WARRAY) &&
2782 P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2783 redux = fast_mp_montgomery_reduce;
2787 #ifdef BN_MP_MONTGOMERY_REDUCE_C
2788 /* use slower baseline Montgomery method */
2789 redux = mp_montgomery_reduce;
2795 } else if (redmode == 1) {
2796 #if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C)
2797 /* setup DR reduction for moduli of the form B**k - b */
2798 mp_dr_setup(P, &mp);
2799 redux = mp_dr_reduce;
2805 #if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C)
2806 /* setup DR reduction for moduli of the form 2**k - b */
2807 if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) {
2810 redux = mp_reduce_2k;
2818 if ((err = mp_init (&res)) != MP_OKAY) {
2826 * The first half of the table is not computed though accept for M[0] and M[1]
2830 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
2831 /* now we need R mod m */
2832 if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) {
2840 /* now set M[1] to G * R mod m */
2841 if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
2846 if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
2851 /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times */
2852 if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) {
2856 for (x = 0; x < (winsize - 1); x++) {
2857 if ((err = mp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)])) != MP_OKAY) {
2860 if ((err = redux (&M[1 << (winsize - 1)], P, mp)) != MP_OKAY) {
2865 /* create upper table */
2866 for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
2867 if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
2870 if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
2875 /* set initial mode and bit cnt */
2879 digidx = X->used - 1;
2884 /* grab next digit as required */
2885 if (--bitcnt == 0) {
2886 /* if digidx == -1 we are out of digits so break */
2890 /* read next digit and reset bitcnt */
2891 buf = X->dp[digidx--];
2892 bitcnt = (int)DIGIT_BIT;
2895 /* grab the next msb from the exponent */
2896 y = (mp_digit)(buf >> (DIGIT_BIT - 1)) & 1;
2897 buf <<= (mp_digit)1;
2899 /* if the bit is zero and mode == 0 then we ignore it
2900 * These represent the leading zero bits before the first 1 bit
2901 * in the exponent. Technically this opt is not required but it
2902 * does lower the # of trivial squaring/reductions used
2904 if (mode == 0 && y == 0) {
2908 /* if the bit is zero and mode == 1 then we square */
2909 if (mode == 1 && y == 0) {
2910 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2913 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2919 /* else we add it to the window */
2920 bitbuf |= (y << (winsize - ++bitcpy));
2923 if (bitcpy == winsize) {
2924 /* ok window is filled so square as required and multiply */
2926 for (x = 0; x < winsize; x++) {
2927 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2930 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2936 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
2939 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2943 /* empty window and reset */
2950 /* if bits remain then square/multiply */
2951 if (mode == 2 && bitcpy > 0) {
2952 /* square then multiply if the bit is set */
2953 for (x = 0; x < bitcpy; x++) {
2954 if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2957 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2961 /* get next bit of the window */
2963 if ((bitbuf & (1 << winsize)) != 0) {
2965 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
2968 if ((err = redux (&res, P, mp)) != MP_OKAY) {
2976 /* fixup result if Montgomery reduction is used
2977 * recall that any value in a Montgomery system is
2978 * actually multiplied by R mod n. So we have
2979 * to reduce one more time to cancel out the factor
2982 if ((err = redux(&res, P, mp)) != MP_OKAY) {
2987 /* swap res with Y */
2990 LBL_RES:mp_clear (&res);
2993 for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
3001 #ifdef BN_FAST_S_MP_SQR_C
3002 /* the jist of squaring...
3003 * you do like mult except the offset of the tmpx [one that
3004 * starts closer to zero] can't equal the offset of tmpy.
3005 * So basically you set up iy like before then you min it with
3006 * (ty-tx) so that it never happens. You double all those
3007 * you add in the inner loop
3009 After that loop you do the squares and add them in.
3012 static int fast_s_mp_sqr (mp_int * a, mp_int * b)
3014 int olduse, res, pa, ix, iz;
3015 mp_digit W[MP_WARRAY], *tmpx;
3018 /* grow the destination as required */
3019 pa = a->used + a->used;
3020 if (b->alloc < pa) {
3021 if ((res = mp_grow (b, pa)) != MP_OKAY) {
3026 /* number of output digits to produce */
3028 for (ix = 0; ix < pa; ix++) {
3036 /* get offsets into the two bignums */
3037 ty = MIN(a->used-1, ix);
3040 /* setup temp aliases */
3044 /* this is the number of times the loop will iterrate, essentially
3045 while (tx++ < a->used && ty-- >= 0) { ... }
3047 iy = MIN(a->used-tx, ty+1);
3049 /* now for squaring tx can never equal ty
3050 * we halve the distance since they approach at a rate of 2x
3051 * and we have to round because odd cases need to be executed
3053 iy = MIN(iy, (ty-tx+1)>>1);
3056 for (iz = 0; iz < iy; iz++) {
3057 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
3060 /* double the inner product and add carry */
3063 /* even columns have the square term in them */
3065 _W += ((mp_word)a->dp[ix>>1])*((mp_word)a->dp[ix>>1]);
3069 W[ix] = (mp_digit)(_W & MP_MASK);
3071 /* make next carry */
3072 W1 = _W >> ((mp_word)DIGIT_BIT);
3077 b->used = a->used+a->used;
3082 for (ix = 0; ix < pa; ix++) {
3083 *tmpb++ = W[ix] & MP_MASK;
3086 /* clear unused digits [that existed in the old copy of c] */
3087 for (; ix < olduse; ix++) {