bn_mp_montgomery_reduce.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_MONTGOMERY_REDUCE_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* computes xR**-1 == x (mod N) via Montgomery Reduction */
  6. mp_err mp_montgomery_reduce(mp_int *x, const mp_int *n, mp_digit rho)
  7. {
  8. int ix, digs;
  9. mp_err err;
  10. mp_digit mu;
  11. /* can the fast reduction [comba] method be used?
  12. *
  13. * Note that unlike in mul you're safely allowed *less*
  14. * than the available columns [255 per default] since carries
  15. * are fixed up in the inner loop.
  16. */
  17. digs = (n->used * 2) + 1;
  18. if ((digs < MP_WARRAY) &&
  19. (x->used <= MP_WARRAY) &&
  20. (n->used < MP_MAXFAST)) {
  21. return s_mp_montgomery_reduce_fast(x, n, rho);
  22. }
  23. /* grow the input as required */
  24. if (x->alloc < digs) {
  25. if ((err = mp_grow(x, digs)) != MP_OKAY) {
  26. return err;
  27. }
  28. }
  29. x->used = digs;
  30. for (ix = 0; ix < n->used; ix++) {
  31. /* mu = ai * rho mod b
  32. *
  33. * The value of rho must be precalculated via
  34. * montgomery_setup() such that
  35. * it equals -1/n0 mod b this allows the
  36. * following inner loop to reduce the
  37. * input one digit at a time
  38. */
  39. mu = (mp_digit)(((mp_word)x->dp[ix] * (mp_word)rho) & MP_MASK);
  40. /* a = a + mu * m * b**i */
  41. {
  42. int iy;
  43. mp_digit *tmpn, *tmpx, u;
  44. mp_word r;
  45. /* alias for digits of the modulus */
  46. tmpn = n->dp;
  47. /* alias for the digits of x [the input] */
  48. tmpx = x->dp + ix;
  49. /* set the carry to zero */
  50. u = 0;
  51. /* Multiply and add in place */
  52. for (iy = 0; iy < n->used; iy++) {
  53. /* compute product and sum */
  54. r = ((mp_word)mu * (mp_word)*tmpn++) +
  55. (mp_word)u + (mp_word)*tmpx;
  56. /* get carry */
  57. u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
  58. /* fix digit */
  59. *tmpx++ = (mp_digit)(r & (mp_word)MP_MASK);
  60. }
  61. /* At this point the ix'th digit of x should be zero */
  62. /* propagate carries upwards as required*/
  63. while (u != 0u) {
  64. *tmpx += u;
  65. u = *tmpx >> MP_DIGIT_BIT;
  66. *tmpx++ &= MP_MASK;
  67. }
  68. }
  69. }
  70. /* at this point the n.used'th least
  71. * significant digits of x are all zero
  72. * which means we can shift x to the
  73. * right by n.used digits and the
  74. * residue is unchanged.
  75. */
  76. /* x = x/b**n.used */
  77. mp_clamp(x);
  78. mp_rshd(x, n->used);
  79. /* if x >= n then x = x - n */
  80. if (mp_cmp_mag(x, n) != MP_LT) {
  81. return s_mp_sub(x, n, x);
  82. }
  83. return MP_OKAY;
  84. }
  85. #endif