1 #include "tommath_private.h"
2 #ifdef BN_MP_DR_REDUCE_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* reduce "x" in place modulo "n" using the Diminished Radix algorithm.
8 * Based on algorithm from the paper
10 * "Generating Efficient Primes for Discrete Log Cryptosystems"
11 * Chae Hoon Lim, Pil Joong Lee,
12 * POSTECH Information Research Laboratories
14 * The modulus must be of a special format [see manual]
16 * Has been modified to use algorithm 7.10 from the LTM book instead
18 * Input x must be in the range 0 <= x <= (n-1)**2
20 mp_err mp_dr_reduce(mp_int *x, const mp_int *n, mp_digit k)
25 mp_digit mu, *tmpx1, *tmpx2;
27 /* m = digits in modulus */
30 /* ensure that "x" has at least 2m digits */
31 if (x->alloc < (m + m)) {
32 if ((err = mp_grow(x, m + m)) != MP_OKAY) {
37 /* top of loop, this is where the code resumes if
38 * another reduction pass is required.
41 /* aliases for digits */
42 /* alias for lower half of x */
45 /* alias for upper half of x, or x/B**m */
48 /* set carry to zero */
51 /* compute (x mod B**m) + k * [x/B**m] inline and inplace */
52 for (i = 0; i < m; i++) {
53 r = ((mp_word)*tmpx2++ * (mp_word)k) + *tmpx1 + mu;
54 *tmpx1++ = (mp_digit)(r & MP_MASK);
55 mu = (mp_digit)(r >> ((mp_word)MP_DIGIT_BIT));
61 /* zero words above m */
62 MP_ZERO_DIGITS(tmpx1, (x->used - m) - 1);
64 /* clamp, sub and return */
67 /* if x >= n then subtract and reduce again
68 * Each successive "recursion" makes the input smaller and smaller.
70 if (mp_cmp_mag(x, n) != MP_LT) {
71 if ((err = s_mp_sub(x, n, x)) != MP_OKAY) {