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