1
0
mirror of http://galexander.org/git/simplesshd.git synced 2024-11-30 19:28:10 +00:00
simplesshd/dropbear/libtommath/bn_mp_exptmod.c

77 lines
2.2 KiB
C
Raw Normal View History

2020-12-28 21:40:37 +00:00
#include "tommath_private.h"
2014-12-10 21:56:49 +00:00
#ifdef BN_MP_EXPTMOD_C
2020-12-28 21:40:37 +00:00
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
2014-12-10 21:56:49 +00:00
/* this is a shell function that calls either the normal or Montgomery
* exptmod functions. Originally the call to the montgomery code was
* embedded in the normal function but that wasted alot of stack space
* for nothing (since 99% of the time the Montgomery code would be called)
*/
2020-12-28 21:40:37 +00:00
mp_err mp_exptmod(const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y)
2014-12-10 21:56:49 +00:00
{
2020-12-28 21:40:37 +00:00
int dr;
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* modulus P must be positive */
if (P->sign == MP_NEG) {
return MP_VAL;
}
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* if exponent X is negative we have to recurse */
if (X->sign == MP_NEG) {
mp_int tmpG, tmpX;
mp_err err;
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
if (!MP_HAS(MP_INVMOD)) {
return MP_VAL;
}
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
if ((err = mp_init_multi(&tmpG, &tmpX, NULL)) != MP_OKAY) {
return err;
}
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* first compute 1/G mod P */
if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
goto LBL_ERR;
}
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* now get |X| */
if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
goto LBL_ERR;
}
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* and now compute (1/G)**|X| instead of G**X [X < 0] */
err = mp_exptmod(&tmpG, &tmpX, P, Y);
LBL_ERR:
mp_clear_multi(&tmpG, &tmpX, NULL);
return err;
}
2014-12-10 21:56:49 +00:00
2020-12-28 21:40:37 +00:00
/* modified diminished radix reduction */
if (MP_HAS(MP_REDUCE_IS_2K_L) && MP_HAS(MP_REDUCE_2K_L) && MP_HAS(S_MP_EXPTMOD) &&
(mp_reduce_is_2k_l(P) == MP_YES)) {
return s_mp_exptmod(G, X, P, Y, 1);
}
/* is it a DR modulus? default to no */
dr = (MP_HAS(MP_DR_IS_MODULUS) && (mp_dr_is_modulus(P) == MP_YES)) ? 1 : 0;
/* if not, is it a unrestricted DR modulus? */
if (MP_HAS(MP_REDUCE_IS_2K) && (dr == 0)) {
dr = (mp_reduce_is_2k(P) == MP_YES) ? 2 : 0;
}
/* if the modulus is odd or dr != 0 use the montgomery method */
if (MP_HAS(S_MP_EXPTMOD_FAST) && (MP_IS_ODD(P) || (dr != 0))) {
return s_mp_exptmod_fast(G, X, P, Y, dr);
} else if (MP_HAS(S_MP_EXPTMOD)) {
/* otherwise use the generic Barrett reduction technique */
return s_mp_exptmod(G, X, P, Y, 0);
} else {
/* no exptmod for evens */
return MP_VAL;
}
2014-12-10 21:56:49 +00:00
}
#endif