bn_mp_montgomery_setup.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <tommath.h>
  2. #ifdef BN_MP_MONTGOMERY_SETUP_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis
  4. *
  5. * LibTomMath is a library that provides multiple-precision
  6. * integer arithmetic as well as number theoretic functionality.
  7. *
  8. * The library was designed directly after the MPI library by
  9. * Michael Fromberger but has been written from scratch with
  10. * additional optimizations in place.
  11. *
  12. * The library is free for all purposes without any express
  13. * guarantee it works.
  14. *
  15. * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
  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. /* fast inversion mod 2**k
  23. *
  24. * Based on the fact that
  25. *
  26. * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
  27. * => 2*X*A - X*X*A*A = 1
  28. * => 2*(1) - (1) = 1
  29. */
  30. b = n->dp[0];
  31. if ((b & 1) == 0) {
  32. return MP_VAL;
  33. }
  34. x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
  35. x *= 2 - b * x; /* here x*a==1 mod 2**8 */
  36. #if !defined(MP_8BIT)
  37. x *= 2 - b * x; /* here x*a==1 mod 2**16 */
  38. #endif
  39. #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
  40. x *= 2 - b * x; /* here x*a==1 mod 2**32 */
  41. #endif
  42. #ifdef MP_64BIT
  43. x *= 2 - b * x; /* here x*a==1 mod 2**64 */
  44. #endif
  45. /* rho = -1/m mod b */
  46. *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK;
  47. return MP_OKAY;
  48. }
  49. #endif
  50. /* $Source: /cvs/libtom/libtommath/bn_mp_montgomery_setup.c,v $ */
  51. /* $Revision: 1.4 $ */
  52. /* $Date: 2006/12/04 21:34:03 $ */