bn_mp_reduce_2k_l.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <tommath.h>
  2. #ifdef BN_MP_REDUCE_2K_L_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. /* reduces a modulo n where n is of the form 2**p - d
  18. This differs from reduce_2k since "d" can be larger
  19. than a single digit.
  20. */
  21. int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
  22. {
  23. mp_int q;
  24. int p, res;
  25. if ((res = mp_init(&q)) != MP_OKAY) {
  26. return res;
  27. }
  28. p = mp_count_bits(n);
  29. top:
  30. /* q = a/2**p, a = a mod 2**p */
  31. if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
  32. goto ERR;
  33. }
  34. /* q = q * d */
  35. if ((res = mp_mul(&q, d, &q)) != MP_OKAY) {
  36. goto ERR;
  37. }
  38. /* a = a + q */
  39. if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
  40. goto ERR;
  41. }
  42. if (mp_cmp_mag(a, n) != MP_LT) {
  43. s_mp_sub(a, n, a);
  44. goto top;
  45. }
  46. ERR:
  47. mp_clear(&q);
  48. return res;
  49. }
  50. #endif
  51. /* $Source: /cvs/libtom/libtommath/bn_mp_reduce_2k_l.c,v $ */
  52. /* $Revision: 1.3 $ */
  53. /* $Date: 2006/03/31 14:18:44 $ */