s4:torture: Adapt KDC canon test to Heimdal upstream changes
[samba.git] / source4 / heimdal / lib / hcrypto / libtommath / bn_mp_reduce.c
1 #include "tommath_private.h"
2 #ifdef BN_MP_REDUCE_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
5
6 /* reduces x mod m, assumes 0 < x < m**2, mu is
7  * precomputed via mp_reduce_setup.
8  * From HAC pp.604 Algorithm 14.42
9  */
10 mp_err mp_reduce(mp_int *x, const mp_int *m, const mp_int *mu)
11 {
12    mp_int  q;
13    mp_err  err;
14    int     um = m->used;
15
16    /* q = x */
17    if ((err = mp_init_copy(&q, x)) != MP_OKAY) {
18       return err;
19    }
20
21    /* q1 = x / b**(k-1)  */
22    mp_rshd(&q, um - 1);
23
24    /* according to HAC this optimization is ok */
25    if ((mp_digit)um > ((mp_digit)1 << (MP_DIGIT_BIT - 1))) {
26       if ((err = mp_mul(&q, mu, &q)) != MP_OKAY) {
27          goto CLEANUP;
28       }
29    } else if (MP_HAS(S_MP_MUL_HIGH_DIGS)) {
30       if ((err = s_mp_mul_high_digs(&q, mu, &q, um)) != MP_OKAY) {
31          goto CLEANUP;
32       }
33    } else if (MP_HAS(S_MP_MUL_HIGH_DIGS_FAST)) {
34       if ((err = s_mp_mul_high_digs_fast(&q, mu, &q, um)) != MP_OKAY) {
35          goto CLEANUP;
36       }
37    } else {
38       err = MP_VAL;
39       goto CLEANUP;
40    }
41
42    /* q3 = q2 / b**(k+1) */
43    mp_rshd(&q, um + 1);
44
45    /* x = x mod b**(k+1), quick (no division) */
46    if ((err = mp_mod_2d(x, MP_DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
47       goto CLEANUP;
48    }
49
50    /* q = q * m mod b**(k+1), quick (no division) */
51    if ((err = s_mp_mul_digs(&q, m, &q, um + 1)) != MP_OKAY) {
52       goto CLEANUP;
53    }
54
55    /* x = x - q */
56    if ((err = mp_sub(x, &q, x)) != MP_OKAY) {
57       goto CLEANUP;
58    }
59
60    /* If x < 0, add b**(k+1) to it */
61    if (mp_cmp_d(x, 0uL) == MP_LT) {
62       mp_set(&q, 1uL);
63       if ((err = mp_lshd(&q, um + 1)) != MP_OKAY) {
64          goto CLEANUP;
65       }
66       if ((err = mp_add(x, &q, x)) != MP_OKAY) {
67          goto CLEANUP;
68       }
69    }
70
71    /* Back off if it's too big */
72    while (mp_cmp(x, m) != MP_LT) {
73       if ((err = s_mp_sub(x, m, x)) != MP_OKAY) {
74          goto CLEANUP;
75       }
76    }
77
78 CLEANUP:
79    mp_clear(&q);
80
81    return err;
82 }
83 #endif