modarith.h 13 KB

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