bn_mp_montgomery_setup.c 1.57 KB
Newer Older
1
#include "tommath_private.h"
2 3 4 5 6 7 8 9 10 11
#ifdef BN_MP_MONTGOMERY_SETUP_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis
 *
 * LibTomMath is a library that provides multiple-precision
 * integer arithmetic as well as number theoretic functionality.
 *
 * The library was designed directly after the MPI library by
 * Michael Fromberger but has been written from scratch with
 * additional optimizations in place.
 *
12
 * SPDX-License-Identifier: Unlicense
13 14 15
 */

/* setups the montgomery reduction stuff */
16
int mp_montgomery_setup(const mp_int *n, mp_digit *rho)
17
{
18
   mp_digit x, b;
19

20 21 22 23 24 25 26 27 28
   /* fast inversion mod 2**k
    *
    * Based on the fact that
    *
    * XA = 1 (mod 2**n)  =>  (X(2-XA)) A = 1 (mod 2**2n)
    *                    =>  2*X*A - X*X*A*A = 1
    *                    =>  2*(1) - (1)     = 1
    */
   b = n->dp[0];
29

30 31 32
   if ((b & 1u) == 0u) {
      return MP_VAL;
   }
33

34 35
   x = (((b + 2u) & 4u) << 1) + b; /* here x*a==1 mod 2**4 */
   x *= 2u - (b * x);              /* here x*a==1 mod 2**8 */
36
#if !defined(MP_8BIT)
37
   x *= 2u - (b * x);              /* here x*a==1 mod 2**16 */
38 39
#endif
#if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
40
   x *= 2u - (b * x);              /* here x*a==1 mod 2**32 */
41 42
#endif
#ifdef MP_64BIT
43
   x *= 2u - (b * x);              /* here x*a==1 mod 2**64 */
44 45
#endif

46 47
   /* rho = -1/m mod b */
   *rho = (mp_digit)(((mp_word)1 << (mp_word)DIGIT_BIT) - x) & MP_MASK;
48

49
   return MP_OKAY;
50 51 52
}
#endif

53 54 55
/* ref:         HEAD -> master, tag: v1.1.0 */
/* git commit:  08549ad6bc8b0cede0b357a9c341c5c6473a9c55 */
/* commit time: 2019-01-28 20:32:32 +0100 */