1 /* $NetBSD: bn_mp_montgomery_setup.c,v 1.1.1.1 2011/04/13 18:14:54 elric Exp $ */ 2 3 #include <tommath.h> 4 #ifdef BN_MP_MONTGOMERY_SETUP_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 /* setups the montgomery reduction stuff */ 21 int 22 mp_montgomery_setup (mp_int * n, mp_digit * rho) 23 { 24 mp_digit x, b; 25 26 /* fast inversion mod 2**k 27 * 28 * Based on the fact that 29 * 30 * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n) 31 * => 2*X*A - X*X*A*A = 1 32 * => 2*(1) - (1) = 1 33 */ 34 b = n->dp[0]; 35 36 if ((b & 1) == 0) { 37 return MP_VAL; 38 } 39 40 x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */ 41 x *= 2 - b * x; /* here x*a==1 mod 2**8 */ 42 #if !defined(MP_8BIT) 43 x *= 2 - b * x; /* here x*a==1 mod 2**16 */ 44 #endif 45 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT)) 46 x *= 2 - b * x; /* here x*a==1 mod 2**32 */ 47 #endif 48 #ifdef MP_64BIT 49 x *= 2 - b * x; /* here x*a==1 mod 2**64 */ 50 #endif 51 52 /* rho = -1/m mod b */ 53 *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK; 54 55 return MP_OKAY; 56 } 57 #endif 58 59 /* Source: /cvs/libtom/libtommath/bn_mp_montgomery_setup.c,v */ 60 /* Revision: 1.5 */ 61 /* Date: 2006/12/28 01:25:13 */ 62