bn_mp_reduce_2k_l.c 998 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_REDUCE_2K_L_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* reduces a modulo n where n is of the form 2**p - d
  6. This differs from reduce_2k since "d" can be larger
  7. than a single digit.
  8. */
  9. mp_err mp_reduce_2k_l(mp_int *a, const mp_int *n, const mp_int *d)
  10. {
  11. mp_int q;
  12. mp_err err;
  13. int p;
  14. if ((err = mp_init(&q)) != MP_OKAY) {
  15. return err;
  16. }
  17. p = mp_count_bits(n);
  18. top:
  19. /* q = a/2**p, a = a mod 2**p */
  20. if ((err = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
  21. goto LBL_ERR;
  22. }
  23. /* q = q * d */
  24. if ((err = mp_mul(&q, d, &q)) != MP_OKAY) {
  25. goto LBL_ERR;
  26. }
  27. /* a = a + q */
  28. if ((err = s_mp_add(a, &q, a)) != MP_OKAY) {
  29. goto LBL_ERR;
  30. }
  31. if (mp_cmp_mag(a, n) != MP_LT) {
  32. if ((err = s_mp_sub(a, n, a)) != MP_OKAY) {
  33. goto LBL_ERR;
  34. }
  35. goto top;
  36. }
  37. LBL_ERR:
  38. mp_clear(&q);
  39. return err;
  40. }
  41. #endif