new beta-0.90.0
[luatex.git] / source / libs / gmp / gmp-src / mpz / powm_sec.c
blob98644ca4963dd2c8f4a401c5d88dbfb6fa50ed33
1 /* mpz_powm_sec(res,base,exp,mod) -- Set R to (U^E) mod M.
3 Contributed to the GNU project by Torbjorn Granlund.
5 Copyright 1991, 1993, 1994, 1996, 1997, 2000-2002, 2005, 2008, 2009, 2012 Free
6 Software Foundation, Inc.
8 This file is part of the GNU MP Library.
10 The GNU MP Library is free software; you can redistribute it and/or modify
11 it under the terms of either:
13 * the GNU Lesser General Public License as published by the Free
14 Software Foundation; either version 3 of the License, or (at your
15 option) any later version.
19 * the GNU General Public License as published by the Free Software
20 Foundation; either version 2 of the License, or (at your option) any
21 later version.
23 or both in parallel, as here.
25 The GNU MP Library is distributed in the hope that it will be useful, but
26 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
27 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
28 for more details.
30 You should have received copies of the GNU General Public License and the
31 GNU Lesser General Public License along with the GNU MP Library. If not,
32 see https://www.gnu.org/licenses/. */
35 #include "gmp.h"
36 #include "gmp-impl.h"
39 void
40 mpz_powm_sec (mpz_ptr r, mpz_srcptr b, mpz_srcptr e, mpz_srcptr m)
42 mp_size_t n;
43 mp_ptr rp, tp;
44 mp_srcptr bp, ep, mp;
45 mp_size_t rn, bn, es, en;
46 TMP_DECL;
48 n = ABSIZ(m);
50 mp = PTR(m);
52 if (UNLIKELY ((n == 0) || (mp[0] % 2 == 0)))
53 DIVIDE_BY_ZERO;
55 es = SIZ(e);
56 if (UNLIKELY (es <= 0))
58 if (es == 0)
60 /* b^0 mod m, b is anything and m is non-zero.
61 Result is 1 mod m, i.e., 1 or 0 depending on if m = 1. */
62 SIZ(r) = n != 1 || mp[0] != 1;
63 PTR(r)[0] = 1;
64 return;
66 DIVIDE_BY_ZERO;
68 en = es;
70 bn = ABSIZ(b);
72 if (UNLIKELY (bn == 0))
74 SIZ(r) = 0;
75 return;
78 TMP_MARK;
79 tp = TMP_ALLOC_LIMBS (n + mpn_sec_powm_itch (bn, en * GMP_NUMB_BITS, n));
81 rp = tp; tp += n;
83 bp = PTR(b);
84 ep = PTR(e);
86 mpn_sec_powm (rp, bp, bn, ep, en * GMP_NUMB_BITS, mp, n, tp);
88 rn = n;
90 MPN_NORMALIZE (rp, rn);
92 if ((ep[0] & 1) && SIZ(b) < 0 && rn != 0)
94 mpn_sub (rp, PTR(m), n, rp, rn);
95 rn = n;
96 MPN_NORMALIZE (rp, rn);
99 MPZ_REALLOC (r, rn);
100 SIZ(r) = rn;
101 MPN_COPY (PTR(r), rp, rn);
103 TMP_FREE;