Crypto++  5.6.5
Free C++ class library of cryptographic schemes
modarith.h
Go to the documentation of this file.
1 // modarith.h - written and placed in the public domain by Wei Dai
2 
3 //! \file modarith.h
4 //! \brief Class file for performing modular arithmetic.
5 
6 #ifndef CRYPTOPP_MODARITH_H
7 #define CRYPTOPP_MODARITH_H
8 
9 // implementations are in integer.cpp
10 
11 #include "cryptlib.h"
12 #include "integer.h"
13 #include "algebra.h"
14 #include "secblock.h"
15 #include "misc.h"
16 
17 NAMESPACE_BEGIN(CryptoPP)
18 
19 CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<Integer>;
20 CRYPTOPP_DLL_TEMPLATE_CLASS AbstractRing<Integer>;
21 CRYPTOPP_DLL_TEMPLATE_CLASS AbstractEuclideanDomain<Integer>;
22 
23 //! \class ModularArithmetic
24 //! \brief Ring of congruence classes modulo n
25 //! \details This implementation represents each congruence class as the smallest
26 //! non-negative integer in that class.
27 //! \details <tt>const Element&</tt> returned by member functions are references
28 //! to internal data members. Since each object may have only
29 //! one such data member for holding results, the following code
30 //! will produce incorrect results:
31 //! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
32 //! But this should be fine:
33 //! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
34 class CRYPTOPP_DLL ModularArithmetic : public AbstractRing<Integer>
35 {
36 public:
37 
38  typedef int RandomizationParameter;
39  typedef Integer Element;
40 
41  virtual ~ModularArithmetic() {}
42 
43  //! \brief Construct a ModularArithmetic
44  //! \param modulus congruence class modulus
45  ModularArithmetic(const Integer &modulus = Integer::One())
46  : AbstractRing<Integer>(), m_modulus(modulus), m_result((word)0, modulus.reg.size()) {}
47 
48  //! \brief Copy construct a ModularArithmetic
49  //! \param ma other ModularArithmetic
51  : AbstractRing<Integer>(), m_modulus(ma.m_modulus), m_result((word)0, ma.m_modulus.reg.size()) {}
52 
53  //! \brief Construct a ModularArithmetic
54  //! \param bt BER encoded ModularArithmetic
55  ModularArithmetic(BufferedTransformation &bt); // construct from BER encoded parameters
56 
57  //! \brief Clone a ModularArithmetic
58  //! \returns pointer to a new ModularArithmetic
59  //! \details Clone effectively copy constructs a new ModularArithmetic. The caller is
60  //! responsible for deleting the pointer returned from this method.
61  virtual ModularArithmetic * Clone() const {return new ModularArithmetic(*this);}
62 
63  //! \brief Encodes in DER format
64  //! \param bt BufferedTransformation object
65  void DEREncode(BufferedTransformation &bt) const;
66 
67  //! \brief Encodes element in DER format
68  //! \param out BufferedTransformation object
69  //! \param a Element to encode
70  void DEREncodeElement(BufferedTransformation &out, const Element &a) const;
71 
72  //! \brief Decodes element in DER format
73  //! \param in BufferedTransformation object
74  //! \param a Element to decode
75  void BERDecodeElement(BufferedTransformation &in, Element &a) const;
76 
77  //! \brief Retrieves the modulus
78  //! \returns the modulus
79  const Integer& GetModulus() const {return m_modulus;}
80 
81  //! \brief Sets the modulus
82  //! \param newModulus the new modulus
83  void SetModulus(const Integer &newModulus)
84  {m_modulus = newModulus; m_result.reg.resize(m_modulus.reg.size());}
85 
86  //! \brief Retrieves the representation
87  //! \returns true if the if the modulus is in Montgomery form for multiplication, false otherwise
88  virtual bool IsMontgomeryRepresentation() const {return false;}
89 
90  //! \brief Reduces an element in the congruence class
91  //! \param a element to convert
92  //! \returns the reduced element
93  //! \details ConvertIn is useful for derived classes, like MontgomeryRepresentation, which
94  //! must convert between representations.
95  virtual Integer ConvertIn(const Integer &a) const
96  {return a%m_modulus;}
97 
98  //! \brief Reduces an element in the congruence class
99  //! \param a element to convert
100  //! \returns the reduced element
101  //! \details ConvertOut is useful for derived classes, like MontgomeryRepresentation, which
102  //! must convert between representations.
103  virtual Integer ConvertOut(const Integer &a) const
104  {return a;}
105 
106  //! \brief Divides an element by 2
107  //! \param a element to convert
108  const Integer& Half(const Integer &a) const;
109 
110  //! \brief Compare two elements for equality
111  //! \param a first element
112  //! \param b second element
113  //! \returns true if the elements are equal, false otherwise
114  //! \details Equal() tests the elements for equality using <tt>a==b</tt>
115  bool Equal(const Integer &a, const Integer &b) const
116  {return a==b;}
117 
118  //! \brief Provides the Identity element
119  //! \returns the Identity element
120  const Integer& Identity() const
121  {return Integer::Zero();}
122 
123  //! \brief Adds elements in the ring
124  //! \param a first element
125  //! \param b second element
126  //! \returns the sum of <tt>a</tt> and <tt>b</tt>
127  const Integer& Add(const Integer &a, const Integer &b) const;
128 
129  //! \brief TODO
130  //! \param a first element
131  //! \param b second element
132  //! \returns TODO
133  Integer& Accumulate(Integer &a, const Integer &b) const;
134 
135  //! \brief Inverts the element in the ring
136  //! \param a first element
137  //! \returns the inverse of the element
138  const Integer& Inverse(const Integer &a) const;
139 
140  //! \brief Subtracts elements in the ring
141  //! \param a first element
142  //! \param b second element
143  //! \returns the difference of <tt>a</tt> and <tt>b</tt>. The element <tt>a</tt> must provide a Subtract member function.
144  const Integer& Subtract(const Integer &a, const Integer &b) const;
145 
146  //! \brief TODO
147  //! \param a first element
148  //! \param b second element
149  //! \returns TODO
150  Integer& Reduce(Integer &a, const Integer &b) const;
151 
152  //! \brief Doubles an element in the ring
153  //! \param a the element
154  //! \returns the element doubled
155  //! \details Double returns <tt>Add(a, a)</tt>. The element <tt>a</tt> must provide an Add member function.
156  const Integer& Double(const Integer &a) const
157  {return Add(a, a);}
158 
159  //! \brief Retrieves the multiplicative identity
160  //! \returns the multiplicative identity
161  //! \details the base class implementations returns 1.
162  const Integer& MultiplicativeIdentity() const
163  {return Integer::One();}
164 
165  //! \brief Multiplies elements in the ring
166  //! \param a the multiplicand
167  //! \param b the multiplier
168  //! \returns the product of a and b
169  //! \details Multiply returns <tt>a*b\%n</tt>.
170  const Integer& Multiply(const Integer &a, const Integer &b) const
171  {return m_result1 = a*b%m_modulus;}
172 
173  //! \brief Square an element in the ring
174  //! \param a the element
175  //! \returns the element squared
176  //! \details Square returns <tt>a*a\%n</tt>. The element <tt>a</tt> must provide a Square member function.
177  const Integer& Square(const Integer &a) const
178  {return m_result1 = a.Squared()%m_modulus;}
179 
180  //! \brief Determines whether an element is a unit in the ring
181  //! \param a the element
182  //! \returns true if the element is a unit after reduction, false otherwise.
183  bool IsUnit(const Integer &a) const
184  {return Integer::Gcd(a, m_modulus).IsUnit();}
185 
186  //! \brief Calculate the multiplicative inverse of an element in the ring
187  //! \param a the element
188  //! \details MultiplicativeInverse returns <tt>a<sup>-1</sup>\%n</tt>. The element <tt>a</tt> must
189  //! provide a InverseMod member function.
190  const Integer& MultiplicativeInverse(const Integer &a) const
191  {return m_result1 = a.InverseMod(m_modulus);}
192 
193  //! \brief Divides elements in the ring
194  //! \param a the dividend
195  //! \param b the divisor
196  //! \returns the quotient
197  //! \details Divide returns <tt>a*b<sup>-1</sup>\%n</tt>.
198  const Integer& Divide(const Integer &a, const Integer &b) const
199  {return Multiply(a, MultiplicativeInverse(b));}
200 
201  //! \brief TODO
202  //! \param x first element
203  //! \param e1 first exponent
204  //! \param y second element
205  //! \param e2 second exponent
206  //! \returns TODO
207  Integer CascadeExponentiate(const Integer &x, const Integer &e1, const Integer &y, const Integer &e2) const;
208 
209  //! \brief Exponentiates a base to multiple exponents in the ring
210  //! \param results an array of Elements
211  //! \param base the base to raise to the exponents
212  //! \param exponents an array of exponents
213  //! \param exponentsCount the number of exponents in the array
214  //! \details SimultaneousExponentiate() raises the base to each exponent in the exponents array and stores the
215  //! result at the respective position in the results array.
216  //! \details SimultaneousExponentiate() must be implemented in a derived class.
217  //! \pre <tt>COUNTOF(results) == exponentsCount</tt>
218  //! \pre <tt>COUNTOF(exponents) == exponentsCount</tt>
219  void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
220 
221  //! \brief Provides the maximum bit size of an element in the ring
222  //! \returns maximum bit size of an element
223  unsigned int MaxElementBitLength() const
224  {return (m_modulus-1).BitCount();}
225 
226  //! \brief Provides the maximum byte size of an element in the ring
227  //! \returns maximum byte size of an element
228  unsigned int MaxElementByteLength() const
229  {return (m_modulus-1).ByteCount();}
230 
231  //! \brief Provides a random element in the ring
232  //! \param rng RandomNumberGenerator used to generate material
233  //! \param ignore_for_now unused
234  //! \returns a random element that is uniformly distributed
235  //! \details RandomElement constructs a new element in the range <tt>[0,n-1]</tt>, inclusive.
236  //! The element's class must provide a constructor with the signature <tt>Element(RandomNumberGenerator rng,
237  //! Element min, Element max)</tt>.
238  Element RandomElement(RandomNumberGenerator &rng , const RandomizationParameter &ignore_for_now = 0) const
239  // left RandomizationParameter arg as ref in case RandomizationParameter becomes a more complicated struct
240  {
241  CRYPTOPP_UNUSED(ignore_for_now);
242  return Element(rng, Integer::Zero(), m_modulus - Integer::One()) ;
243  }
244 
245  //! \brief Compares two ModularArithmetic for equality
246  //! \param rhs other ModularArithmetic
247  //! \returns true if this is equal to the other, false otherwise
248  //! \details The operator tests for equality using <tt>this.m_modulus == rhs.m_modulus</tt>.
249  bool operator==(const ModularArithmetic &rhs) const
250  {return m_modulus == rhs.m_modulus;}
251 
252  static const RandomizationParameter DefaultRandomizationParameter ;
253 
254 protected:
255  Integer m_modulus;
256  mutable Integer m_result, m_result1;
257 };
258 
259 // const ModularArithmetic::RandomizationParameter ModularArithmetic::DefaultRandomizationParameter = 0 ;
260 
261 //! \class MontgomeryRepresentation
262 //! \brief Performs modular arithmetic in Montgomery representation for increased speed
263 //! \details The Montgomery representation represents each congruence class <tt>[a]</tt> as
264 //! <tt>a*r\%n</tt>, where <tt>r</tt> is a convenient power of 2.
265 //! \details <tt>const Element&</tt> returned by member functions are references to
266 //! internal data members. Since each object may have only one such data member for holding
267 //! results, the following code will produce incorrect results:
268 //! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
269 //! But this should be fine:
270 //! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
271 class CRYPTOPP_DLL MontgomeryRepresentation : public ModularArithmetic
272 {
273 public:
274  virtual ~MontgomeryRepresentation() {}
275 
276  //! \brief Construct a MontgomeryRepresentation
277  //! \param modulus congruence class modulus
278  //! \note The modulus must be odd.
279  MontgomeryRepresentation(const Integer &modulus);
280 
281  //! \brief Clone a MontgomeryRepresentation
282  //! \returns pointer to a new MontgomeryRepresentation
283  //! \details Clone effectively copy constructs a new MontgomeryRepresentation. The caller is
284  //! responsible for deleting the pointer returned from this method.
285  virtual ModularArithmetic * Clone() const {return new MontgomeryRepresentation(*this);}
286 
287  bool IsMontgomeryRepresentation() const {return true;}
288 
289  Integer ConvertIn(const Integer &a) const
290  {return (a<<(WORD_BITS*m_modulus.reg.size()))%m_modulus;}
291 
292  Integer ConvertOut(const Integer &a) const;
293 
294  const Integer& MultiplicativeIdentity() const
295  {return m_result1 = Integer::Power2(WORD_BITS*m_modulus.reg.size())%m_modulus;}
296 
297  const Integer& Multiply(const Integer &a, const Integer &b) const;
298 
299  const Integer& Square(const Integer &a) const;
300 
301  const Integer& MultiplicativeInverse(const Integer &a) const;
302 
303  Integer CascadeExponentiate(const Integer &x, const Integer &e1, const Integer &y, const Integer &e2) const
304  {return AbstractRing<Integer>::CascadeExponentiate(x, e1, y, e2);}
305 
306  void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const
307  {AbstractRing<Integer>::SimultaneousExponentiate(results, base, exponents, exponentsCount);}
308 
309 private:
310  Integer m_u;
311  mutable IntegerSecBlock m_workspace;
312 };
313 
314 NAMESPACE_END
315 
316 #endif
bool IsUnit(const Integer &a) const
Determines whether an element is a unit in the ring.
Definition: modarith.h:183
const Integer & GetModulus() const
Retrieves the modulus.
Definition: modarith.h:79
Utility functions for the Crypto++ library.
virtual ModularArithmetic * Clone() const
Clone a ModularArithmetic.
Definition: modarith.h:61
static Integer Gcd(const Integer &a, const Integer &n)
greatest common divisor
Definition: integer.cpp:4365
void resize(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:705
const Integer & MultiplicativeIdentity() const
Retrieves the multiplicative identity.
Definition: modarith.h:162
Abstract base classes that provide a uniform interface to this library.
const Integer & MultiplicativeInverse(const Integer &a) const
Calculate the multiplicative inverse of an element in the ring.
Definition: modarith.h:190
Abstract Euclidean domain.
Definition: algebra.h:276
const Integer & Square(const Integer &a) const
Square an element in the ring.
Definition: modarith.h:177
Ring of congruence classes modulo n.
Definition: modarith.h:34
Interface for random number generators.
Definition: cryptlib.h:1188
Element RandomElement(RandomNumberGenerator &rng, const RandomizationParameter &ignore_for_now=0) const
Provides a random element in the ring.
Definition: modarith.h:238
virtual void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const
Exponentiates a base to multiple exponents in the Ring.
Definition: algebra.cpp:334
Classes for performing mathematics over different fields.
Interface for buffered transformations.
Definition: cryptlib.h:1352
static const Integer & One()
Integer representing 1.
Definition: integer.cpp:3035
Abstract ring.
Definition: algebra.h:118
virtual ModularArithmetic * Clone() const
Clone a MontgomeryRepresentation.
Definition: modarith.h:285
Classes and functions for secure memory allocations.
bool IsUnit() const
is 1 or -1
Definition: integer.cpp:4344
virtual Integer ConvertIn(const Integer &a) const
Reduces an element in the congruence class.
Definition: modarith.h:95
virtual Integer ConvertOut(const Integer &a) const
Reduces an element in the congruence class.
Definition: modarith.h:103
const Integer & Multiply(const Integer &a, const Integer &b) const
Multiplies elements in the ring.
Definition: modarith.h:170
const Integer & MultiplicativeIdentity() const
Retrieves the multiplicative identity.
Definition: modarith.h:294
Integer Squared() const
Multiply this integer by itself.
Definition: integer.h:570
static Integer Power2(size_t e)
Exponentiates to a power of 2.
Definition: integer.cpp:3008
unsigned int MaxElementBitLength() const
Provides the maximum bit size of an element in the ring.
Definition: modarith.h:223
Multiple precision integer with arithmetic operations.
Definition: integer.h:43
const Integer & Double(const Integer &a) const
Doubles an element in the ring.
Definition: modarith.h:156
virtual Element CascadeExponentiate(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const
TODO.
Definition: algebra.cpp:323
ModularArithmetic(const Integer &modulus=Integer::One())
Construct a ModularArithmetic.
Definition: modarith.h:45
Abstract group.
Definition: algebra.h:26
const Integer & Divide(const Integer &a, const Integer &b) const
Divides elements in the ring.
Definition: modarith.h:198
void SetModulus(const Integer &newModulus)
Sets the modulus.
Definition: modarith.h:83
Performs modular arithmetic in Montgomery representation for increased speed.
Definition: modarith.h:271
Integer CascadeExponentiate(const Integer &x, const Integer &e1, const Integer &y, const Integer &e2) const
TODO.
Definition: modarith.h:303
Integer InverseMod(const Integer &n) const
calculate multiplicative inverse of *this mod n
Definition: integer.cpp:4370
bool operator==(const ModularArithmetic &rhs) const
Compares two ModularArithmetic for equality.
Definition: modarith.h:249
Multiple precision integer with arithmetic operations.
static const Integer & Zero()
Integer representing 0.
Definition: integer.cpp:3027
Crypto++ library namespace.
bool IsMontgomeryRepresentation() const
Retrieves the representation.
Definition: modarith.h:287
ModularArithmetic(const ModularArithmetic &ma)
Copy construct a ModularArithmetic.
Definition: modarith.h:50
virtual bool IsMontgomeryRepresentation() const
Retrieves the representation.
Definition: modarith.h:88
const Integer & Identity() const
Provides the Identity element.
Definition: modarith.h:120
bool Equal(const Integer &a, const Integer &b) const
Compare two elements for equality.
Definition: modarith.h:115
unsigned int MaxElementByteLength() const
Provides the maximum byte size of an element in the ring.
Definition: modarith.h:228
void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const
Exponentiates a base to multiple exponents in the ring.
Definition: modarith.h:306
Integer ConvertIn(const Integer &a) const
Reduces an element in the congruence class.
Definition: modarith.h:289