bn_s_mp_mul_digs.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "tommath_private.h"
  2. #ifdef BN_S_MP_MUL_DIGS_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* multiplies |a| * |b| and only computes upto digs digits of result
  6. * HAC pp. 595, Algorithm 14.12 Modified so you can control how
  7. * many digits of output are created.
  8. */
  9. mp_err s_mp_mul_digs(const mp_int *a, const mp_int *b, mp_int *c, int digs)
  10. {
  11. mp_int t;
  12. mp_err err;
  13. int pa, pb, ix, iy;
  14. mp_digit u;
  15. mp_word r;
  16. mp_digit tmpx, *tmpt, *tmpy;
  17. /* can we use the fast multiplier? */
  18. if ((digs < MP_WARRAY) &&
  19. (MP_MIN(a->used, b->used) < MP_MAXFAST)) {
  20. return s_mp_mul_digs_fast(a, b, c, digs);
  21. }
  22. if ((err = mp_init_size(&t, digs)) != MP_OKAY) {
  23. return err;
  24. }
  25. t.used = digs;
  26. /* compute the digits of the product directly */
  27. pa = a->used;
  28. for (ix = 0; ix < pa; ix++) {
  29. /* set the carry to zero */
  30. u = 0;
  31. /* limit ourselves to making digs digits of output */
  32. pb = MP_MIN(b->used, digs - ix);
  33. /* setup some aliases */
  34. /* copy of the digit from a used within the nested loop */
  35. tmpx = a->dp[ix];
  36. /* an alias for the destination shifted ix places */
  37. tmpt = t.dp + ix;
  38. /* an alias for the digits of b */
  39. tmpy = b->dp;
  40. /* compute the columns of the output and propagate the carry */
  41. for (iy = 0; iy < pb; iy++) {
  42. /* compute the column as a mp_word */
  43. r = (mp_word)*tmpt +
  44. ((mp_word)tmpx * (mp_word)*tmpy++) +
  45. (mp_word)u;
  46. /* the new column is the lower part of the result */
  47. *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
  48. /* get the carry word from the result */
  49. u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
  50. }
  51. /* set carry if it is placed below digs */
  52. if ((ix + iy) < digs) {
  53. *tmpt = u;
  54. }
  55. }
  56. mp_clamp(&t);
  57. mp_exch(&t, c);
  58. mp_clear(&t);
  59. return MP_OKAY;
  60. }
  61. #endif