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