comparison bn_mp_montgomery_calc_normalization.c @ 142:d29b64170cf0 libtommath-orig

import of libtommath 0.32
author Matt Johnston <matt@ucc.asn.au>
date Sun, 19 Dec 2004 11:33:56 +0000
parents 86e0b50a9b58
children d8254fc979e9
comparison
equal deleted inserted replaced
19:e1037a1e12e7 142:d29b64170cf0
1 #include <tommath.h>
2 #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis 3 /* LibTomMath, multiple-precision integer library -- Tom St Denis
2 * 4 *
3 * LibTomMath is a library that provides multiple-precision 5 * LibTomMath is a library that provides multiple-precision
4 * integer arithmetic as well as number theoretic functionality. 6 * integer arithmetic as well as number theoretic functionality.
5 * 7 *
10 * The library is free for all purposes without any express 12 * The library is free for all purposes without any express
11 * guarantee it works. 13 * guarantee it works.
12 * 14 *
13 * Tom St Denis, [email protected], http://math.libtomcrypt.org 15 * Tom St Denis, [email protected], http://math.libtomcrypt.org
14 */ 16 */
15 #include <tommath.h>
16 17
17 /* calculates a = B^n mod b for Montgomery reduction 18 /*
18 * Where B is the base [e.g. 2^DIGIT_BIT].
19 * B^n mod b is computed by first computing
20 * A = B^(n-1) which doesn't require a reduction but a simple OR.
21 * then C = A * B = B^n is computed by performing upto DIGIT_BIT
22 * shifts with subtractions when the result is greater than b. 19 * shifts with subtractions when the result is greater than b.
23 * 20 *
24 * The method is slightly modified to shift B unconditionally upto just under 21 * The method is slightly modified to shift B unconditionally upto just under
25 * the leading bit of b. This saves alot of multiple precision shifting. 22 * the leading bit of b. This saves alot of multiple precision shifting.
26 */ 23 */
27 int 24 int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
28 mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
29 { 25 {
30 int x, bits, res; 26 int x, bits, res;
31 27
32 /* how many bits of last digit does b use */ 28 /* how many bits of last digit does b use */
33 bits = mp_count_bits (b) % DIGIT_BIT; 29 bits = mp_count_bits (b) % DIGIT_BIT;
34 30
35 /* compute A = B^(n-1) * 2^(bits-1) */ 31
36 if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) { 32 if (b->used > 1) {
37 return res; 33 if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) {
34 return res;
35 }
36 } else {
37 mp_set(a, 1);
38 bits = 1;
38 } 39 }
40
39 41
40 /* now compute C = A * B mod b */ 42 /* now compute C = A * B mod b */
41 for (x = bits - 1; x < (int)DIGIT_BIT; x++) { 43 for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
42 if ((res = mp_mul_2 (a, a)) != MP_OKAY) { 44 if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
43 return res; 45 return res;
49 } 51 }
50 } 52 }
51 53
52 return MP_OKAY; 54 return MP_OKAY;
53 } 55 }
56 #endif