bn_mp_expt_u32.c 878 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_EXPT_U32_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* calculate c = a**b using a square-multiply algorithm */
  6. mp_err mp_expt_u32(const mp_int *a, uint32_t b, mp_int *c)
  7. {
  8. mp_err err;
  9. mp_int g;
  10. if ((err = mp_init_copy(&g, a)) != MP_OKAY) {
  11. return err;
  12. }
  13. /* set initial result */
  14. mp_set(c, 1uL);
  15. while (b > 0u) {
  16. /* if the bit is set multiply */
  17. if ((b & 1u) != 0u) {
  18. if ((err = mp_mul(c, &g, c)) != MP_OKAY) {
  19. goto LBL_ERR;
  20. }
  21. }
  22. /* square */
  23. if (b > 1u) {
  24. if ((err = mp_sqr(&g, &g)) != MP_OKAY) {
  25. goto LBL_ERR;
  26. }
  27. }
  28. /* shift to next bit */
  29. b >>= 1;
  30. }
  31. err = MP_OKAY;
  32. LBL_ERR:
  33. mp_clear(&g);
  34. return err;
  35. }
  36. #endif