tommath/bn_mp_dr_reduce.c

87 lines
2.2 KiB
C
Raw Normal View History

2003-03-22 10:10:20 -05:00
/* LibTomMath, multiple-precision integer library -- Tom St Denis
*
* LibTomMath is library that provides for multiple-precision
* integer arithmetic as well as number theoretic functionality.
*
* The library is designed directly after the MPI library by
* Michael Fromberger but has been written from scratch with
* additional optimizations in place.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
*/
#include <tommath.h>
2003-05-29 09:35:26 -04:00
/* reduce "x" in place modulo "n" using the Diminished Radix algorithm.
2003-03-22 10:10:20 -05:00
*
2003-05-17 08:33:54 -04:00
* Based on algorithm from the paper
2003-03-22 10:10:20 -05:00
*
* "Generating Efficient Primes for Discrete Log Cryptosystems"
* Chae Hoon Lim, Pil Loong Lee,
* POSTECH Information Research Laboratories
*
* The modulus must be of a special format [see manual]
2003-05-29 09:35:26 -04:00
*
* Has been modified to use algorithm 7.10 from the LTM book instead
2003-03-22 10:10:20 -05:00
*/
int
2003-05-29 09:35:26 -04:00
mp_dr_reduce (mp_int * x, mp_int * n, mp_digit k)
2003-03-22 10:10:20 -05:00
{
2003-05-29 09:35:26 -04:00
int err, i, m;
mp_word r;
mp_digit mu, *tmpx1, *tmpx2;
/* m = digits in modulus */
m = n->used;
/* ensure that "x" has at least 2m digits */
if (x->alloc < m + m) {
if ((err = mp_grow (x, m + m)) != MP_OKAY) {
2003-03-22 10:10:20 -05:00
return err;
}
}
2003-05-17 08:33:54 -04:00
2003-05-29 09:35:26 -04:00
/* top of loop, this is where the code resumes if
* another reduction pass is required.
*/
top:
/* aliases for digits */
/* alias for lower half of x */
tmpx1 = x->dp;
/* alias for upper half of x, or x/B**m */
tmpx2 = x->dp + m;
/* set carry to zero */
mu = 0;
/* compute (x mod B**m) + mp * [x/B**m] inline and inplace */
for (i = 0; i < m; i++) {
r = ((mp_word)*tmpx2++) * ((mp_word)k) + *tmpx1 + mu;
2003-06-19 06:04:50 -04:00
*tmpx1++ = (mp_digit)(r & MP_MASK);
mu = (mp_digit)(r >> ((mp_word)DIGIT_BIT));
2003-03-22 10:10:20 -05:00
}
2003-05-29 09:35:26 -04:00
/* set final carry */
*tmpx1++ = mu;
/* zero words above m */
for (i = m + 1; i < x->used; i++) {
*tmpx1++ = 0;
2003-03-22 10:10:20 -05:00
}
/* clamp, sub and return */
2003-05-29 09:35:26 -04:00
mp_clamp (x);
2003-05-17 08:33:54 -04:00
2003-05-29 09:35:26 -04:00
/* if x >= n then subtract and reduce again
* Each successive "recursion" makes the input smaller and smaller.
*/
if (mp_cmp_mag (x, n) != MP_LT) {
s_mp_sub(x, n, x);
goto top;
2003-03-22 10:10:20 -05:00
}
return MP_OKAY;
}