1 /* $NetBSD: bn_mp_montgomery_calc_normalization.c,v 1.1.1.2 2014/04/24 12:45:31 pettai Exp $ */
2
3 #include <tommath.h>
4 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
5 /* LibTomMath, multiple-precision integer library -- Tom St Denis
6 *
7 * LibTomMath is a library that provides multiple-precision
8 * integer arithmetic as well as number theoretic functionality.
9 *
10 * The library was designed directly after the MPI library by
11 * Michael Fromberger but has been written from scratch with
12 * additional optimizations in place.
13 *
14 * The library is free for all purposes without any express
15 * guarantee it works.
16 *
17 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
18 */
19
20 /*
21 * shifts with subtractions when the result is greater than b.
22 *
23 * The method is slightly modified to shift B unconditionally upto just under
24 * the leading bit of b. This saves alot of multiple precision shifting.
25 */
mp_montgomery_calc_normalization(mp_int * a,mp_int * b)26 int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
27 {
28 int x, bits, res;
29
30 /* how many bits of last digit does b use */
31 bits = mp_count_bits (b) % DIGIT_BIT;
32
33 if (b->used > 1) {
34 if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) {
35 return res;
36 }
37 } else {
38 mp_set(a, 1);
39 bits = 1;
40 }
41
42
43 /* now compute C = A * B mod b */
44 for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
45 if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
46 return res;
47 }
48 if (mp_cmp_mag (a, b) != MP_LT) {
49 if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
50 return res;
51 }
52 }
53 }
54
55 return MP_OKAY;
56 }
57 #endif
58
59 /* Source: /cvs/libtom/libtommath/bn_mp_montgomery_calc_normalization.c,v */
60 /* Revision: 1.4 */
61 /* Date: 2006/12/28 01:25:13 */
62