1
0
mirror of http://galexander.org/git/simplesshd.git synced 2024-11-30 19:28:10 +00:00
simplesshd/dropbear/libtommath/bn_mp_dr_reduce.c

79 lines
2.0 KiB
C
Raw Normal View History

2020-12-28 21:40:37 +00:00
#include "tommath_private.h"
2014-12-10 21:56:49 +00:00
#ifdef BN_MP_DR_REDUCE_C
2020-12-28 21:40:37 +00:00
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
2014-12-10 21:56:49 +00:00
/* reduce "x" in place modulo "n" using the Diminished Radix algorithm.
*
* Based on algorithm from the paper
*
* "Generating Efficient Primes for Discrete Log Cryptosystems"
* Chae Hoon Lim, Pil Joong Lee,
* POSTECH Information Research Laboratories
*
* The modulus must be of a special format [see manual]
*
* Has been modified to use algorithm 7.10 from the LTM book instead
*
* Input x must be in the range 0 <= x <= (n-1)**2
*/
2020-12-28 21:40:37 +00:00
mp_err mp_dr_reduce(mp_int *x, const mp_int *n, mp_digit k)
2014-12-10 21:56:49 +00:00
{
2020-12-28 21:40:37 +00:00
mp_err err;
int i, m;
mp_word r;
mp_digit mu, *tmpx1, *tmpx2;
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* m = digits in modulus */
m = n->used;
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* ensure that "x" has at least 2m digits */
if (x->alloc < (m + m)) {
if ((err = mp_grow(x, m + m)) != MP_OKAY) {
return err;
}
}
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* top of loop, this is where the code resumes if
* another reduction pass is required.
*/
2014-12-10 21:56:49 +00:00
top:
2020-12-28 21:40:37 +00:00
/* aliases for digits */
/* alias for lower half of x */
tmpx1 = x->dp;
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* alias for upper half of x, or x/B**m */
tmpx2 = x->dp + m;
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* set carry to zero */
mu = 0;
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* compute (x mod B**m) + k * [x/B**m] inline and inplace */
for (i = 0; i < m; i++) {
r = ((mp_word)*tmpx2++ * (mp_word)k) + *tmpx1 + mu;
2014-12-10 21:56:49 +00:00
*tmpx1++ = (mp_digit)(r & MP_MASK);
2020-12-28 21:40:37 +00:00
mu = (mp_digit)(r >> ((mp_word)MP_DIGIT_BIT));
}
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* set final carry */
*tmpx1++ = mu;
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* zero words above m */
MP_ZERO_DIGITS(tmpx1, (x->used - m) - 1);
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* clamp, sub and return */
mp_clamp(x);
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00: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) {
if ((err = s_mp_sub(x, n, x)) != MP_OKAY) {
return err;
}
goto top;
}
return MP_OKAY;
2014-12-10 21:56:49 +00:00
}
#endif