142
|
1 #include <tommath.h> |
|
2 #ifdef BN_MP_REDUCE_C |
2
|
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis |
|
4 * |
|
5 * LibTomMath is a library that provides multiple-precision |
|
6 * integer arithmetic as well as number theoretic functionality. |
|
7 * |
|
8 * The library was designed directly after the MPI library by |
|
9 * Michael Fromberger but has been written from scratch with |
|
10 * additional optimizations in place. |
|
11 * |
|
12 * The library is free for all purposes without any express |
|
13 * guarantee it works. |
|
14 * |
|
15 * Tom St Denis, [email protected], http://math.libtomcrypt.org |
|
16 */ |
|
17 |
|
18 /* reduces x mod m, assumes 0 < x < m**2, mu is |
|
19 * precomputed via mp_reduce_setup. |
|
20 * From HAC pp.604 Algorithm 14.42 |
|
21 */ |
|
22 int |
|
23 mp_reduce (mp_int * x, mp_int * m, mp_int * mu) |
|
24 { |
|
25 mp_int q; |
|
26 int res, um = m->used; |
|
27 |
|
28 /* q = x */ |
|
29 if ((res = mp_init_copy (&q, x)) != MP_OKAY) { |
|
30 return res; |
|
31 } |
|
32 |
|
33 /* q1 = x / b**(k-1) */ |
|
34 mp_rshd (&q, um - 1); |
|
35 |
|
36 /* according to HAC this optimization is ok */ |
|
37 if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) { |
|
38 if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) { |
|
39 goto CLEANUP; |
|
40 } |
|
41 } else { |
142
|
42 #ifdef BN_S_MP_MUL_HIGH_DIGS_C |
2
|
43 if ((res = s_mp_mul_high_digs (&q, mu, &q, um - 1)) != MP_OKAY) { |
|
44 goto CLEANUP; |
|
45 } |
142
|
46 #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C) |
|
47 if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um - 1)) != MP_OKAY) { |
|
48 goto CLEANUP; |
|
49 } |
|
50 #else |
|
51 { |
|
52 res = MP_VAL; |
|
53 goto CLEANUP; |
|
54 } |
|
55 #endif |
2
|
56 } |
|
57 |
|
58 /* q3 = q2 / b**(k+1) */ |
|
59 mp_rshd (&q, um + 1); |
|
60 |
|
61 /* x = x mod b**(k+1), quick (no division) */ |
|
62 if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) { |
|
63 goto CLEANUP; |
|
64 } |
|
65 |
|
66 /* q = q * m mod b**(k+1), quick (no division) */ |
|
67 if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) { |
|
68 goto CLEANUP; |
|
69 } |
|
70 |
|
71 /* x = x - q */ |
|
72 if ((res = mp_sub (x, &q, x)) != MP_OKAY) { |
|
73 goto CLEANUP; |
|
74 } |
|
75 |
|
76 /* If x < 0, add b**(k+1) to it */ |
|
77 if (mp_cmp_d (x, 0) == MP_LT) { |
|
78 mp_set (&q, 1); |
|
79 if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) |
|
80 goto CLEANUP; |
|
81 if ((res = mp_add (x, &q, x)) != MP_OKAY) |
|
82 goto CLEANUP; |
|
83 } |
|
84 |
|
85 /* Back off if it's too big */ |
|
86 while (mp_cmp (x, m) != MP_LT) { |
|
87 if ((res = s_mp_sub (x, m, x)) != MP_OKAY) { |
|
88 goto CLEANUP; |
|
89 } |
|
90 } |
|
91 |
|
92 CLEANUP: |
|
93 mp_clear (&q); |
|
94 |
|
95 return res; |
|
96 } |
142
|
97 #endif |