comparison bn_mp_reduce.c @ 2:86e0b50a9b58 libtommath-orig ltm-0.30-orig

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