1 /* $NetBSD: bn_mp_exptmod.c,v 1.1.1.2 2014/04/24 12:45:31 pettai Exp $ */
5 /* LibTomMath, multiple-precision integer library -- Tom St Denis
7 * LibTomMath is a library that provides multiple-precision
8 * integer arithmetic as well as number theoretic functionality.
10 * The library was designed directly after the MPI library by
11 * Michael Fromberger but has been written from scratch with
12 * additional optimizations in place.
14 * The library is free for all purposes without any express
17 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
21 /* this is a shell function that calls either the normal or Montgomery
22 * exptmod functions. Originally the call to the montgomery code was
23 * embedded in the normal function but that wasted alot of stack space
24 * for nothing (since 99% of the time the Montgomery code would be called)
26 int mp_exptmod (mp_int
* G
, mp_int
* X
, mp_int
* P
, mp_int
* Y
)
30 /* modulus P must be positive */
31 if (P
->sign
== MP_NEG
) {
35 /* if exponent X is negative we have to recurse */
36 if (X
->sign
== MP_NEG
) {
41 /* first compute 1/G mod P */
42 if ((err
= mp_init(&tmpG
)) != MP_OKAY
) {
45 if ((err
= mp_invmod(G
, P
, &tmpG
)) != MP_OKAY
) {
51 if ((err
= mp_init(&tmpX
)) != MP_OKAY
) {
55 if ((err
= mp_abs(X
, &tmpX
)) != MP_OKAY
) {
56 mp_clear_multi(&tmpG
, &tmpX
, NULL
);
60 /* and now compute (1/G)**|X| instead of G**X [X < 0] */
61 err
= mp_exptmod(&tmpG
, &tmpX
, P
, Y
);
62 mp_clear_multi(&tmpG
, &tmpX
, NULL
);
70 /* modified diminished radix reduction */
71 #if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && defined(BN_S_MP_EXPTMOD_C)
72 if (mp_reduce_is_2k_l(P
) == MP_YES
) {
73 return s_mp_exptmod(G
, X
, P
, Y
, 1);
77 #ifdef BN_MP_DR_IS_MODULUS_C
78 /* is it a DR modulus? */
79 dr
= mp_dr_is_modulus(P
);
85 #ifdef BN_MP_REDUCE_IS_2K_C
86 /* if not, is it a unrestricted DR modulus? */
88 dr
= mp_reduce_is_2k(P
) << 1;
92 /* if the modulus is odd or dr != 0 use the montgomery method */
93 #ifdef BN_MP_EXPTMOD_FAST_C
94 if (mp_isodd (P
) == 1 || dr
!= 0) {
95 return mp_exptmod_fast (G
, X
, P
, Y
, dr
);
98 #ifdef BN_S_MP_EXPTMOD_C
99 /* otherwise use the generic Barrett reduction technique */
100 return s_mp_exptmod (G
, X
, P
, Y
, 0);
102 /* no exptmod for evens */
105 #ifdef BN_MP_EXPTMOD_FAST_C
112 /* Source: /cvs/libtom/libtommath/bn_mp_exptmod.c,v */
114 /* Date: 2006/12/28 01:25:13 */