bn_s_mp_sqr.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "tommath_private.h"
  2. #ifdef BN_S_MP_SQR_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
  6. mp_err s_mp_sqr(const mp_int *a, mp_int *b)
  7. {
  8. mp_int t;
  9. int ix, iy, pa;
  10. mp_err err;
  11. mp_word r;
  12. mp_digit u, tmpx, *tmpt;
  13. pa = a->used;
  14. if ((err = mp_init_size(&t, (2 * pa) + 1)) != MP_OKAY) {
  15. return err;
  16. }
  17. /* default used is maximum possible size */
  18. t.used = (2 * pa) + 1;
  19. for (ix = 0; ix < pa; ix++) {
  20. /* first calculate the digit at 2*ix */
  21. /* calculate double precision result */
  22. r = (mp_word)t.dp[2*ix] +
  23. ((mp_word)a->dp[ix] * (mp_word)a->dp[ix]);
  24. /* store lower part in result */
  25. t.dp[ix+ix] = (mp_digit)(r & (mp_word)MP_MASK);
  26. /* get the carry */
  27. u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
  28. /* left hand side of A[ix] * A[iy] */
  29. tmpx = a->dp[ix];
  30. /* alias for where to store the results */
  31. tmpt = t.dp + ((2 * ix) + 1);
  32. for (iy = ix + 1; iy < pa; iy++) {
  33. /* first calculate the product */
  34. r = (mp_word)tmpx * (mp_word)a->dp[iy];
  35. /* now calculate the double precision result, note we use
  36. * addition instead of *2 since it's easier to optimize
  37. */
  38. r = (mp_word)*tmpt + r + r + (mp_word)u;
  39. /* store lower part */
  40. *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
  41. /* get carry */
  42. u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
  43. }
  44. /* propagate upwards */
  45. while (u != 0uL) {
  46. r = (mp_word)*tmpt + (mp_word)u;
  47. *tmpt++ = (mp_digit)(r & (mp_word)MP_MASK);
  48. u = (mp_digit)(r >> (mp_word)MP_DIGIT_BIT);
  49. }
  50. }
  51. mp_clamp(&t);
  52. mp_exch(&t, b);
  53. mp_clear(&t);
  54. return MP_OKAY;
  55. }
  56. #endif