bn_s_mp_sqr.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <tommath.h>
  2. #ifdef BN_S_MP_SQR_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. /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
  18. int s_mp_sqr (mp_int * a, mp_int * b)
  19. {
  20. mp_int t;
  21. int res, ix, iy, pa;
  22. mp_word r;
  23. mp_digit u, tmpx, *tmpt;
  24. pa = a->used;
  25. if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
  26. return res;
  27. }
  28. /* default used is maximum possible size */
  29. t.used = 2*pa + 1;
  30. for (ix = 0; ix < pa; ix++) {
  31. /* first calculate the digit at 2*ix */
  32. /* calculate double precision result */
  33. r = ((mp_word) t.dp[2*ix]) +
  34. ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]);
  35. /* store lower part in result */
  36. t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
  37. /* get the carry */
  38. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  39. /* left hand side of A[ix] * A[iy] */
  40. tmpx = a->dp[ix];
  41. /* alias for where to store the results */
  42. tmpt = t.dp + (2*ix + 1);
  43. for (iy = ix + 1; iy < pa; iy++) {
  44. /* first calculate the product */
  45. r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
  46. /* now calculate the double precision result, note we use
  47. * addition instead of *2 since it's easier to optimize
  48. */
  49. r = ((mp_word) *tmpt) + r + r + ((mp_word) u);
  50. /* store lower part */
  51. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  52. /* get carry */
  53. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  54. }
  55. /* propagate upwards */
  56. while (u != ((mp_digit) 0)) {
  57. r = ((mp_word) *tmpt) + ((mp_word) u);
  58. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  59. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  60. }
  61. }
  62. mp_clamp (&t);
  63. mp_exch (&t, b);
  64. mp_clear (&t);
  65. return MP_OKAY;
  66. }
  67. #endif
  68. /* $Source: /cvs/libtom/libtommath/bn_s_mp_sqr.c,v $ */
  69. /* $Revision: 1.3 $ */
  70. /* $Date: 2006/03/31 14:18:44 $ */