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
6 /* calculate c = a**b using a square-multiply algorithm */
mp_expt_u32(const mp_int * a,unsigned int b,mp_int * c)7 mp_err mp_expt_u32(const mp_int *a, unsigned int b, mp_int *c)
8 {
9 mp_err err;
10
11 mp_int g;
12
13 if ((err = mp_init_copy(&g, a)) != MP_OKAY) {
14 return err;
15 }
16
17 /* set initial result */
18 mp_set(c, 1uL);
19
20 while (b > 0u) {
21 /* if the bit is set multiply */
22 if ((b & 1u) != 0u) {
23 if ((err = mp_mul(c, &g, c)) != MP_OKAY) {
24 goto LBL_ERR;
25 }
26 }
27
28 /* square */
29 if (b > 1u) {
30 if ((err = mp_sqr(&g, &g)) != MP_OKAY) {
31 goto LBL_ERR;
32 }
33 }
34
35 /* shift to next bit */
36 b >>= 1;
37 }
38
39 err = MP_OKAY;
40
41 LBL_ERR:
42 mp_clear(&g);
43 return err;
44 }
45
46 #endif
47