1 /* $NetBSD: mpi.c,v 1.1.1.3 2014/04/24 12:45:39 pettai Exp $ */
6 by Michael J. Fromberger <sting@linguist.dartmouth.edu>
7 Copyright (C) 1998 Michael J. Fromberger, All Rights Reserved
9 Arbitrary precision integer arithmetic library
11 Id: mpi.c,v 1.2 2005/05/05 14:38:47 tom Exp
22 #define DIAG(T,V) {fprintf(stderr,T);mp_print(V,stderr);fputc('\n',stderr);}
28 If MP_LOGTAB is not defined, use the math library to compute the
29 logarithms on the fly. Otherwise, use the static table below.
30 Pick which works best for your system.
34 /* {{{ s_logv_2[] - log table for 2 in various bases */
37 A table of the logs of 2 for various bases (the 0 and 1 entries of
38 this table are meaningless and should not be referenced).
40 This table is used to compute output lengths for the mp_toradix()
41 function. Since a number n in radix r takes up about log_r(n)
42 digits, we estimate the output size by taking the least integer
43 greater than log_r(n), where:
45 log_r(n) = log_2(n) * log_r(2)
47 This table, therefore, is a table of log_r(2) for 2 <= r <= 36,
48 which are the output bases supported.
54 #define LOG_V_2(R) s_logv_2[(R)]
59 #define LOG_V_2(R) (log(2.0)/log(R))
63 /* Default precision for newly created mp_int's */
64 static unsigned int s_mp_defprec
= MP_DEFPREC
;
66 /* {{{ Digit arithmetic macros */
69 When adding and multiplying digits, the results can be larger than
70 can be contained in an mp_digit. Thus, an mp_word is used. These
71 macros mask off the upper and lower digits of the mp_word (the
72 mp_word may be more than 2 mp_digits wide, but we only concern
73 ourselves with the low-order 2 mp_digits)
75 If your mp_word DOES have more than 2 mp_digits, you need to
76 uncomment the first line, and comment out the second.
79 /* #define CARRYOUT(W) (((W)>>DIGIT_BIT)&MP_DIGIT_MAX) */
80 #define CARRYOUT(W) ((W)>>DIGIT_BIT)
81 #define ACCUM(W) ((W)&MP_DIGIT_MAX)
85 /* {{{ Comparison constants */
93 /* {{{ Constant strings */
95 /* Constant strings returned by mp_strerror() */
96 static const char *mp_err_string
[] = {
97 "unknown result code", /* say what? */
98 "boolean true", /* MP_OKAY, MP_YES */
99 "boolean false", /* MP_NO */
100 "out of memory", /* MP_MEM */
101 "argument out of range", /* MP_RANGE */
102 "invalid input parameter", /* MP_BADARG */
103 "result is undefined" /* MP_UNDEF */
106 /* Value to digit maps for radix conversion */
108 /* s_dmap_1 - standard digits and letters */
109 static const char *s_dmap_1
=
110 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
113 /* s_dmap_2 - base64 ordering for digits */
114 static const char *s_dmap_2
=
115 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
120 /* {{{ Static function declarations */
123 If MP_MACRO is false, these will be defined as actual functions;
124 otherwise, suitable macro definitions will be used. This works
125 around the fact that ANSI C89 doesn't support an 'inline' keyword
126 (although I hear C9x will ... about bloody time). At present, the
127 macro definitions are identical to the function bodies, but they'll
128 expand in place, instead of generating a function call.
130 I chose these particular functions to be made into macros because
131 some profiling showed they are called a lot on a typical workload,
132 and yet they are primarily housekeeping.
135 void s_mp_setz(mp_digit
*dp
, mp_size count
); /* zero digits */
136 void s_mp_copy(mp_digit
*sp
, mp_digit
*dp
, mp_size count
); /* copy */
137 void *s_mp_alloc(size_t nb
, size_t ni
); /* general allocator */
138 void s_mp_free(void *ptr
); /* general free function */
141 /* Even if these are defined as macros, we need to respect the settings
142 of the MP_MEMSET and MP_MEMCPY configuration options...
145 #define s_mp_setz(dp, count) \
146 {int ix;for(ix=0;ix<(count);ix++)(dp)[ix]=0;}
148 #define s_mp_setz(dp, count) memset(dp, 0, (count) * sizeof(mp_digit))
149 #endif /* MP_MEMSET */
152 #define s_mp_copy(sp, dp, count) \
153 {int ix;for(ix=0;ix<(count);ix++)(dp)[ix]=(sp)[ix];}
155 #define s_mp_copy(sp, dp, count) memcpy(dp, sp, (count) * sizeof(mp_digit))
156 #endif /* MP_MEMCPY */
158 #define s_mp_alloc(nb, ni) calloc(nb, ni)
159 #define s_mp_free(ptr) {if(ptr) free(ptr);}
160 #endif /* MP_MACRO */
162 mp_err
s_mp_grow(mp_int
*mp
, mp_size min
); /* increase allocated size */
163 mp_err
s_mp_pad(mp_int
*mp
, mp_size min
); /* left pad with zeroes */
165 void s_mp_clamp(mp_int
*mp
); /* clip leading zeroes */
167 void s_mp_exch(mp_int
*a
, mp_int
*b
); /* swap a and b in place */
169 mp_err
s_mp_lshd(mp_int
*mp
, mp_size p
); /* left-shift by p digits */
170 void s_mp_rshd(mp_int
*mp
, mp_size p
); /* right-shift by p digits */
171 void s_mp_div_2d(mp_int
*mp
, mp_digit d
); /* divide by 2^d in place */
172 void s_mp_mod_2d(mp_int
*mp
, mp_digit d
); /* modulo 2^d in place */
173 mp_err
s_mp_mul_2d(mp_int
*mp
, mp_digit d
); /* multiply by 2^d in place*/
174 void s_mp_div_2(mp_int
*mp
); /* divide by 2 in place */
175 mp_err
s_mp_mul_2(mp_int
*mp
); /* multiply by 2 in place */
176 mp_digit
s_mp_norm(mp_int
*a
, mp_int
*b
); /* normalize for division */
177 mp_err
s_mp_add_d(mp_int
*mp
, mp_digit d
); /* unsigned digit addition */
178 mp_err
s_mp_sub_d(mp_int
*mp
, mp_digit d
); /* unsigned digit subtract */
179 mp_err
s_mp_mul_d(mp_int
*mp
, mp_digit d
); /* unsigned digit multiply */
180 mp_err
s_mp_div_d(mp_int
*mp
, mp_digit d
, mp_digit
*r
);
181 /* unsigned digit divide */
182 mp_err
s_mp_reduce(mp_int
*x
, mp_int
*m
, mp_int
*mu
);
183 /* Barrett reduction */
184 mp_err
s_mp_add(mp_int
*a
, mp_int
*b
); /* magnitude addition */
185 mp_err
s_mp_sub(mp_int
*a
, mp_int
*b
); /* magnitude subtract */
186 mp_err
s_mp_mul(mp_int
*a
, mp_int
*b
); /* magnitude multiply */
188 void s_mp_kmul(mp_digit
*a
, mp_digit
*b
, mp_digit
*out
, mp_size len
);
189 /* multiply buffers in place */
192 mp_err
s_mp_sqr(mp_int
*a
); /* magnitude square */
194 #define s_mp_sqr(a) s_mp_mul(a, a)
196 mp_err
s_mp_div(mp_int
*a
, mp_int
*b
); /* magnitude divide */
197 mp_err
s_mp_2expt(mp_int
*a
, mp_digit k
); /* a = 2^k */
198 int s_mp_cmp(mp_int
*a
, mp_int
*b
); /* magnitude comparison */
199 int s_mp_cmp_d(mp_int
*a
, mp_digit d
); /* magnitude digit compare */
200 int s_mp_ispow2(mp_int
*v
); /* is v a power of 2? */
201 int s_mp_ispow2d(mp_digit d
); /* is d a power of 2? */
203 int s_mp_tovalue(char ch
, int r
); /* convert ch to value */
204 char s_mp_todigit(int val
, int r
, int low
); /* convert val to digit */
205 int s_mp_outlen(int bits
, int r
); /* output length in bytes */
209 /* {{{ Default precision manipulation */
211 unsigned int mp_get_prec(void)
215 } /* end mp_get_prec() */
217 void mp_set_prec(unsigned int prec
)
220 s_mp_defprec
= MP_DEFPREC
;
224 } /* end mp_set_prec() */
228 /*------------------------------------------------------------------------*/
229 /* {{{ mp_init(mp) */
234 Initialize a new zero-valued mp_int. Returns MP_OKAY if successful,
235 MP_MEM if memory could not be allocated for the structure.
238 mp_err
mp_init(mp_int
*mp
)
240 return mp_init_size(mp
, s_mp_defprec
);
242 } /* end mp_init() */
246 /* {{{ mp_init_array(mp[], count) */
248 mp_err
mp_init_array(mp_int mp
[], int count
)
253 ARGCHK(mp
!=NULL
&& count
> 0, MP_BADARG
);
255 for(pos
= 0; pos
< count
; ++pos
) {
256 if((res
= mp_init(&mp
[pos
])) != MP_OKAY
)
268 } /* end mp_init_array() */
272 /* {{{ mp_init_size(mp, prec) */
275 mp_init_size(mp, prec)
277 Initialize a new zero-valued mp_int with at least the given
278 precision; returns MP_OKAY if successful, or MP_MEM if memory could
279 not be allocated for the structure.
282 mp_err
mp_init_size(mp_int
*mp
, mp_size prec
)
284 ARGCHK(mp
!= NULL
&& prec
> 0, MP_BADARG
);
286 if((DIGITS(mp
) = s_mp_alloc(prec
, sizeof(mp_digit
))) == NULL
)
295 } /* end mp_init_size() */
299 /* {{{ mp_init_copy(mp, from) */
302 mp_init_copy(mp, from)
304 Initialize mp as an exact copy of from. Returns MP_OKAY if
305 successful, MP_MEM if memory could not be allocated for the new
309 mp_err
mp_init_copy(mp_int
*mp
, mp_int
*from
)
311 ARGCHK(mp
!= NULL
&& from
!= NULL
, MP_BADARG
);
316 if((DIGITS(mp
) = s_mp_alloc(USED(from
), sizeof(mp_digit
))) == NULL
)
319 s_mp_copy(DIGITS(from
), DIGITS(mp
), USED(from
));
320 USED(mp
) = USED(from
);
321 ALLOC(mp
) = USED(from
);
322 SIGN(mp
) = SIGN(from
);
326 } /* end mp_init_copy() */
330 /* {{{ mp_copy(from, to) */
335 Copies the mp_int 'from' to the mp_int 'to'. It is presumed that
336 'to' has already been initialized (if not, use mp_init_copy()
337 instead). If 'from' and 'to' are identical, nothing happens.
340 mp_err
mp_copy(mp_int
*from
, mp_int
*to
)
342 ARGCHK(from
!= NULL
&& to
!= NULL
, MP_BADARG
);
351 If the allocated buffer in 'to' already has enough space to hold
352 all the used digits of 'from', we'll re-use it to avoid hitting
353 the memory allocater more than necessary; otherwise, we'd have
354 to grow anyway, so we just allocate a hunk and make the copy as
357 if(ALLOC(to
) >= USED(from
)) {
358 s_mp_setz(DIGITS(to
) + USED(from
), ALLOC(to
) - USED(from
));
359 s_mp_copy(DIGITS(from
), DIGITS(to
), USED(from
));
362 if((tmp
= s_mp_alloc(USED(from
), sizeof(mp_digit
))) == NULL
)
365 s_mp_copy(DIGITS(from
), tmp
, USED(from
));
367 if(DIGITS(to
) != NULL
) {
369 s_mp_setz(DIGITS(to
), ALLOC(to
));
371 s_mp_free(DIGITS(to
));
375 ALLOC(to
) = USED(from
);
378 /* Copy the precision and sign from the original */
379 USED(to
) = USED(from
);
380 SIGN(to
) = SIGN(from
);
385 } /* end mp_copy() */
389 /* {{{ mp_exch(mp1, mp2) */
394 Exchange mp1 and mp2 without allocating any intermediate memory
395 (well, unless you count the stack space needed for this call and the
396 locals it creates...). This cannot fail.
399 void mp_exch(mp_int
*mp1
, mp_int
*mp2
)
402 assert(mp1
!= NULL
&& mp2
!= NULL
);
404 if(mp1
== NULL
|| mp2
== NULL
)
410 } /* end mp_exch() */
414 /* {{{ mp_clear(mp) */
419 Release the storage used by an mp_int, and void its fields so that
420 if someone calls mp_clear() again for the same int later, we won't
424 void mp_clear(mp_int
*mp
)
429 if(DIGITS(mp
) != NULL
) {
431 s_mp_setz(DIGITS(mp
), ALLOC(mp
));
433 s_mp_free(DIGITS(mp
));
440 } /* end mp_clear() */
444 /* {{{ mp_clear_array(mp[], count) */
446 void mp_clear_array(mp_int mp
[], int count
)
448 ARGCHK(mp
!= NULL
&& count
> 0, MP_BADARG
);
451 mp_clear(&mp
[count
]);
453 } /* end mp_clear_array() */
457 /* {{{ mp_zero(mp) */
462 Set mp to zero. Does not change the allocated size of the structure,
463 and therefore cannot fail (except on a bad argument, which we ignore)
465 void mp_zero(mp_int
*mp
)
470 s_mp_setz(DIGITS(mp
), ALLOC(mp
));
474 } /* end mp_zero() */
478 /* {{{ mp_set(mp, d) */
480 void mp_set(mp_int
*mp
, mp_digit d
)
492 /* {{{ mp_set_int(mp, z) */
494 mp_err
mp_set_int(mp_int
*mp
, long z
)
497 unsigned long v
= abs(z
);
500 ARGCHK(mp
!= NULL
, MP_BADARG
);
504 return MP_OKAY
; /* shortcut for zero */
506 for(ix
= sizeof(long) - 1; ix
>= 0; ix
--) {
508 if((res
= s_mp_mul_2d(mp
, CHAR_BIT
)) != MP_OKAY
)
512 (mp_digit
)((v
>> (ix
* CHAR_BIT
)) & UCHAR_MAX
));
523 } /* end mp_set_int() */
527 /*------------------------------------------------------------------------*/
528 /* {{{ Digit arithmetic */
530 /* {{{ mp_add_d(a, d, b) */
535 Compute the sum b = a + d, for a single digit d. Respects the sign of
536 its primary addend (single digits are unsigned anyway).
539 mp_err
mp_add_d(mp_int
*a
, mp_digit d
, mp_int
*b
)
541 mp_err res
= MP_OKAY
;
543 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_BADARG
);
545 if((res
= mp_copy(a
, b
)) != MP_OKAY
)
548 if(SIGN(b
) == MP_ZPOS
) {
549 res
= s_mp_add_d(b
, d
);
550 } else if(s_mp_cmp_d(b
, d
) >= 0) {
551 res
= s_mp_sub_d(b
, d
);
555 DIGIT(b
, 0) = d
- DIGIT(b
, 0);
560 } /* end mp_add_d() */
564 /* {{{ mp_sub_d(a, d, b) */
569 Compute the difference b = a - d, for a single digit d. Respects the
570 sign of its subtrahend (single digits are unsigned anyway).
573 mp_err
mp_sub_d(mp_int
*a
, mp_digit d
, mp_int
*b
)
577 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_BADARG
);
579 if((res
= mp_copy(a
, b
)) != MP_OKAY
)
582 if(SIGN(b
) == MP_NEG
) {
583 if((res
= s_mp_add_d(b
, d
)) != MP_OKAY
)
586 } else if(s_mp_cmp_d(b
, d
) >= 0) {
587 if((res
= s_mp_sub_d(b
, d
)) != MP_OKAY
)
593 DIGIT(b
, 0) = d
- DIGIT(b
, 0);
597 if(s_mp_cmp_d(b
, 0) == 0)
602 } /* end mp_sub_d() */
606 /* {{{ mp_mul_d(a, d, b) */
611 Compute the product b = a * d, for a single digit d. Respects the sign
612 of its multiplicand (single digits are unsigned anyway)
615 mp_err
mp_mul_d(mp_int
*a
, mp_digit d
, mp_int
*b
)
619 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_BADARG
);
626 if((res
= mp_copy(a
, b
)) != MP_OKAY
)
629 res
= s_mp_mul_d(b
, d
);
633 } /* end mp_mul_d() */
637 /* {{{ mp_mul_2(a, c) */
639 mp_err
mp_mul_2(mp_int
*a
, mp_int
*c
)
643 ARGCHK(a
!= NULL
&& c
!= NULL
, MP_BADARG
);
645 if((res
= mp_copy(a
, c
)) != MP_OKAY
)
648 return s_mp_mul_2(c
);
650 } /* end mp_mul_2() */
654 /* {{{ mp_div_d(a, d, q, r) */
659 Compute the quotient q = a / d and remainder r = a mod d, for a
660 single digit d. Respects the sign of its divisor (single digits are
664 mp_err
mp_div_d(mp_int
*a
, mp_digit d
, mp_int
*q
, mp_digit
*r
)
670 ARGCHK(a
!= NULL
, MP_BADARG
);
675 /* Shortcut for powers of two ... */
676 if((pow
= s_mp_ispow2d(d
)) >= 0) {
679 mask
= (1 << pow
) - 1;
680 rem
= DIGIT(a
, 0) & mask
;
694 If the quotient is actually going to be returned, we'll try to
695 avoid hitting the memory allocator by copying the dividend into it
696 and doing the division there. This can't be any _worse_ than
697 always copying, and will sometimes be better (since it won't make
700 If it's not going to be returned, we need to allocate a temporary
701 to hold the quotient, which will just be discarded.
704 if((res
= mp_copy(a
, q
)) != MP_OKAY
)
707 res
= s_mp_div_d(q
, d
, &rem
);
708 if(s_mp_cmp_d(q
, 0) == MP_EQ
)
714 if((res
= mp_init_copy(&qp
, a
)) != MP_OKAY
)
717 res
= s_mp_div_d(&qp
, d
, &rem
);
718 if(s_mp_cmp_d(&qp
, 0) == 0)
729 } /* end mp_div_d() */
733 /* {{{ mp_div_2(a, c) */
738 Compute c = a / 2, disregarding the remainder.
741 mp_err
mp_div_2(mp_int
*a
, mp_int
*c
)
745 ARGCHK(a
!= NULL
&& c
!= NULL
, MP_BADARG
);
747 if((res
= mp_copy(a
, c
)) != MP_OKAY
)
754 } /* end mp_div_2() */
758 /* {{{ mp_expt_d(a, d, b) */
760 mp_err
mp_expt_d(mp_int
*a
, mp_digit d
, mp_int
*c
)
765 ARGCHK(a
!= NULL
&& c
!= NULL
, MP_BADARG
);
767 if((res
= mp_init(&s
)) != MP_OKAY
)
769 if((res
= mp_init_copy(&x
, a
)) != MP_OKAY
)
776 if((res
= s_mp_mul(&s
, &x
)) != MP_OKAY
)
782 if((res
= s_mp_sqr(&x
)) != MP_OKAY
)
795 } /* end mp_expt_d() */
801 /*------------------------------------------------------------------------*/
802 /* {{{ Full arithmetic */
804 /* {{{ mp_abs(a, b) */
809 Compute b = |a|. 'a' and 'b' may be identical.
812 mp_err
mp_abs(mp_int
*a
, mp_int
*b
)
816 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_BADARG
);
818 if((res
= mp_copy(a
, b
)) != MP_OKAY
)
829 /* {{{ mp_neg(a, b) */
834 Compute b = -a. 'a' and 'b' may be identical.
837 mp_err
mp_neg(mp_int
*a
, mp_int
*b
)
841 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_BADARG
);
843 if((res
= mp_copy(a
, b
)) != MP_OKAY
)
846 if(s_mp_cmp_d(b
, 0) == MP_EQ
)
849 SIGN(b
) = (SIGN(b
) == MP_NEG
) ? MP_ZPOS
: MP_NEG
;
857 /* {{{ mp_add(a, b, c) */
862 Compute c = a + b. All parameters may be identical.
865 mp_err
mp_add(mp_int
*a
, mp_int
*b
, mp_int
*c
)
870 ARGCHK(a
!= NULL
&& b
!= NULL
&& c
!= NULL
, MP_BADARG
);
872 if(SIGN(a
) == SIGN(b
)) { /* same sign: add values, keep sign */
874 /* Commutativity of addition lets us do this in either order,
875 so we avoid having to use a temporary even if the result
876 is supposed to replace the output
879 if((res
= s_mp_add(c
, a
)) != MP_OKAY
)
882 if(c
!= a
&& (res
= mp_copy(a
, c
)) != MP_OKAY
)
885 if((res
= s_mp_add(c
, b
)) != MP_OKAY
)
889 } else if((cmp
= s_mp_cmp(a
, b
)) > 0) { /* different sign: a > b */
891 /* If the output is going to be clobbered, we will use a temporary
892 variable; otherwise, we'll do it without touching the memory
893 allocator at all, if possible
898 if((res
= mp_init_copy(&tmp
, a
)) != MP_OKAY
)
900 if((res
= s_mp_sub(&tmp
, b
)) != MP_OKAY
) {
910 if(c
!= a
&& (res
= mp_copy(a
, c
)) != MP_OKAY
)
912 if((res
= s_mp_sub(c
, b
)) != MP_OKAY
)
917 } else if(cmp
== 0) { /* different sign, a == b */
922 } else { /* different sign: a < b */
928 if((res
= mp_init_copy(&tmp
, b
)) != MP_OKAY
)
930 if((res
= s_mp_sub(&tmp
, a
)) != MP_OKAY
) {
940 if(c
!= b
&& (res
= mp_copy(b
, c
)) != MP_OKAY
)
942 if((res
= s_mp_sub(c
, a
)) != MP_OKAY
)
948 if(USED(c
) == 1 && DIGIT(c
, 0) == 0)
957 /* {{{ mp_sub(a, b, c) */
962 Compute c = a - b. All parameters may be identical.
965 mp_err
mp_sub(mp_int
*a
, mp_int
*b
, mp_int
*c
)
970 ARGCHK(a
!= NULL
&& b
!= NULL
&& c
!= NULL
, MP_BADARG
);
972 if(SIGN(a
) != SIGN(b
)) {
974 if((res
= s_mp_add(c
, b
)) != MP_OKAY
)
977 if(c
!= b
&& ((res
= mp_copy(b
, c
)) != MP_OKAY
))
979 if((res
= s_mp_add(c
, a
)) != MP_OKAY
)
984 } else if((cmp
= s_mp_cmp(a
, b
)) > 0) { /* Same sign, a > b */
988 if((res
= mp_init_copy(&tmp
, a
)) != MP_OKAY
)
990 if((res
= s_mp_sub(&tmp
, b
)) != MP_OKAY
) {
998 if(c
!= a
&& ((res
= mp_copy(a
, c
)) != MP_OKAY
))
1001 if((res
= s_mp_sub(c
, b
)) != MP_OKAY
)
1005 } else if(cmp
== 0) { /* Same sign, equal magnitude */
1009 } else { /* Same sign, b > a */
1013 if((res
= mp_init_copy(&tmp
, b
)) != MP_OKAY
)
1016 if((res
= s_mp_sub(&tmp
, a
)) != MP_OKAY
) {
1024 if(c
!= b
&& ((res
= mp_copy(b
, c
)) != MP_OKAY
))
1027 if((res
= s_mp_sub(c
, a
)) != MP_OKAY
)
1034 if(USED(c
) == 1 && DIGIT(c
, 0) == 0)
1039 } /* end mp_sub() */
1043 /* {{{ mp_mul(a, b, c) */
1048 Compute c = a * b. All parameters may be identical.
1051 mp_err
mp_mul(mp_int
*a
, mp_int
*b
, mp_int
*c
)
1056 ARGCHK(a
!= NULL
&& b
!= NULL
&& c
!= NULL
, MP_BADARG
);
1058 sgn
= (SIGN(a
) == SIGN(b
)) ? MP_ZPOS
: MP_NEG
;
1061 if((res
= s_mp_mul(c
, a
)) != MP_OKAY
)
1065 if((res
= mp_copy(a
, c
)) != MP_OKAY
)
1068 if((res
= s_mp_mul(c
, b
)) != MP_OKAY
)
1072 if(sgn
== MP_ZPOS
|| s_mp_cmp_d(c
, 0) == MP_EQ
)
1079 } /* end mp_mul() */
1083 /* {{{ mp_mul_2d(a, d, c) */
1088 Compute c = a * 2^d. a may be the same as c.
1091 mp_err
mp_mul_2d(mp_int
*a
, mp_digit d
, mp_int
*c
)
1095 ARGCHK(a
!= NULL
&& c
!= NULL
, MP_BADARG
);
1097 if((res
= mp_copy(a
, c
)) != MP_OKAY
)
1103 return s_mp_mul_2d(c
, d
);
1105 } /* end mp_mul() */
1109 /* {{{ mp_sqr(a, b) */
1112 mp_err
mp_sqr(mp_int
*a
, mp_int
*b
)
1116 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_BADARG
);
1118 if((res
= mp_copy(a
, b
)) != MP_OKAY
)
1121 if((res
= s_mp_sqr(b
)) != MP_OKAY
)
1128 } /* end mp_sqr() */
1133 /* {{{ mp_div(a, b, q, r) */
1138 Compute q = a / b and r = a mod b. Input parameters may be re-used
1139 as output parameters. If q or r is NULL, that portion of the
1140 computation will be discarded (although it will still be computed)
1142 Pay no attention to the hacker behind the curtain.
1145 mp_err
mp_div(mp_int
*a
, mp_int
*b
, mp_int
*q
, mp_int
*r
)
1151 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_BADARG
);
1153 if(mp_cmp_z(b
) == MP_EQ
)
1156 /* If a <= b, we can compute the solution without division, and
1157 avoid any memory allocation
1159 if((cmp
= s_mp_cmp(a
, b
)) < 0) {
1161 if((res
= mp_copy(a
, r
)) != MP_OKAY
)
1170 } else if(cmp
== 0) {
1172 /* Set quotient to 1, with appropriate sign */
1174 int qneg
= (SIGN(a
) != SIGN(b
));
1187 /* If we get here, it means we actually have to do some division */
1189 /* Set up some temporaries... */
1190 if((res
= mp_init_copy(&qtmp
, a
)) != MP_OKAY
)
1192 if((res
= mp_init_copy(&rtmp
, b
)) != MP_OKAY
)
1195 if((res
= s_mp_div(&qtmp
, &rtmp
)) != MP_OKAY
)
1198 /* Compute the signs for the output */
1199 SIGN(&rtmp
) = SIGN(a
); /* Sr = Sa */
1200 if(SIGN(a
) == SIGN(b
))
1201 SIGN(&qtmp
) = MP_ZPOS
; /* Sq = MP_ZPOS if Sa = Sb */
1203 SIGN(&qtmp
) = MP_NEG
; /* Sq = MP_NEG if Sa != Sb */
1205 if(s_mp_cmp_d(&qtmp
, 0) == MP_EQ
)
1206 SIGN(&qtmp
) = MP_ZPOS
;
1207 if(s_mp_cmp_d(&rtmp
, 0) == MP_EQ
)
1208 SIGN(&rtmp
) = MP_ZPOS
;
1210 /* Copy output, if it is needed */
1212 s_mp_exch(&qtmp
, q
);
1215 s_mp_exch(&rtmp
, r
);
1223 } /* end mp_div() */
1227 /* {{{ mp_div_2d(a, d, q, r) */
1229 mp_err
mp_div_2d(mp_int
*a
, mp_digit d
, mp_int
*q
, mp_int
*r
)
1233 ARGCHK(a
!= NULL
, MP_BADARG
);
1236 if((res
= mp_copy(a
, q
)) != MP_OKAY
)
1243 if((res
= mp_copy(a
, r
)) != MP_OKAY
)
1251 } /* end mp_div_2d() */
1255 /* {{{ mp_expt(a, b, c) */
1260 Compute c = a ** b, that is, raise a to the b power. Uses a
1261 standard iterative square-and-multiply technique.
1264 mp_err
mp_expt(mp_int
*a
, mp_int
*b
, mp_int
*c
)
1271 ARGCHK(a
!= NULL
&& b
!= NULL
&& c
!= NULL
, MP_BADARG
);
1276 if((res
= mp_init(&s
)) != MP_OKAY
)
1281 if((res
= mp_init_copy(&x
, a
)) != MP_OKAY
)
1284 /* Loop over low-order digits in ascending order */
1285 for(dig
= 0; dig
< (USED(b
) - 1); dig
++) {
1288 /* Loop over bits of each non-maximal digit */
1289 for(bit
= 0; bit
< DIGIT_BIT
; bit
++) {
1291 if((res
= s_mp_mul(&s
, &x
)) != MP_OKAY
)
1297 if((res
= s_mp_sqr(&x
)) != MP_OKAY
)
1302 /* Consider now the last digit... */
1307 if((res
= s_mp_mul(&s
, &x
)) != MP_OKAY
)
1313 if((res
= s_mp_sqr(&x
)) != MP_OKAY
)
1320 res
= mp_copy(&s
, c
);
1329 } /* end mp_expt() */
1333 /* {{{ mp_2expt(a, k) */
1335 /* Compute a = 2^k */
1337 mp_err
mp_2expt(mp_int
*a
, mp_digit k
)
1339 ARGCHK(a
!= NULL
, MP_BADARG
);
1341 return s_mp_2expt(a
, k
);
1343 } /* end mp_2expt() */
1347 /* {{{ mp_mod(a, m, c) */
1352 Compute c = a (mod m). Result will always be 0 <= c < m.
1355 mp_err
mp_mod(mp_int
*a
, mp_int
*m
, mp_int
*c
)
1360 ARGCHK(a
!= NULL
&& m
!= NULL
&& c
!= NULL
, MP_BADARG
);
1362 if(SIGN(m
) == MP_NEG
)
1366 If |a| > m, we need to divide to get the remainder and take the
1369 If |a| < m, we don't need to do any division, just copy and adjust
1370 the sign (if a is negative).
1372 If |a| == m, we can simply set the result to zero.
1374 This order is intended to minimize the average path length of the
1375 comparison chain on common workloads -- the most frequent cases are
1376 that |a| != m, so we do those first.
1378 if((mag
= s_mp_cmp(a
, m
)) > 0) {
1379 if((res
= mp_div(a
, m
, NULL
, c
)) != MP_OKAY
)
1382 if(SIGN(c
) == MP_NEG
) {
1383 if((res
= mp_add(c
, m
, c
)) != MP_OKAY
)
1387 } else if(mag
< 0) {
1388 if((res
= mp_copy(a
, c
)) != MP_OKAY
)
1391 if(mp_cmp_z(a
) < 0) {
1392 if((res
= mp_add(c
, m
, c
)) != MP_OKAY
)
1404 } /* end mp_mod() */
1408 /* {{{ mp_mod_d(a, d, c) */
1413 Compute c = a (mod d). Result will always be 0 <= c < d
1415 mp_err
mp_mod_d(mp_int
*a
, mp_digit d
, mp_digit
*c
)
1420 ARGCHK(a
!= NULL
&& c
!= NULL
, MP_BADARG
);
1422 if(s_mp_cmp_d(a
, d
) > 0) {
1423 if((res
= mp_div_d(a
, d
, NULL
, &rem
)) != MP_OKAY
)
1427 if(SIGN(a
) == MP_NEG
)
1428 rem
= d
- DIGIT(a
, 0);
1438 } /* end mp_mod_d() */
1442 /* {{{ mp_sqrt(a, b) */
1447 Compute the integer square root of a, and store the result in b.
1448 Uses an integer-arithmetic version of Newton's iterative linear
1449 approximation technique to determine this value; the result has the
1450 following two properties:
1455 It is a range error to pass a negative value.
1457 mp_err
mp_sqrt(mp_int
*a
, mp_int
*b
)
1462 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_BADARG
);
1464 /* Cannot take square root of a negative value */
1465 if(SIGN(a
) == MP_NEG
)
1468 /* Special cases for zero and one, trivial */
1469 if(mp_cmp_d(a
, 0) == MP_EQ
|| mp_cmp_d(a
, 1) == MP_EQ
)
1470 return mp_copy(a
, b
);
1472 /* Initialize the temporaries we'll use below */
1473 if((res
= mp_init_size(&t
, USED(a
))) != MP_OKAY
)
1476 /* Compute an initial guess for the iteration as a itself */
1477 if((res
= mp_init_copy(&x
, a
)) != MP_OKAY
)
1480 s_mp_rshd(&x
, (USED(&x
)/2)+1);
1481 mp_add_d(&x
, 1, &x
);
1484 /* t = (x * x) - a */
1485 mp_copy(&x
, &t
); /* can't fail, t is big enough for original x */
1486 if((res
= mp_sqr(&t
, &t
)) != MP_OKAY
||
1487 (res
= mp_sub(&t
, a
, &t
)) != MP_OKAY
)
1492 if((res
= mp_div(&t
, &x
, &t
, NULL
)) != MP_OKAY
)
1496 /* Terminate the loop, if the quotient is zero */
1497 if(mp_cmp_z(&t
) == MP_EQ
)
1501 if((res
= mp_sub(&x
, &t
, &x
)) != MP_OKAY
)
1506 /* Copy result to output parameter */
1507 mp_sub_d(&x
, 1, &x
);
1517 } /* end mp_sqrt() */
1523 /*------------------------------------------------------------------------*/
1524 /* {{{ Modular arithmetic */
1527 /* {{{ mp_addmod(a, b, m, c) */
1530 mp_addmod(a, b, m, c)
1532 Compute c = (a + b) mod m
1535 mp_err
mp_addmod(mp_int
*a
, mp_int
*b
, mp_int
*m
, mp_int
*c
)
1539 ARGCHK(a
!= NULL
&& b
!= NULL
&& m
!= NULL
&& c
!= NULL
, MP_BADARG
);
1541 if((res
= mp_add(a
, b
, c
)) != MP_OKAY
)
1543 if((res
= mp_mod(c
, m
, c
)) != MP_OKAY
)
1552 /* {{{ mp_submod(a, b, m, c) */
1555 mp_submod(a, b, m, c)
1557 Compute c = (a - b) mod m
1560 mp_err
mp_submod(mp_int
*a
, mp_int
*b
, mp_int
*m
, mp_int
*c
)
1564 ARGCHK(a
!= NULL
&& b
!= NULL
&& m
!= NULL
&& c
!= NULL
, MP_BADARG
);
1566 if((res
= mp_sub(a
, b
, c
)) != MP_OKAY
)
1568 if((res
= mp_mod(c
, m
, c
)) != MP_OKAY
)
1577 /* {{{ mp_mulmod(a, b, m, c) */
1580 mp_mulmod(a, b, m, c)
1582 Compute c = (a * b) mod m
1585 mp_err
mp_mulmod(mp_int
*a
, mp_int
*b
, mp_int
*m
, mp_int
*c
)
1589 ARGCHK(a
!= NULL
&& b
!= NULL
&& m
!= NULL
&& c
!= NULL
, MP_BADARG
);
1591 if((res
= mp_mul(a
, b
, c
)) != MP_OKAY
)
1593 if((res
= mp_mod(c
, m
, c
)) != MP_OKAY
)
1602 /* {{{ mp_sqrmod(a, m, c) */
1605 mp_err
mp_sqrmod(mp_int
*a
, mp_int
*m
, mp_int
*c
)
1609 ARGCHK(a
!= NULL
&& m
!= NULL
&& c
!= NULL
, MP_BADARG
);
1611 if((res
= mp_sqr(a
, c
)) != MP_OKAY
)
1613 if((res
= mp_mod(c
, m
, c
)) != MP_OKAY
)
1618 } /* end mp_sqrmod() */
1623 /* {{{ mp_exptmod(a, b, m, c) */
1626 mp_exptmod(a, b, m, c)
1628 Compute c = (a ** b) mod m. Uses a standard square-and-multiply
1629 method with modular reductions at each step. (This is basically the
1630 same code as mp_expt(), except for the addition of the reductions)
1632 The modular reductions are done using Barrett's algorithm (see
1633 s_mp_reduce() below for details)
1636 mp_err
mp_exptmod(mp_int
*a
, mp_int
*b
, mp_int
*m
, mp_int
*c
)
1640 mp_digit d
, *db
= DIGITS(b
);
1641 mp_size ub
= USED(b
);
1644 ARGCHK(a
!= NULL
&& b
!= NULL
&& c
!= NULL
, MP_BADARG
);
1646 if(mp_cmp_z(b
) < 0 || mp_cmp_z(m
) <= 0)
1649 if((res
= mp_init(&s
)) != MP_OKAY
)
1651 if((res
= mp_init_copy(&x
, a
)) != MP_OKAY
)
1653 if((res
= mp_mod(&x
, m
, &x
)) != MP_OKAY
||
1654 (res
= mp_init(&mu
)) != MP_OKAY
)
1661 s_mp_lshd(&mu
, 2 * USED(m
));
1662 if((res
= mp_div(&mu
, m
, &mu
, NULL
)) != MP_OKAY
)
1665 /* Loop over digits of b in ascending order, except highest order */
1666 for(dig
= 0; dig
< (ub
- 1); dig
++) {
1669 /* Loop over the bits of the lower-order digits */
1670 for(bit
= 0; bit
< DIGIT_BIT
; bit
++) {
1672 if((res
= s_mp_mul(&s
, &x
)) != MP_OKAY
)
1674 if((res
= s_mp_reduce(&s
, m
, &mu
)) != MP_OKAY
)
1680 if((res
= s_mp_sqr(&x
)) != MP_OKAY
)
1682 if((res
= s_mp_reduce(&x
, m
, &mu
)) != MP_OKAY
)
1687 /* Now do the last digit... */
1692 if((res
= s_mp_mul(&s
, &x
)) != MP_OKAY
)
1694 if((res
= s_mp_reduce(&s
, m
, &mu
)) != MP_OKAY
)
1700 if((res
= s_mp_sqr(&x
)) != MP_OKAY
)
1702 if((res
= s_mp_reduce(&x
, m
, &mu
)) != MP_OKAY
)
1717 } /* end mp_exptmod() */
1721 /* {{{ mp_exptmod_d(a, d, m, c) */
1723 mp_err
mp_exptmod_d(mp_int
*a
, mp_digit d
, mp_int
*m
, mp_int
*c
)
1728 ARGCHK(a
!= NULL
&& c
!= NULL
, MP_BADARG
);
1730 if((res
= mp_init(&s
)) != MP_OKAY
)
1732 if((res
= mp_init_copy(&x
, a
)) != MP_OKAY
)
1739 if((res
= s_mp_mul(&s
, &x
)) != MP_OKAY
||
1740 (res
= mp_mod(&s
, m
, &s
)) != MP_OKAY
)
1746 if((res
= s_mp_sqr(&x
)) != MP_OKAY
||
1747 (res
= mp_mod(&x
, m
, &x
)) != MP_OKAY
)
1760 } /* end mp_exptmod_d() */
1763 #endif /* if MP_MODARITH */
1767 /*------------------------------------------------------------------------*/
1768 /* {{{ Comparison functions */
1770 /* {{{ mp_cmp_z(a) */
1775 Compare a <=> 0. Returns <0 if a<0, 0 if a=0, >0 if a>0.
1778 int mp_cmp_z(mp_int
*a
)
1780 if(SIGN(a
) == MP_NEG
)
1782 else if(USED(a
) == 1 && DIGIT(a
, 0) == 0)
1787 } /* end mp_cmp_z() */
1791 /* {{{ mp_cmp_d(a, d) */
1796 Compare a <=> d. Returns <0 if a<d, 0 if a=d, >0 if a>d
1799 int mp_cmp_d(mp_int
*a
, mp_digit d
)
1801 ARGCHK(a
!= NULL
, MP_EQ
);
1803 if(SIGN(a
) == MP_NEG
)
1806 return s_mp_cmp_d(a
, d
);
1808 } /* end mp_cmp_d() */
1812 /* {{{ mp_cmp(a, b) */
1814 int mp_cmp(mp_int
*a
, mp_int
*b
)
1816 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_EQ
);
1818 if(SIGN(a
) == SIGN(b
)) {
1821 if((mag
= s_mp_cmp(a
, b
)) == MP_EQ
)
1824 if(SIGN(a
) == MP_ZPOS
)
1829 } else if(SIGN(a
) == MP_ZPOS
) {
1835 } /* end mp_cmp() */
1839 /* {{{ mp_cmp_mag(a, b) */
1844 Compares |a| <=> |b|, and returns an appropriate comparison result
1847 int mp_cmp_mag(mp_int
*a
, mp_int
*b
)
1849 ARGCHK(a
!= NULL
&& b
!= NULL
, MP_EQ
);
1851 return s_mp_cmp(a
, b
);
1853 } /* end mp_cmp_mag() */
1857 /* {{{ mp_cmp_int(a, z) */
1860 This just converts z to an mp_int, and uses the existing comparison
1861 routines. This is sort of inefficient, but it's not clear to me how
1862 frequently this wil get used anyway. For small positive constants,
1863 you can always use mp_cmp_d(), and for zero, there is mp_cmp_z().
1865 int mp_cmp_int(mp_int
*a
, long z
)
1870 ARGCHK(a
!= NULL
, MP_EQ
);
1872 mp_init(&tmp
); mp_set_int(&tmp
, z
);
1873 out
= mp_cmp(a
, &tmp
);
1878 } /* end mp_cmp_int() */
1882 /* {{{ mp_isodd(a) */
1887 Returns a true (non-zero) value if a is odd, false (zero) otherwise.
1889 int mp_isodd(mp_int
*a
)
1891 ARGCHK(a
!= NULL
, 0);
1893 return (DIGIT(a
, 0) & 1);
1895 } /* end mp_isodd() */
1899 /* {{{ mp_iseven(a) */
1901 int mp_iseven(mp_int
*a
)
1903 return !mp_isodd(a
);
1905 } /* end mp_iseven() */
1911 /*------------------------------------------------------------------------*/
1912 /* {{{ Number theoretic functions */
1915 /* {{{ mp_gcd(a, b, c) */
1918 Like the old mp_gcd() function, except computes the GCD using the
1919 binary algorithm due to Josef Stein in 1961 (via Knuth).
1921 mp_err
mp_gcd(mp_int
*a
, mp_int
*b
, mp_int
*c
)
1927 ARGCHK(a
!= NULL
&& b
!= NULL
&& c
!= NULL
, MP_BADARG
);
1929 if(mp_cmp_z(a
) == MP_EQ
&& mp_cmp_z(b
) == MP_EQ
)
1931 if(mp_cmp_z(a
) == MP_EQ
) {
1932 return mp_copy(b
, c
);
1933 } else if(mp_cmp_z(b
) == MP_EQ
) {
1934 return mp_copy(a
, c
);
1937 if((res
= mp_init(&t
)) != MP_OKAY
)
1939 if((res
= mp_init_copy(&u
, a
)) != MP_OKAY
)
1941 if((res
= mp_init_copy(&v
, b
)) != MP_OKAY
)
1947 /* Divide out common factors of 2 until at least 1 of a, b is even */
1948 while(mp_iseven(&u
) && mp_iseven(&v
)) {
1956 if((res
= mp_copy(&v
, &t
)) != MP_OKAY
)
1960 if(SIGN(&v
) == MP_ZPOS
)
1966 if((res
= mp_copy(&u
, &t
)) != MP_OKAY
)
1972 while(mp_iseven(&t
)) {
1976 if(mp_cmp_z(&t
) == MP_GT
) {
1977 if((res
= mp_copy(&t
, &u
)) != MP_OKAY
)
1981 if((res
= mp_copy(&t
, &v
)) != MP_OKAY
)
1985 if(SIGN(&t
) == MP_ZPOS
)
1991 if((res
= mp_sub(&u
, &v
, &t
)) != MP_OKAY
)
1994 if(s_mp_cmp_d(&t
, 0) == MP_EQ
)
1998 s_mp_2expt(&v
, k
); /* v = 2^k */
1999 res
= mp_mul(&u
, &v
, c
); /* c = u * v */
2010 } /* end mp_bgcd() */
2014 /* {{{ mp_lcm(a, b, c) */
2016 /* We compute the least common multiple using the rule:
2020 ... by computing the product, and dividing out the gcd.
2023 mp_err
mp_lcm(mp_int
*a
, mp_int
*b
, mp_int
*c
)
2028 ARGCHK(a
!= NULL
&& b
!= NULL
&& c
!= NULL
, MP_BADARG
);
2030 /* Set up temporaries */
2031 if((res
= mp_init(&gcd
)) != MP_OKAY
)
2033 if((res
= mp_init(&prod
)) != MP_OKAY
)
2036 if((res
= mp_mul(a
, b
, &prod
)) != MP_OKAY
)
2038 if((res
= mp_gcd(a
, b
, &gcd
)) != MP_OKAY
)
2041 res
= mp_div(&prod
, &gcd
, c
, NULL
);
2050 } /* end mp_lcm() */
2054 /* {{{ mp_xgcd(a, b, g, x, y) */
2057 mp_xgcd(a, b, g, x, y)
2059 Compute g = (a, b) and values x and y satisfying Bezout's identity
2060 (that is, ax + by = g). This uses the extended binary GCD algorithm
2061 based on the Stein algorithm used for mp_gcd()
2064 mp_err
mp_xgcd(mp_int
*a
, mp_int
*b
, mp_int
*g
, mp_int
*x
, mp_int
*y
)
2066 mp_int gx
, xc
, yc
, u
, v
, A
, B
, C
, D
;
2071 if(mp_cmp_z(b
) == 0)
2074 /* Initialize all these variables we need */
2075 if((res
= mp_init(&u
)) != MP_OKAY
) goto CLEANUP
;
2077 if((res
= mp_init(&v
)) != MP_OKAY
) goto CLEANUP
;
2079 if((res
= mp_init(&gx
)) != MP_OKAY
) goto CLEANUP
;
2080 clean
[++last
] = &gx
;
2081 if((res
= mp_init(&A
)) != MP_OKAY
) goto CLEANUP
;
2083 if((res
= mp_init(&B
)) != MP_OKAY
) goto CLEANUP
;
2085 if((res
= mp_init(&C
)) != MP_OKAY
) goto CLEANUP
;
2087 if((res
= mp_init(&D
)) != MP_OKAY
) goto CLEANUP
;
2089 if((res
= mp_init_copy(&xc
, a
)) != MP_OKAY
) goto CLEANUP
;
2090 clean
[++last
] = &xc
;
2092 if((res
= mp_init_copy(&yc
, b
)) != MP_OKAY
) goto CLEANUP
;
2093 clean
[++last
] = &yc
;
2098 /* Divide by two until at least one of them is even */
2099 while(mp_iseven(&xc
) && mp_iseven(&yc
)) {
2102 if((res
= s_mp_mul_2(&gx
)) != MP_OKAY
)
2108 mp_set(&A
, 1); mp_set(&D
, 1);
2110 /* Loop through binary GCD algorithm */
2112 while(mp_iseven(&u
)) {
2115 if(mp_iseven(&A
) && mp_iseven(&B
)) {
2116 s_mp_div_2(&A
); s_mp_div_2(&B
);
2118 if((res
= mp_add(&A
, &yc
, &A
)) != MP_OKAY
) goto CLEANUP
;
2120 if((res
= mp_sub(&B
, &xc
, &B
)) != MP_OKAY
) goto CLEANUP
;
2125 while(mp_iseven(&v
)) {
2128 if(mp_iseven(&C
) && mp_iseven(&D
)) {
2129 s_mp_div_2(&C
); s_mp_div_2(&D
);
2131 if((res
= mp_add(&C
, &yc
, &C
)) != MP_OKAY
) goto CLEANUP
;
2133 if((res
= mp_sub(&D
, &xc
, &D
)) != MP_OKAY
) goto CLEANUP
;
2138 if(mp_cmp(&u
, &v
) >= 0) {
2139 if((res
= mp_sub(&u
, &v
, &u
)) != MP_OKAY
) goto CLEANUP
;
2140 if((res
= mp_sub(&A
, &C
, &A
)) != MP_OKAY
) goto CLEANUP
;
2141 if((res
= mp_sub(&B
, &D
, &B
)) != MP_OKAY
) goto CLEANUP
;
2144 if((res
= mp_sub(&v
, &u
, &v
)) != MP_OKAY
) goto CLEANUP
;
2145 if((res
= mp_sub(&C
, &A
, &C
)) != MP_OKAY
) goto CLEANUP
;
2146 if((res
= mp_sub(&D
, &B
, &D
)) != MP_OKAY
) goto CLEANUP
;
2150 /* If we're done, copy results to output */
2151 if(mp_cmp_z(&u
) == 0) {
2153 if((res
= mp_copy(&C
, x
)) != MP_OKAY
) goto CLEANUP
;
2156 if((res
= mp_copy(&D
, y
)) != MP_OKAY
) goto CLEANUP
;
2159 if((res
= mp_mul(&gx
, &v
, g
)) != MP_OKAY
) goto CLEANUP
;
2167 mp_clear(clean
[last
--]);
2171 } /* end mp_xgcd() */
2175 /* {{{ mp_invmod(a, m, c) */
2180 Compute c = a^-1 (mod m), if there is an inverse for a (mod m).
2181 This is equivalent to the question of whether (a, m) = 1. If not,
2182 MP_UNDEF is returned, and there is no inverse.
2185 mp_err
mp_invmod(mp_int
*a
, mp_int
*m
, mp_int
*c
)
2190 ARGCHK(a
&& m
&& c
, MP_BADARG
);
2192 if(mp_cmp_z(a
) == 0 || mp_cmp_z(m
) == 0)
2195 if((res
= mp_init(&g
)) != MP_OKAY
)
2197 if((res
= mp_init(&x
)) != MP_OKAY
)
2200 if((res
= mp_xgcd(a
, m
, &g
, &x
, NULL
)) != MP_OKAY
)
2203 if(mp_cmp_d(&g
, 1) != MP_EQ
) {
2208 res
= mp_mod(&x
, m
, c
);
2218 } /* end mp_invmod() */
2221 #endif /* if MP_NUMTH */
2225 /*------------------------------------------------------------------------*/
2226 /* {{{ mp_print(mp, ofp) */
2232 Print a textual representation of the given mp_int on the output
2233 stream 'ofp'. Output is generated using the internal radix.
2236 void mp_print(mp_int
*mp
, FILE *ofp
)
2240 if(mp
== NULL
|| ofp
== NULL
)
2243 fputc((SIGN(mp
) == MP_NEG
) ? '-' : '+', ofp
);
2245 for(ix
= USED(mp
) - 1; ix
>= 0; ix
--) {
2246 fprintf(ofp
, DIGIT_FMT
, DIGIT(mp
, ix
));
2249 } /* end mp_print() */
2251 #endif /* if MP_IOFUNC */
2255 /*------------------------------------------------------------------------*/
2256 /* {{{ More I/O Functions */
2258 /* {{{ mp_read_signed_bin(mp, str, len) */
2261 mp_read_signed_bin(mp, str, len)
2263 Read in a raw value (base 256) into the given mp_int
2266 mp_err
mp_read_signed_bin(mp_int
*mp
, unsigned char *str
, int len
)
2270 ARGCHK(mp
!= NULL
&& str
!= NULL
&& len
> 0, MP_BADARG
);
2272 if((res
= mp_read_unsigned_bin(mp
, str
+ 1, len
- 1)) == MP_OKAY
) {
2273 /* Get sign from first byte */
2282 } /* end mp_read_signed_bin() */
2286 /* {{{ mp_signed_bin_size(mp) */
2288 int mp_signed_bin_size(mp_int
*mp
)
2290 ARGCHK(mp
!= NULL
, 0);
2292 return mp_unsigned_bin_size(mp
) + 1;
2294 } /* end mp_signed_bin_size() */
2298 /* {{{ mp_to_signed_bin(mp, str) */
2300 mp_err
mp_to_signed_bin(mp_int
*mp
, unsigned char *str
)
2302 ARGCHK(mp
!= NULL
&& str
!= NULL
, MP_BADARG
);
2304 /* Caller responsible for allocating enough memory (use mp_raw_size(mp)) */
2305 str
[0] = (char)SIGN(mp
);
2307 return mp_to_unsigned_bin(mp
, str
+ 1);
2309 } /* end mp_to_signed_bin() */
2313 /* {{{ mp_read_unsigned_bin(mp, str, len) */
2316 mp_read_unsigned_bin(mp, str, len)
2318 Read in an unsigned value (base 256) into the given mp_int
2321 mp_err
mp_read_unsigned_bin(mp_int
*mp
, unsigned char *str
, int len
)
2326 ARGCHK(mp
!= NULL
&& str
!= NULL
&& len
> 0, MP_BADARG
);
2330 for(ix
= 0; ix
< len
; ix
++) {
2331 if((res
= s_mp_mul_2d(mp
, CHAR_BIT
)) != MP_OKAY
)
2334 if((res
= mp_add_d(mp
, str
[ix
], mp
)) != MP_OKAY
)
2340 } /* end mp_read_unsigned_bin() */
2344 /* {{{ mp_unsigned_bin_size(mp) */
2346 int mp_unsigned_bin_size(mp_int
*mp
)
2351 ARGCHK(mp
!= NULL
, 0);
2353 /* Special case for the value zero */
2354 if(USED(mp
) == 1 && DIGIT(mp
, 0) == 0)
2357 count
= (USED(mp
) - 1) * sizeof(mp_digit
);
2358 topdig
= DIGIT(mp
, USED(mp
) - 1);
2360 while(topdig
!= 0) {
2362 topdig
>>= CHAR_BIT
;
2367 } /* end mp_unsigned_bin_size() */
2371 /* {{{ mp_to_unsigned_bin(mp, str) */
2373 mp_err
mp_to_unsigned_bin(mp_int
*mp
, unsigned char *str
)
2375 mp_digit
*dp
, *end
, d
;
2376 unsigned char *spos
;
2378 ARGCHK(mp
!= NULL
&& str
!= NULL
, MP_BADARG
);
2381 end
= dp
+ USED(mp
) - 1;
2384 /* Special case for zero, quick test */
2385 if(dp
== end
&& *dp
== 0) {
2390 /* Generate digits in reverse order */
2395 for(ix
= 0; ix
< sizeof(mp_digit
); ++ix
) {
2396 *spos
= d
& UCHAR_MAX
;
2404 /* Now handle last digit specially, high order zeroes are not written */
2407 *spos
= d
& UCHAR_MAX
;
2412 /* Reverse everything to get digits in the correct order */
2413 while(--spos
> str
) {
2414 unsigned char t
= *str
;
2423 } /* end mp_to_unsigned_bin() */
2427 /* {{{ mp_count_bits(mp) */
2429 int mp_count_bits(mp_int
*mp
)
2434 ARGCHK(mp
!= NULL
, MP_BADARG
);
2436 len
= DIGIT_BIT
* (USED(mp
) - 1);
2437 d
= DIGIT(mp
, USED(mp
) - 1);
2446 } /* end mp_count_bits() */
2450 /* {{{ mp_read_radix(mp, str, radix) */
2453 mp_read_radix(mp, str, radix)
2455 Read an integer from the given string, and set mp to the resulting
2456 value. The input is presumed to be in base 10. Leading non-digit
2457 characters are ignored, and the function reads until a non-digit
2458 character or the end of the string.
2461 mp_err
mp_read_radix(mp_int
*mp
, unsigned char *str
, int radix
)
2463 int ix
= 0, val
= 0;
2465 mp_sign sig
= MP_ZPOS
;
2467 ARGCHK(mp
!= NULL
&& str
!= NULL
&& radix
>= 2 && radix
<= MAX_RADIX
,
2472 /* Skip leading non-digit characters until a digit or '-' or '+' */
2474 (s_mp_tovalue(str
[ix
], radix
) < 0) &&
2480 if(str
[ix
] == '-') {
2483 } else if(str
[ix
] == '+') {
2484 sig
= MP_ZPOS
; /* this is the default anyway... */
2488 while((val
= s_mp_tovalue(str
[ix
], radix
)) >= 0) {
2489 if((res
= s_mp_mul_d(mp
, radix
)) != MP_OKAY
)
2491 if((res
= s_mp_add_d(mp
, val
)) != MP_OKAY
)
2496 if(s_mp_cmp_d(mp
, 0) == MP_EQ
)
2503 } /* end mp_read_radix() */
2507 /* {{{ mp_radix_size(mp, radix) */
2509 int mp_radix_size(mp_int
*mp
, int radix
)
2512 ARGCHK(mp
!= NULL
, 0);
2514 len
= s_mp_outlen(mp_count_bits(mp
), radix
) + 1; /* for NUL terminator */
2516 if(mp_cmp_z(mp
) < 0)
2517 ++len
; /* for sign */
2521 } /* end mp_radix_size() */
2525 /* {{{ mp_value_radix_size(num, qty, radix) */
2527 /* num = number of digits
2528 qty = number of bits per digit
2531 Return the number of digits in the specified radix that would be
2532 needed to express 'num' digits of 'qty' bits each.
2534 int mp_value_radix_size(int num
, int qty
, int radix
)
2536 ARGCHK(num
>= 0 && qty
> 0 && radix
>= 2 && radix
<= MAX_RADIX
, 0);
2538 return s_mp_outlen(num
* qty
, radix
);
2540 } /* end mp_value_radix_size() */
2544 /* {{{ mp_toradix(mp, str, radix) */
2546 mp_err
mp_toradix(mp_int
*mp
, unsigned char *str
, int radix
)
2550 ARGCHK(mp
!= NULL
&& str
!= NULL
, MP_BADARG
);
2551 ARGCHK(radix
> 1 && radix
<= MAX_RADIX
, MP_RANGE
);
2553 if(mp_cmp_z(mp
) == MP_EQ
) {
2560 mp_digit rem
, rdx
= (mp_digit
)radix
;
2563 if((res
= mp_init_copy(&tmp
, mp
)) != MP_OKAY
)
2566 /* Save sign for later, and take absolute value */
2567 sgn
= SIGN(&tmp
); SIGN(&tmp
) = MP_ZPOS
;
2569 /* Generate output digits in reverse order */
2570 while(mp_cmp_z(&tmp
) != 0) {
2571 if((res
= s_mp_div_d(&tmp
, rdx
, &rem
)) != MP_OKAY
) {
2576 /* Generate digits, use capital letters */
2577 ch
= s_mp_todigit(rem
, radix
, 0);
2582 /* Add - sign if original value was negative */
2586 /* Add trailing NUL to end the string */
2589 /* Reverse the digits and sign indicator */
2605 } /* end mp_toradix() */
2609 /* {{{ mp_char2value(ch, r) */
2611 int mp_char2value(char ch
, int r
)
2613 return s_mp_tovalue(ch
, r
);
2615 } /* end mp_tovalue() */
2621 /* {{{ mp_strerror(ec) */
2626 Return a string describing the meaning of error code 'ec'. The
2627 string returned is allocated in static memory, so the caller should
2628 not attempt to modify or free the memory associated with this
2631 const char *mp_strerror(mp_err ec
)
2633 int aec
= (ec
< 0) ? -ec
: ec
;
2635 /* Code values are negative, so the senses of these comparisons
2637 if(ec
< MP_LAST_CODE
|| ec
> MP_OKAY
) {
2638 return mp_err_string
[0]; /* unknown error code */
2640 return mp_err_string
[aec
+ 1];
2643 } /* end mp_strerror() */
2647 /*========================================================================*/
2648 /*------------------------------------------------------------------------*/
2649 /* Static function definitions (internal use only) */
2651 /* {{{ Memory management */
2653 /* {{{ s_mp_grow(mp, min) */
2655 /* Make sure there are at least 'min' digits allocated to mp */
2656 mp_err
s_mp_grow(mp_int
*mp
, mp_size min
)
2658 if(min
> ALLOC(mp
)) {
2661 /* Set min to next nearest default precision block size */
2662 min
= ((min
+ (s_mp_defprec
- 1)) / s_mp_defprec
) * s_mp_defprec
;
2664 if((tmp
= s_mp_alloc(min
, sizeof(mp_digit
))) == NULL
)
2667 s_mp_copy(DIGITS(mp
), tmp
, USED(mp
));
2670 s_mp_setz(DIGITS(mp
), ALLOC(mp
));
2672 s_mp_free(DIGITS(mp
));
2679 } /* end s_mp_grow() */
2683 /* {{{ s_mp_pad(mp, min) */
2685 /* Make sure the used size of mp is at least 'min', growing if needed */
2686 mp_err
s_mp_pad(mp_int
*mp
, mp_size min
)
2688 if(min
> USED(mp
)) {
2691 /* Make sure there is room to increase precision */
2692 if(min
> ALLOC(mp
) && (res
= s_mp_grow(mp
, min
)) != MP_OKAY
)
2695 /* Increase precision; should already be 0-filled */
2701 } /* end s_mp_pad() */
2705 /* {{{ s_mp_setz(dp, count) */
2708 /* Set 'count' digits pointed to by dp to be zeroes */
2709 void s_mp_setz(mp_digit
*dp
, mp_size count
)
2714 for(ix
= 0; ix
< count
; ix
++)
2717 memset(dp
, 0, count
* sizeof(mp_digit
));
2720 } /* end s_mp_setz() */
2725 /* {{{ s_mp_copy(sp, dp, count) */
2728 /* Copy 'count' digits from sp to dp */
2729 void s_mp_copy(mp_digit
*sp
, mp_digit
*dp
, mp_size count
)
2734 for(ix
= 0; ix
< count
; ix
++)
2737 memcpy(dp
, sp
, count
* sizeof(mp_digit
));
2740 } /* end s_mp_copy() */
2745 /* {{{ s_mp_alloc(nb, ni) */
2748 /* Allocate ni records of nb bytes each, and return a pointer to that */
2749 void *s_mp_alloc(size_t nb
, size_t ni
)
2751 return calloc(nb
, ni
);
2753 } /* end s_mp_alloc() */
2758 /* {{{ s_mp_free(ptr) */
2761 /* Free the memory pointed to by ptr */
2762 void s_mp_free(void *ptr
)
2767 } /* end s_mp_free() */
2772 /* {{{ s_mp_clamp(mp) */
2774 /* Remove leading zeroes from the given value */
2775 void s_mp_clamp(mp_int
*mp
)
2777 mp_size du
= USED(mp
);
2778 mp_digit
*zp
= DIGITS(mp
) + du
- 1;
2780 while(du
> 1 && !*zp
--)
2785 } /* end s_mp_clamp() */
2790 /* {{{ s_mp_exch(a, b) */
2792 /* Exchange the data for a and b; (b, a) = (a, b) */
2793 void s_mp_exch(mp_int
*a
, mp_int
*b
)
2801 } /* end s_mp_exch() */
2807 /* {{{ Arithmetic helpers */
2809 /* {{{ s_mp_lshd(mp, p) */
2812 Shift mp leftward by p digits, growing if needed, and zero-filling
2813 the in-shifted digits at the right end. This is a convenient
2814 alternative to multiplication by powers of the radix
2817 mp_err
s_mp_lshd(mp_int
*mp
, mp_size p
)
2827 if((res
= s_mp_pad(mp
, USED(mp
) + p
)) != MP_OKAY
)
2833 /* Shift all the significant figures over as needed */
2834 for(ix
= pos
- p
; ix
>= 0; ix
--)
2835 dp
[ix
+ p
] = dp
[ix
];
2837 /* Fill the bottom digits with zeroes */
2838 for(ix
= 0; ix
< p
; ix
++)
2843 } /* end s_mp_lshd() */
2847 /* {{{ s_mp_rshd(mp, p) */
2850 Shift mp rightward by p digits. Maintains the invariant that
2851 digits above the precision are all zero. Digits shifted off the
2852 end are lost. Cannot fail.
2855 void s_mp_rshd(mp_int
*mp
, mp_size p
)
2863 /* Shortcut when all digits are to be shifted off */
2865 s_mp_setz(DIGITS(mp
), ALLOC(mp
));
2871 /* Shift all the significant figures over as needed */
2873 for(ix
= p
; ix
< USED(mp
); ix
++)
2874 dp
[ix
- p
] = dp
[ix
];
2876 /* Fill the top digits with zeroes */
2878 while(ix
< USED(mp
))
2881 /* Strip off any leading zeroes */
2884 } /* end s_mp_rshd() */
2888 /* {{{ s_mp_div_2(mp) */
2890 /* Divide by two -- take advantage of radix properties to do it fast */
2891 void s_mp_div_2(mp_int
*mp
)
2895 } /* end s_mp_div_2() */
2899 /* {{{ s_mp_mul_2(mp) */
2901 mp_err
s_mp_mul_2(mp_int
*mp
)
2904 mp_digit kin
= 0, kout
, *dp
= DIGITS(mp
);
2907 /* Shift digits leftward by 1 bit */
2908 for(ix
= 0; ix
< USED(mp
); ix
++) {
2909 kout
= (dp
[ix
] >> (DIGIT_BIT
- 1)) & 1;
2910 dp
[ix
] = (dp
[ix
] << 1) | kin
;
2915 /* Deal with rollover from last digit */
2917 if(ix
>= ALLOC(mp
)) {
2918 if((res
= s_mp_grow(mp
, ALLOC(mp
) + 1)) != MP_OKAY
)
2929 } /* end s_mp_mul_2() */
2933 /* {{{ s_mp_mod_2d(mp, d) */
2936 Remainder the integer by 2^d, where d is a number of bits. This
2937 amounts to a bitwise AND of the value, and does not require the full
2940 void s_mp_mod_2d(mp_int
*mp
, mp_digit d
)
2942 unsigned int ndig
= (d
/ DIGIT_BIT
), nbit
= (d
% DIGIT_BIT
);
2944 mp_digit dmask
, *dp
= DIGITS(mp
);
2946 if(ndig
>= USED(mp
))
2949 /* Flush all the bits above 2^d in its digit */
2950 dmask
= (1 << nbit
) - 1;
2953 /* Flush all digits above the one with 2^d in it */
2954 for(ix
= ndig
+ 1; ix
< USED(mp
); ix
++)
2959 } /* end s_mp_mod_2d() */
2963 /* {{{ s_mp_mul_2d(mp, d) */
2966 Multiply by the integer 2^d, where d is a number of bits. This
2967 amounts to a bitwise shift of the value, and does not require the
2968 full multiplication code.
2970 mp_err
s_mp_mul_2d(mp_int
*mp
, mp_digit d
)
2973 mp_digit save
, next
, mask
, *dp
;
2977 if((res
= s_mp_lshd(mp
, d
/ DIGIT_BIT
)) != MP_OKAY
)
2980 dp
= DIGITS(mp
); used
= USED(mp
);
2983 mask
= (1 << d
) - 1;
2985 /* If the shift requires another digit, make sure we've got one to
2987 if((dp
[used
- 1] >> (DIGIT_BIT
- d
)) & mask
) {
2988 if((res
= s_mp_grow(mp
, used
+ 1)) != MP_OKAY
)
2993 /* Do the shifting... */
2995 for(ix
= 0; ix
< used
; ix
++) {
2996 next
= (dp
[ix
] >> (DIGIT_BIT
- d
)) & mask
;
2997 dp
[ix
] = (dp
[ix
] << d
) | save
;
3001 /* If, at this point, we have a nonzero carryout into the next
3002 digit, we'll increase the size by one digit, and store it...
3012 } /* end s_mp_mul_2d() */
3016 /* {{{ s_mp_div_2d(mp, d) */
3019 Divide the integer by 2^d, where d is a number of bits. This
3020 amounts to a bitwise shift of the value, and does not require the
3021 full division code (used in Barrett reduction, see below)
3023 void s_mp_div_2d(mp_int
*mp
, mp_digit d
)
3026 mp_digit save
, next
, mask
, *dp
= DIGITS(mp
);
3028 s_mp_rshd(mp
, d
/ DIGIT_BIT
);
3031 mask
= (1 << d
) - 1;
3034 for(ix
= USED(mp
) - 1; ix
>= 0; ix
--) {
3035 next
= dp
[ix
] & mask
;
3036 dp
[ix
] = (dp
[ix
] >> d
) | (save
<< (DIGIT_BIT
- d
));
3042 } /* end s_mp_div_2d() */
3046 /* {{{ s_mp_norm(a, b) */
3051 Normalize a and b for division, where b is the divisor. In order
3052 that we might make good guesses for quotient digits, we want the
3053 leading digit of b to be at least half the radix, which we
3054 accomplish by multiplying a and b by a constant. This constant is
3055 returned (so that it can be divided back out of the remainder at the
3056 end of the division process).
3058 We multiply by the smallest power of 2 that gives us a leading digit
3059 at least half the radix. By choosing a power of 2, we simplify the
3060 multiplication and division steps to simple shifts.
3062 mp_digit
s_mp_norm(mp_int
*a
, mp_int
*b
)
3066 t
= DIGIT(b
, USED(b
) - 1);
3067 while(t
< (RADIX
/ 2)) {
3079 } /* end s_mp_norm() */
3085 /* {{{ Primitive digit arithmetic */
3087 /* {{{ s_mp_add_d(mp, d) */
3089 /* Add d to |mp| in place */
3090 mp_err
s_mp_add_d(mp_int
*mp
, mp_digit d
) /* unsigned digit addition */
3093 mp_size ix
= 1, used
= USED(mp
);
3094 mp_digit
*dp
= DIGITS(mp
);
3100 while(ix
< used
&& k
) {
3110 if((res
= s_mp_pad(mp
, USED(mp
) + 1)) != MP_OKAY
)
3118 } /* end s_mp_add_d() */
3122 /* {{{ s_mp_sub_d(mp, d) */
3124 /* Subtract d from |mp| in place, assumes |mp| > d */
3125 mp_err
s_mp_sub_d(mp_int
*mp
, mp_digit d
) /* unsigned digit subtract */
3128 mp_size ix
= 1, used
= USED(mp
);
3129 mp_digit
*dp
= DIGITS(mp
);
3131 /* Compute initial subtraction */
3132 w
= (RADIX
+ dp
[0]) - d
;
3133 b
= CARRYOUT(w
) ? 0 : 1;
3136 /* Propagate borrows leftward */
3137 while(b
&& ix
< used
) {
3138 w
= (RADIX
+ dp
[ix
]) - b
;
3139 b
= CARRYOUT(w
) ? 0 : 1;
3144 /* Remove leading zeroes */
3147 /* If we have a borrow out, it's a violation of the input invariant */
3153 } /* end s_mp_sub_d() */
3157 /* {{{ s_mp_mul_d(a, d) */
3159 /* Compute a = a * d, single digit multiplication */
3160 mp_err
s_mp_mul_d(mp_int
*a
, mp_digit d
)
3165 mp_digit
*dp
= DIGITS(a
);
3168 Single-digit multiplication will increase the precision of the
3169 output by at most one digit. However, we can detect when this
3170 will happen -- if the high-order digit of a, times d, gives a
3171 two-digit result, then the precision of the result will increase;
3172 otherwise it won't. We use this fact to avoid calling s_mp_pad()
3173 unless absolutely necessary.
3176 w
= dp
[max
- 1] * d
;
3177 if(CARRYOUT(w
) != 0) {
3178 if((res
= s_mp_pad(a
, max
+ 1)) != MP_OKAY
)
3183 for(ix
= 0; ix
< max
; ix
++) {
3184 w
= (dp
[ix
] * d
) + k
;
3189 /* If there is a precision increase, take care of it here; the above
3190 test guarantees we have enough storage to do this safely.
3201 } /* end s_mp_mul_d() */
3205 /* {{{ s_mp_div_d(mp, d, r) */
3208 s_mp_div_d(mp, d, r)
3210 Compute the quotient mp = mp / d and remainder r = mp mod d, for a
3211 single digit d. If r is null, the remainder will be discarded.
3214 mp_err
s_mp_div_d(mp_int
*mp
, mp_digit d
, mp_digit
*r
)
3219 mp_digit
*dp
= DIGITS(mp
), *qp
;
3225 /* Make room for the quotient */
3226 if((res
= mp_init_size("
, USED(mp
))) != MP_OKAY
)
3229 USED("
) = USED(mp
); /* so clamping will work below */
3232 /* Divide without subtraction */
3233 for(ix
= USED(mp
) - 1; ix
>= 0; ix
--) {
3234 w
= (w
<< DIGIT_BIT
) | dp
[ix
];
3246 /* Deliver the remainder, if desired */
3256 } /* end s_mp_div_d() */
3262 /* {{{ Primitive full arithmetic */
3264 /* {{{ s_mp_add(a, b) */
3266 /* Compute a = |a| + |b| */
3267 mp_err
s_mp_add(mp_int
*a
, mp_int
*b
) /* magnitude addition */
3271 mp_size ix
, used
= USED(b
);
3274 /* Make sure a has enough precision for the output value */
3275 if((used
> USED(a
)) && (res
= s_mp_pad(a
, used
)) != MP_OKAY
)
3279 Add up all digits up to the precision of b. If b had initially
3280 the same precision as a, or greater, we took care of it by the
3281 padding step above, so there is no problem. If b had initially
3282 less precision, we'll have to make sure the carry out is duly
3283 propagated upward among the higher-order digits of the sum.
3287 for(ix
= 0; ix
< used
; ++ix
) {
3293 /* If we run out of 'b' digits before we're actually done, make
3294 sure the carries get propagated upward...
3297 while(w
&& ix
< used
) {
3304 /* If there's an overall carry out, increase precision and include
3305 it. We could have done this initially, but why touch the memory
3306 allocator unless we're sure we have to?
3309 if((res
= s_mp_pad(a
, used
+ 1)) != MP_OKAY
)
3312 DIGIT(a
, ix
) = w
; /* pa may not be valid after s_mp_pad() call */
3317 } /* end s_mp_add() */
3321 /* {{{ s_mp_sub(a, b) */
3323 /* Compute a = |a| - |b|, assumes |a| >= |b| */
3324 mp_err
s_mp_sub(mp_int
*a
, mp_int
*b
) /* magnitude subtract */
3328 mp_size ix
, used
= USED(b
);
3331 Subtract and propagate borrow. Up to the precision of b, this
3332 accounts for the digits of b; after that, we just make sure the
3333 carries get to the right place. This saves having to pad b out to
3334 the precision of a just to make the loops work right...
3339 for(ix
= 0; ix
< used
; ++ix
) {
3340 w
= (RADIX
+ *pa
) - w
- *pb
++;
3342 w
= CARRYOUT(w
) ? 0 : 1;
3347 w
= RADIX
+ *pa
- w
;
3349 w
= CARRYOUT(w
) ? 0 : 1;
3353 /* Clobber any leading zeroes we created */
3357 If there was a borrow out, then |b| > |a| in violation
3358 of our input invariant. We've already done the work,
3359 but we'll at least complain about it...
3366 } /* end s_mp_sub() */
3370 mp_err
s_mp_reduce(mp_int
*x
, mp_int
*m
, mp_int
*mu
)
3374 mp_size um
= USED(m
);
3376 if((res
= mp_init_copy(&q
, x
)) != MP_OKAY
)
3379 s_mp_rshd(&q
, um
- 1); /* q1 = x / b^(k-1) */
3380 s_mp_mul(&q
, mu
); /* q2 = q1 * mu */
3381 s_mp_rshd(&q
, um
+ 1); /* q3 = q2 / b^(k+1) */
3383 /* x = x mod b^(k+1), quick (no division) */
3384 s_mp_mod_2d(x
, (mp_digit
)(DIGIT_BIT
* (um
+ 1)));
3386 /* q = q * m mod b^(k+1), quick (no division), uses the short multiplier */
3389 s_mp_mod_2d(&q
, (mp_digit
)(DIGIT_BIT
* (um
+ 1)));
3391 s_mp_mul_dig(&q
, m
, um
+ 1);
3395 if((res
= mp_sub(x
, &q
, x
)) != MP_OKAY
)
3398 /* If x < 0, add b^(k+1) to it */
3399 if(mp_cmp_z(x
) < 0) {
3401 if((res
= s_mp_lshd(&q
, um
+ 1)) != MP_OKAY
)
3403 if((res
= mp_add(x
, &q
, x
)) != MP_OKAY
)
3407 /* Back off if it's too big */
3408 while(mp_cmp(x
, m
) >= 0) {
3409 if((res
= s_mp_sub(x
, m
)) != MP_OKAY
)
3418 } /* end s_mp_reduce() */
3422 /* {{{ s_mp_mul(a, b) */
3424 /* Compute a = |a| * |b| */
3425 mp_err
s_mp_mul(mp_int
*a
, mp_int
*b
)
3430 mp_size ix
, jx
, ua
= USED(a
), ub
= USED(b
);
3431 mp_digit
*pa
, *pb
, *pt
, *pbt
;
3433 if((res
= mp_init_size(&tmp
, ua
+ ub
)) != MP_OKAY
)
3436 /* This has the effect of left-padding with zeroes... */
3437 USED(&tmp
) = ua
+ ub
;
3439 /* We're going to need the base value each iteration */
3442 /* Outer loop: Digits of b */
3445 for(ix
= 0; ix
< ub
; ++ix
, ++pb
) {
3449 /* Inner product: Digits of a */
3451 for(jx
= 0; jx
< ua
; ++jx
, ++pa
) {
3453 w
= *pb
* *pa
+ k
+ *pt
;
3469 } /* end s_mp_mul() */
3473 /* {{{ s_mp_kmul(a, b, out, len) */
3476 void s_mp_kmul(mp_digit
*a
, mp_digit
*b
, mp_digit
*out
, mp_size len
)
3482 for(ix
= 0; ix
< len
; ++ix
, ++b
) {
3487 for(jx
= 0; jx
< len
; ++jx
, ++pa
) {
3489 w
= *b
* *pa
+ k
+ *pt
;
3498 } /* end s_mp_kmul() */
3503 /* {{{ s_mp_sqr(a) */
3506 Computes the square of a, in place. This can be done more
3507 efficiently than a general multiplication, because many of the
3508 computation steps are redundant when squaring. The inner product
3509 step is a bit more complicated, but we save a fair number of
3510 iterations of the multiplication loop.
3513 mp_err
s_mp_sqr(mp_int
*a
)
3518 mp_size ix
, jx
, kx
, used
= USED(a
);
3519 mp_digit
*pa1
, *pa2
, *pt
, *pbt
;
3521 if((res
= mp_init_size(&tmp
, 2 * used
)) != MP_OKAY
)
3524 /* Left-pad with zeroes */
3525 USED(&tmp
) = 2 * used
;
3527 /* We need the base value each time through the loop */
3531 for(ix
= 0; ix
< used
; ++ix
, ++pa1
) {
3535 w
= DIGIT(&tmp
, ix
+ ix
) + (*pa1
* *pa1
);
3537 pbt
[ix
+ ix
] = ACCUM(w
);
3541 The inner product is computed as:
3543 (C, S) = t[i,j] + 2 a[i] a[j] + C
3545 This can overflow what can be represented in an mp_word, and
3546 since C arithmetic does not provide any way to check for
3547 overflow, we have to check explicitly for overflow conditions
3550 for(jx
= ix
+ 1, pa2
= DIGITS(a
) + jx
; jx
< used
; ++jx
, ++pa2
) {
3553 /* Store this in a temporary to avoid indirections later */
3556 /* Compute the multiplicative step */
3559 /* If w is more than half MP_WORD_MAX, the doubling will
3560 overflow, and we need to record a carry out into the next
3562 u
= (w
>> (MP_WORD_BIT
- 1)) & 1;
3564 /* Double what we've got, overflow will be ignored as defined
3565 for C arithmetic (we've already noted if it is to occur)
3569 /* Compute the additive step */
3572 /* If we do not already have an overflow carry, check to see
3573 if the addition will cause one, and set the carry out if so
3575 u
|= ((MP_WORD_MAX
- v
) < w
);
3577 /* Add in the rest, again ignoring overflow */
3580 /* Set the i,j digit of the output */
3583 /* Save carry information for the next iteration of the loop.
3584 This is why k must be an mp_word, instead of an mp_digit */
3585 k
= CARRYOUT(w
) | (u
<< DIGIT_BIT
);
3589 /* Set the last digit in the cycle and reset the carry */
3590 k
= DIGIT(&tmp
, ix
+ jx
) + k
;
3591 pbt
[ix
+ jx
] = ACCUM(k
);
3594 /* If we are carrying out, propagate the carry to the next digit
3595 in the output. This may cascade, so we have to be somewhat
3596 circumspect -- but we will have enough precision in the output
3597 that we won't overflow
3601 k
= pbt
[ix
+ jx
+ kx
] + 1;
3602 pbt
[ix
+ jx
+ kx
] = ACCUM(k
);
3615 } /* end s_mp_sqr() */
3620 /* {{{ s_mp_div(a, b) */
3625 Compute a = a / b and b = a mod b. Assumes b > a.
3628 mp_err
s_mp_div(mp_int
*a
, mp_int
*b
)
3630 mp_int quot
, rem
, t
;
3636 if(mp_cmp_z(b
) == 0)
3639 /* Shortcut if b is power of two */
3640 if((ix
= s_mp_ispow2(b
)) >= 0) {
3641 mp_copy(a
, b
); /* need this for remainder */
3642 s_mp_div_2d(a
, (mp_digit
)ix
);
3643 s_mp_mod_2d(b
, (mp_digit
)ix
);
3648 /* Allocate space to store the quotient */
3649 if((res
= mp_init_size("
, USED(a
))) != MP_OKAY
)
3652 /* A working temporary for division */
3653 if((res
= mp_init_size(&t
, USED(a
))) != MP_OKAY
)
3656 /* Allocate space for the remainder */
3657 if((res
= mp_init_size(&rem
, USED(a
))) != MP_OKAY
)
3660 /* Normalize to optimize guessing */
3661 d
= s_mp_norm(a
, b
);
3663 /* Perform the division itself...woo! */
3667 /* Find a partial substring of a which is at least b */
3668 while(s_mp_cmp(&rem
, b
) < 0 && ix
>= 0) {
3669 if((res
= s_mp_lshd(&rem
, 1)) != MP_OKAY
)
3672 if((res
= s_mp_lshd("
, 1)) != MP_OKAY
)
3675 DIGIT(&rem
, 0) = DIGIT(a
, ix
);
3680 /* If we didn't find one, we're finished dividing */
3681 if(s_mp_cmp(&rem
, b
) < 0)
3684 /* Compute a guess for the next quotient digit */
3685 q
= DIGIT(&rem
, USED(&rem
) - 1);
3686 if(q
<= DIGIT(b
, USED(b
) - 1) && USED(&rem
) > 1)
3687 q
= (q
<< DIGIT_BIT
) | DIGIT(&rem
, USED(&rem
) - 2);
3689 q
/= DIGIT(b
, USED(b
) - 1);
3691 /* The guess can be as much as RADIX + 1 */
3695 /* See what that multiplies out to */
3697 if((res
= s_mp_mul_d(&t
, q
)) != MP_OKAY
)
3701 If it's too big, back it off. We should not have to do this
3702 more than once, or, in rare cases, twice. Knuth describes a
3703 method by which this could be reduced to a maximum of once, but
3704 I didn't implement that here.
3706 while(s_mp_cmp(&t
, &rem
) > 0) {
3711 /* At this point, q should be the right next digit */
3712 if((res
= s_mp_sub(&rem
, &t
)) != MP_OKAY
)
3716 Include the digit in the quotient. We allocated enough memory
3717 for any quotient we could ever possibly get, so we should not
3718 have to check for failures here
3720 DIGIT("
, 0) = q
;
3723 /* Denormalize remainder */
3725 s_mp_div_2d(&rem
, d
);
3730 /* Copy quotient back to output */
3731 s_mp_exch("
, a
);
3733 /* Copy remainder back to output */
3745 } /* end s_mp_div() */
3749 /* {{{ s_mp_2expt(a, k) */
3751 mp_err
s_mp_2expt(mp_int
*a
, mp_digit k
)
3756 dig
= k
/ DIGIT_BIT
;
3757 bit
= k
% DIGIT_BIT
;
3760 if((res
= s_mp_pad(a
, dig
+ 1)) != MP_OKAY
)
3763 DIGIT(a
, dig
) |= (1 << bit
);
3767 } /* end s_mp_2expt() */
3776 /* {{{ Primitive comparisons */
3778 /* {{{ s_mp_cmp(a, b) */
3780 /* Compare |a| <=> |b|, return 0 if equal, <0 if a<b, >0 if a>b */
3781 int s_mp_cmp(mp_int
*a
, mp_int
*b
)
3783 mp_size ua
= USED(a
), ub
= USED(b
);
3791 mp_digit
*ap
= DIGITS(a
) + ix
, *bp
= DIGITS(b
) + ix
;
3805 } /* end s_mp_cmp() */
3809 /* {{{ s_mp_cmp_d(a, d) */
3811 /* Compare |a| <=> d, return 0 if equal, <0 if a<d, >0 if a>d */
3812 int s_mp_cmp_d(mp_int
*a
, mp_digit d
)
3814 mp_size ua
= USED(a
);
3815 mp_digit
*ap
= DIGITS(a
);
3827 } /* end s_mp_cmp_d() */
3831 /* {{{ s_mp_ispow2(v) */
3834 Returns -1 if the value is not a power of two; otherwise, it returns
3835 k such that v = 2^k, i.e. lg(v).
3837 int s_mp_ispow2(mp_int
*v
)
3840 mp_size uv
= USED(v
);
3843 d
= DIGIT(v
, uv
- 1); /* most significant digit of v */
3845 while(d
&& ((d
& 1) == 0)) {
3852 dp
= DIGITS(v
) + ix
;
3856 return -1; /* not a power of two */
3861 return ((uv
- 1) * DIGIT_BIT
) + extra
;
3866 } /* end s_mp_ispow2() */
3870 /* {{{ s_mp_ispow2d(d) */
3872 int s_mp_ispow2d(mp_digit d
)
3876 while((d
& 1) == 0) {
3885 } /* end s_mp_ispow2d() */
3891 /* {{{ Primitive I/O helpers */
3893 /* {{{ s_mp_tovalue(ch, r) */
3896 Convert the given character to its digit value, in the given radix.
3897 If the given character is not understood in the given radix, -1 is
3898 returned. Otherwise the digit's numeric value is returned.
3900 The results will be odd if you use a radix < 2 or > 62, you are
3901 expected to know what you're up to.
3903 int s_mp_tovalue(char ch
, int r
)
3914 else if(isupper(xch
))
3915 val
= xch
- 'A' + 10;
3916 else if(islower(xch
))
3917 val
= xch
- 'a' + 36;
3925 if(val
< 0 || val
>= r
)
3930 } /* end s_mp_tovalue() */
3934 /* {{{ s_mp_todigit(val, r, low) */
3937 Convert val to a radix-r digit, if possible. If val is out of range
3938 for r, returns zero. Otherwise, returns an ASCII character denoting
3939 the value in the given radix.
3941 The results may be odd if you use a radix < 2 or > 64, you are
3942 expected to know what you're doing.
3945 char s_mp_todigit(int val
, int r
, int low
)
3949 if(val
< 0 || val
>= r
)
3959 } /* end s_mp_todigit() */
3963 /* {{{ s_mp_outlen(bits, radix) */
3966 Return an estimate for how long a string is needed to hold a radix
3967 r representation of a number with 'bits' significant bits.
3969 Does not include space for a sign or a NUL terminator.
3971 int s_mp_outlen(int bits
, int r
)
3973 return (int)((double)bits
* LOG_V_2(r
));
3975 } /* end s_mp_outlen() */
3981 /*------------------------------------------------------------------------*/
3982 /* HERE THERE BE DRAGONS */
3983 /* crc==4242132123, version==2, Sat Feb 02 06:43:52 2002 */
3985 /* Source: /cvs/libtom/libtommath/mtest/mpi.c,v */
3987 /* Date: 2005/05/05 14:38:47 */