Bump actions/upload-artifacts version
[libtommath.git] / mp_montgomery_reduce.c
blobdbf45d3cfbd819c1589cac98f777d6a627cfe0e1
1 #include "tommath_private.h"
2 #ifdef MP_MONTGOMERY_REDUCE_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* computes xR**-1 == x (mod N) via Montgomery Reduction */
7 mp_err mp_montgomery_reduce(mp_int *x, const mp_int *n, mp_digit rho)
9 mp_err err;
10 int ix, digs;
12 /* can the fast reduction [comba] method be used?
14 * Note that unlike in mul you're safely allowed *less*
15 * than the available columns [255 per default] since carries
16 * are fixed up in the inner loop.
18 digs = (n->used * 2) + 1;
19 if ((digs < MP_WARRAY) &&
20 (x->used <= MP_WARRAY) &&
21 (n->used < MP_MAX_COMBA)) {
22 return s_mp_montgomery_reduce_comba(x, n, rho);
25 /* grow the input as required */
26 if ((err = mp_grow(x, digs)) != MP_OKAY) {
27 return err;
29 x->used = digs;
31 for (ix = 0; ix < n->used; ix++) {
32 int iy;
33 mp_digit u, mu;
35 /* mu = ai * rho mod b
37 * The value of rho must be precalculated via
38 * montgomery_setup() such that
39 * it equals -1/n0 mod b this allows the
40 * following inner loop to reduce the
41 * input one digit at a time
43 mu = (mp_digit)(((mp_word)x->dp[ix] * (mp_word)rho) & MP_MASK);
45 /* a = a + mu * m * b**i */
47 /* Multiply and add in place */
48 u = 0;
49 for (iy = 0; iy < n->used; iy++) {
50 /* compute product and sum */
51 mp_word r = ((mp_word)mu * (mp_word)n->dp[iy]) +
52 (mp_word)u + (mp_word)x->dp[ix + iy];
54 /* get carry */
55 u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
57 /* fix digit */
58 x->dp[ix + iy] = (mp_digit)(r & (mp_word)MP_MASK);
60 /* At this point the ix'th digit of x should be zero */
62 /* propagate carries upwards as required*/
63 while (u != 0u) {
64 x->dp[ix + iy] += u;
65 u = x->dp[ix + iy] >> MP_DIGIT_BIT;
66 x->dp[ix + iy] &= MP_MASK;
67 ++iy;
71 /* at this point the n.used'th least
72 * significant digits of x are all zero
73 * which means we can shift x to the
74 * right by n.used digits and the
75 * residue is unchanged.
78 /* x = x/b**n.used */
79 mp_clamp(x);
80 mp_rshd(x, n->used);
82 /* if x >= n then x = x - n */
83 if (mp_cmp_mag(x, n) != MP_LT) {
84 return s_mp_sub(x, n, x);
87 return MP_OKAY;
89 #endif