comparison bn_mp_montgomery_setup.c @ 1:22d5cf7d4b1a libtommath

Renaming branch
author Matt Johnston <matt@ucc.asn.au>
date Mon, 31 May 2004 18:23:46 +0000
parents
children d29b64170cf0
comparison
equal deleted inserted replaced
-1:000000000000 1:22d5cf7d4b1a
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 /* setups the montgomery reduction stuff */
18 int
19 mp_montgomery_setup (mp_int * n, mp_digit * rho)
20 {
21 mp_digit x, b;
22
23 /* fast inversion mod 2**k
24 *
25 * Based on the fact that
26 *
27 * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
28 * => 2*X*A - X*X*A*A = 1
29 * => 2*(1) - (1) = 1
30 */
31 b = n->dp[0];
32
33 if ((b & 1) == 0) {
34 return MP_VAL;
35 }
36
37 x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
38 x *= 2 - b * x; /* here x*a==1 mod 2**8 */
39 #if !defined(MP_8BIT)
40 x *= 2 - b * x; /* here x*a==1 mod 2**16 */
41 #endif
42 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
43 x *= 2 - b * x; /* here x*a==1 mod 2**32 */
44 #endif
45 #ifdef MP_64BIT
46 x *= 2 - b * x; /* here x*a==1 mod 2**64 */
47 #endif
48
49 /* rho = -1/m mod b */
50 *rho = (((mp_digit) 1 << ((mp_digit) DIGIT_BIT)) - x) & MP_MASK;
51
52 return MP_OKAY;
53 }