aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/math/numbertheory/reducer.cpp
blob: e9db7753b493a449c0b947927fcca137c68b123e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Modular Reducer
* (C) 1999-2011 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/reducer.h>

namespace Botan {

/*
* Modular_Reducer Constructor
*/
Modular_Reducer::Modular_Reducer(const BigInt& mod)
   {
   if(mod <= 0)
      throw Invalid_Argument("Modular_Reducer: modulus must be positive");

   m_modulus = mod;
   m_mod_words = m_modulus.sig_words();

   m_modulus_2 = Botan::square(m_modulus);

   m_mu = BigInt::power_of_2(2 * BOTAN_MP_WORD_BITS * m_mod_words) / m_modulus;
   }

/*
* Barrett Reduction
*/
BigInt Modular_Reducer::reduce(const BigInt& x) const
   {
   if(m_mod_words == 0)
      throw Invalid_State("Modular_Reducer: Never initalized");

   const size_t x_sw = x.sig_words();

   if(x_sw < m_mod_words || x.cmp(m_modulus, false) < 0)
      {
      if(x.is_negative())
         return x + m_modulus; // make positive
      return x;
      }
   else if(x.cmp(m_modulus_2, false) < 0)
      {
      secure_vector<word> ws;

      BigInt t1(x.data() + m_mod_words - 1, x_sw - (m_mod_words - 1));

      t1.mul(m_mu, ws);
      t1 >>= (BOTAN_MP_WORD_BITS * (m_mod_words + 1));

      t1.mul(m_modulus, ws);
      t1.mask_bits(BOTAN_MP_WORD_BITS * (m_mod_words + 1));

      t1.rev_sub(x.data(), std::min(x_sw, m_mod_words + 1), ws);

      if(t1.is_negative())
         {
         t1 += BigInt::power_of_2(BOTAN_MP_WORD_BITS * (m_mod_words + 1));
         }

      t1.reduce_below(m_modulus, ws);

      if(x.is_positive())
         return t1;
      else
         return (m_modulus - t1);
      }
   else
      {
      // too big, fall back to normal division
      return (x % m_modulus);
      }
   }

}