bn_mp_reduce_2k.c 947 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_REDUCE_2K_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. mp_err mp_reduce_2k(mp_int *a, const mp_int *n, mp_digit d)
  7. {
  8. mp_int q;
  9. mp_err err;
  10. int p;
  11. if ((err = mp_init(&q)) != MP_OKAY) {
  12. return err;
  13. }
  14. p = mp_count_bits(n);
  15. top:
  16. /* q = a/2**p, a = a mod 2**p */
  17. if ((err = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
  18. goto LBL_ERR;
  19. }
  20. if (d != 1u) {
  21. /* q = q * d */
  22. if ((err = mp_mul_d(&q, d, &q)) != MP_OKAY) {
  23. goto LBL_ERR;
  24. }
  25. }
  26. /* a = a + q */
  27. if ((err = s_mp_add(a, &q, a)) != MP_OKAY) {
  28. goto LBL_ERR;
  29. }
  30. if (mp_cmp_mag(a, n) != MP_LT) {
  31. if ((err = s_mp_sub(a, n, a)) != MP_OKAY) {
  32. goto LBL_ERR;
  33. }
  34. goto top;
  35. }
  36. LBL_ERR:
  37. mp_clear(&q);
  38. return err;
  39. }
  40. #endif