1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
3 * LibTomMath is library that provides for multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
6 * The library is designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
10 * The library is free for all purposes without any express
13 * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
17 /* setups the montgomery reduction stuff */
19 mp_montgomery_setup (mp_int * n, mp_digit * rho)
23 /* fast inversion mod 2**k
25 * Based on the fact that
27 * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
28 * => 2*X*A - X*X*A*A = 1
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 */
40 x *= 2 - b * x; /* here x*a==1 mod 2**16 */
42 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
43 x *= 2 - b * x; /* here x*a==1 mod 2**32 */
46 x *= 2 - b * x; /* here x*a==1 mod 2**64 */
49 /* rho = -1/m mod b */
50 *rho = (((mp_digit) 1 << ((mp_digit) DIGIT_BIT)) - x) & MP_MASK;