1 /* mpz_powm_sec(res,base,exp,mod) -- Set R to (U^E) mod M. 2 3 Contributed to the GNU project by Torbjorn Granlund. 4 5 Copyright 1991, 1993, 1994, 1996, 1997, 2000, 2001, 2002, 2005, 2008, 2009 6 Free Software Foundation, Inc. 7 8 This file is part of the GNU MP Library. 9 10 The GNU MP Library is free software; you can redistribute it and/or modify 11 it under the terms of the GNU Lesser General Public License as published by 12 the Free Software Foundation; either version 3 of the License, or (at your 13 option) any later version. 14 15 The GNU MP Library is distributed in the hope that it will be useful, but 16 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 17 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 18 License for more details. 19 20 You should have received a copy of the GNU Lesser General Public License 21 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 22 23 24 #include "gmp.h" 25 #include "gmp-impl.h" 26 27 28 void 29 mpz_powm_sec (mpz_ptr r, mpz_srcptr b, mpz_srcptr e, mpz_srcptr m) 30 { 31 mp_size_t n; 32 mp_ptr rp, tp; 33 mp_srcptr bp, ep, mp; 34 mp_size_t rn, bn, es, en; 35 TMP_DECL; 36 37 n = ABSIZ(m); 38 if (n == 0) 39 DIVIDE_BY_ZERO; 40 41 mp = PTR(m); 42 43 if (mp[0] % 2 == 0) 44 DIVIDE_BY_ZERO; 45 46 es = SIZ(e); 47 if (UNLIKELY (es <= 0)) 48 { 49 mpz_t new_b; 50 if (es == 0) 51 { 52 /* b^0 mod m, b is anything and m is non-zero. 53 Result is 1 mod m, i.e., 1 or 0 depending on if m = 1. */ 54 SIZ(r) = n != 1 || mp[0] != 1; 55 PTR(r)[0] = 1; 56 return; 57 } 58 DIVIDE_BY_ZERO; 59 } 60 61 en = es; 62 bn = ABSIZ(b); 63 64 TMP_MARK; 65 tp = TMP_ALLOC_LIMBS (n + mpn_powm_sec_itch (bn, en, n)); 66 67 rp = tp; tp += n; 68 69 bp = PTR(b); 70 ep = PTR(e); 71 72 mpn_powm_sec (rp, bp, bn, ep, en, mp, n, tp); 73 74 rn = n; 75 76 MPN_NORMALIZE (rp, rn); 77 78 if ((ep[0] & 1) && SIZ(b) < 0 && rn != 0) 79 { 80 mpn_sub (rp, PTR(m), n, rp, rn); 81 rn = n; 82 MPN_NORMALIZE (rp, rn); 83 } 84 85 MPZ_REALLOC (r, rn); 86 SIZ(r) = rn; 87 MPN_COPY (PTR(r), rp, rn); 88 89 TMP_FREE; 90 } 91