diff options
author | jan.nijtmans <nijtmans@users.sourceforge.net> | 2024-03-27 20:54:34 (GMT) |
---|---|---|
committer | jan.nijtmans <nijtmans@users.sourceforge.net> | 2024-03-27 20:54:34 (GMT) |
commit | 471032ae680a0582e9d1475ae13079ce86e4ac34 (patch) | |
tree | 5e60564479598e0ad6b6320789acbfb39807e48c /libtommath/bn_mp_expt_n.c | |
parent | b31857f4b154b6ee2870deccbe42395fe4351b24 (diff) | |
download | tcl-471032ae680a0582e9d1475ae13079ce86e4ac34.zip tcl-471032ae680a0582e9d1475ae13079ce86e4ac34.tar.gz tcl-471032ae680a0582e9d1475ae13079ce86e4ac34.tar.bz2 |
Libtommath 1.3
Diffstat (limited to 'libtommath/bn_mp_expt_n.c')
-rw-r--r-- | libtommath/bn_mp_expt_n.c | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/libtommath/bn_mp_expt_n.c b/libtommath/bn_mp_expt_n.c new file mode 100644 index 0000000..19c0225 --- /dev/null +++ b/libtommath/bn_mp_expt_n.c @@ -0,0 +1,53 @@ +#include "tommath_private.h" +#ifdef BN_MP_EXPT_N_C +/* LibTomMath, multiple-precision integer library -- Tom St Denis */ +/* SPDX-License-Identifier: Unlicense */ + +#ifdef BN_MP_EXPT_U32_C +mp_err mp_expt_u32(const mp_int *a, uint32_t b, mp_int *c) +{ + if (b > MP_MIN(MP_DIGIT_MAX, INT_MAX)) { + return MP_VAL; + } + return mp_expt_n(a, (int)b, c); +} +#endif + +/* calculate c = a**b using a square-multiply algorithm */ +mp_err mp_expt_n(const mp_int *a, int b, mp_int *c) +{ + mp_err err; + mp_int g; + + if ((err = mp_init_copy(&g, a)) != MP_OKAY) { + return err; + } + + /* set initial result */ + mp_set(c, 1uL); + + while (b > 0) { + /* if the bit is set multiply */ + if ((b & 1) != 0) { + if ((err = mp_mul(c, &g, c)) != MP_OKAY) { + goto LBL_ERR; + } + } + + /* square */ + if (b > 1) { + if ((err = mp_sqr(&g, &g)) != MP_OKAY) { + goto LBL_ERR; + } + } + + /* shift to next bit */ + b >>= 1; + } + +LBL_ERR: + mp_clear(&g); + return err; +} + +#endif |