forked from libtom/libtommath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbn_mp_expt.c
48 lines (46 loc) · 1.11 KB
/
bn_mp_expt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <tommath.h>
#ifdef BN_MP_EXPT_C
int mp_expt(mp_int *a, mp_int *b, mp_int *c)
{
mp_int tmp,e;
int err;
/* only positive exponents for now */
if (b->sign == MP_NEG) {
return MP_VAL;
}
if ((err = mp_init_multi(&tmp,&e,NULL)) != MP_OKAY) {
return err;
}
if ((err = mp_copy(a,&tmp)) != MP_OKAY) {
return err;
}
if ((err = mp_copy(b,&e)) != MP_OKAY) {
return err;
}
if ((err = mp_set_int(c,1)) != MP_OKAY) {
return err;
}
while (!mp_iszero(&e)) {
/* could be done more elegantely by checking bit counted down below */
if (mp_isodd(&e)) {
if ((err = mp_mul(c,&tmp,c)) != MP_OKAY) {
return err;
}
}
/* could be done more elegantely by counting down highbit */
if ((err = mp_div_2(&e, &e)) != MP_OKAY) {
return err;
}
if (!mp_iszero(&e)) {
if ((err = mp_sqr(&tmp,&tmp)) != MP_OKAY) {
return err;
}
}
}
if (a->sign == MP_NEG) {
c->sign = (mp_isodd(b))?MP_NEG:MP_ZPOS;
}
mp_clear_multi(&tmp,&e,NULL);
return MP_OKAY;
}
#endif