Botan  1.10.9
reducer.cpp
Go to the documentation of this file.
1 /*
2 * Modular Reducer
3 * (C) 1999-2011 Jack Lloyd
4 *
5 * Distributed under the terms of the Botan license
6 */
7 
8 #include <botan/reducer.h>
9 #include <botan/internal/mp_core.h>
10 
11 namespace Botan {
12 
13 /*
14 * Modular_Reducer Constructor
15 */
17  {
18  if(mod <= 0)
19  throw Invalid_Argument("Modular_Reducer: modulus must be positive");
20 
21  modulus = mod;
22  mod_words = modulus.sig_words();
23 
24  modulus_2 = Botan::square(modulus);
25 
26  mu = BigInt(BigInt::Power2, 2 * MP_WORD_BITS * mod_words) / modulus;
27  }
28 
29 /*
30 * Barrett Reduction
31 */
33  {
34  if(mod_words == 0)
35  throw Invalid_State("Modular_Reducer: Never initalized");
36 
37  if(x.cmp(modulus, false) < 0)
38  {
39  if(x.is_negative())
40  return x + modulus; // make positive
41  return x;
42  }
43  else if(x.cmp(modulus_2, false) < 0)
44  {
45  BigInt t1 = x;
47  t1 >>= (MP_WORD_BITS * (mod_words - 1));
48  t1 *= mu;
49 
50  t1 >>= (MP_WORD_BITS * (mod_words + 1));
51  t1 *= modulus;
52 
53  t1.mask_bits(MP_WORD_BITS * (mod_words + 1));
54 
55  BigInt t2 = x;
57  t2.mask_bits(MP_WORD_BITS * (mod_words + 1));
58 
59  t2 -= t1;
60 
61  if(t2.is_negative())
62  {
63  BigInt b_to_k1(BigInt::Power2, MP_WORD_BITS * (mod_words + 1));
64  t2 += b_to_k1;
65  }
66 
67  while(t2 >= modulus)
68  t2 -= modulus;
69 
70  if(x.is_positive())
71  return t2;
72  else
73  return (modulus - t2);
74  }
75  else
76  {
77  // too big, fall back to normal division
78  return (x % modulus);
79  }
80  }
81 
82 }
size_t sig_words() const
Definition: bigint.h:290
s32bit cmp(const BigInt &n, bool check_signs=true) const
Definition: bigint.cpp:132
bool is_negative() const
Definition: bigint.h:245
std::invalid_argument Invalid_Argument
Definition: exceptn.h:20
void mask_bits(size_t n)
Definition: bigint.cpp:227
GMP_MPZ mod
Definition: gmp_powm.cpp:29
BigInt reduce(const BigInt &x) const
Definition: reducer.cpp:32
BigInt square(const BigInt &x)
Definition: mp_numth.cpp:18
bool is_positive() const
Definition: bigint.h:251
void set_sign(Sign sign)
Definition: bigint.cpp:291
const size_t MP_WORD_BITS
Definition: mp_core.h:18