integer.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. // integer.h - originally written and placed in the public domain by Wei Dai
  2. /// \file integer.h
  3. /// \brief Multiple precision integer with arithmetic operations
  4. /// \details The Integer class can represent positive and negative integers
  5. /// with absolute value less than (256**sizeof(word))<sup>(256**sizeof(int))</sup>.
  6. /// \details Internally, the library uses a sign magnitude representation, and the class
  7. /// has two data members. The first is a IntegerSecBlock (a SecBlock<word>) and it is
  8. /// used to hold the representation. The second is a Sign (an enumeration), and it is
  9. /// used to track the sign of the Integer.
  10. /// \details For details on how the Integer class initializes its function pointers using
  11. /// InitializeInteger and how it creates Integer::Zero(), Integer::One(), and
  12. /// Integer::Two(), then see the comments at the top of <tt>integer.cpp</tt>.
  13. /// \since Crypto++ 1.0
  14. #ifndef CRYPTOPP_INTEGER_H
  15. #define CRYPTOPP_INTEGER_H
  16. #include "cryptlib.h"
  17. #include "secblock.h"
  18. #include "stdcpp.h"
  19. #include <iosfwd>
  20. NAMESPACE_BEGIN(CryptoPP)
  21. /// \struct InitializeInteger
  22. /// \brief Performs static initialization of the Integer class
  23. struct InitializeInteger
  24. {
  25. InitializeInteger();
  26. };
  27. // Always align, http://github.com/weidai11/cryptopp/issues/256
  28. typedef SecBlock<word, AllocatorWithCleanup<word, true> > IntegerSecBlock;
  29. /// \brief Multiple precision integer with arithmetic operations
  30. /// \details The Integer class can represent positive and negative integers
  31. /// with absolute value less than (256**sizeof(word))<sup>(256**sizeof(int))</sup>.
  32. /// \details Internally, the library uses a sign magnitude representation, and the class
  33. /// has two data members. The first is a IntegerSecBlock (a SecBlock<word>) and it is
  34. /// used to hold the representation. The second is a Sign (an enumeration), and it is
  35. /// used to track the sign of the Integer.
  36. /// \details For details on how the Integer class initializes its function pointers using
  37. /// InitializeInteger and how it creates Integer::Zero(), Integer::One(), and
  38. /// Integer::Two(), then see the comments at the top of <tt>integer.cpp</tt>.
  39. /// \since Crypto++ 1.0
  40. /// \nosubgrouping
  41. class CRYPTOPP_DLL Integer : private InitializeInteger, public ASN1Object
  42. {
  43. public:
  44. /// \name ENUMS, EXCEPTIONS, and TYPEDEFS
  45. //@{
  46. /// \brief Exception thrown when division by 0 is encountered
  47. class DivideByZero : public Exception
  48. {
  49. public:
  50. DivideByZero() : Exception(OTHER_ERROR, "Integer: division by zero") {}
  51. };
  52. /// \brief Exception thrown when a random number cannot be found that
  53. /// satisfies the condition
  54. class RandomNumberNotFound : public Exception
  55. {
  56. public:
  57. RandomNumberNotFound() : Exception(OTHER_ERROR, "Integer: no integer satisfies the given parameters") {}
  58. };
  59. /// \enum Sign
  60. /// \brief Used internally to represent the integer
  61. /// \details Sign is used internally to represent the integer. It is also used in a few API functions.
  62. /// \sa SetPositive(), SetNegative(), Signedness
  63. enum Sign {
  64. /// \brief the value is positive or 0
  65. POSITIVE=0,
  66. /// \brief the value is negative
  67. NEGATIVE=1};
  68. /// \enum Signedness
  69. /// \brief Used when importing and exporting integers
  70. /// \details Signedness is usually used in API functions.
  71. /// \sa Sign
  72. enum Signedness {
  73. /// \brief an unsigned value
  74. UNSIGNED,
  75. /// \brief a signed value
  76. SIGNED};
  77. /// \enum RandomNumberType
  78. /// \brief Properties of a random integer
  79. enum RandomNumberType {
  80. /// \brief a number with no special properties
  81. ANY,
  82. /// \brief a number which is probabilistically prime
  83. PRIME};
  84. //@}
  85. /// \name CREATORS
  86. //@{
  87. /// \brief Creates the zero integer
  88. Integer();
  89. /// copy constructor
  90. Integer(const Integer& t);
  91. /// \brief Convert from signed long
  92. Integer(signed long value);
  93. /// \brief Convert from lword
  94. /// \param sign enumeration indicating Sign
  95. /// \param value the long word
  96. Integer(Sign sign, lword value);
  97. /// \brief Convert from two words
  98. /// \param sign enumeration indicating Sign
  99. /// \param highWord the high word
  100. /// \param lowWord the low word
  101. Integer(Sign sign, word highWord, word lowWord);
  102. /// \brief Convert from a C-string
  103. /// \param str C-string value
  104. /// \param order the ByteOrder of the string to be processed
  105. /// \details \p str can be in base 8, 10, or 16. Base is determined
  106. /// by a case insensitive suffix of 'o' (8), '.' (10), or 'h' (16).
  107. /// No suffix means base 10.
  108. /// \details Byte order was added at Crypto++ 5.7 to allow use of little-endian
  109. /// integers with curve25519, Poly1305 and Microsoft CAPI.
  110. explicit Integer(const char *str, ByteOrder order = BIG_ENDIAN_ORDER);
  111. /// \brief Convert from a wide C-string
  112. /// \param str wide C-string value
  113. /// \param order the ByteOrder of the string to be processed
  114. /// \details \p str can be in base 8, 10, or 16. Base is determined
  115. /// by a case insensitive suffix of 'o' (8), '.' (10), or 'h' (16).
  116. /// No suffix means base 10.
  117. /// \details Byte order was added at Crypto++ 5.7 to allow use of little-endian
  118. /// integers with curve25519, Poly1305 and Microsoft CAPI.
  119. explicit Integer(const wchar_t *str, ByteOrder order = BIG_ENDIAN_ORDER);
  120. /// \brief Convert from a big-endian byte array
  121. /// \param encodedInteger big-endian byte array
  122. /// \param byteCount length of the byte array
  123. /// \param sign enumeration indicating Signedness
  124. /// \param order the ByteOrder of the array to be processed
  125. /// \details Byte order was added at Crypto++ 5.7 to allow use of little-endian
  126. /// integers with curve25519, Poly1305 and Microsoft CAPI.
  127. Integer(const byte *encodedInteger, size_t byteCount, Signedness sign=UNSIGNED, ByteOrder order = BIG_ENDIAN_ORDER);
  128. /// \brief Convert from a big-endian array
  129. /// \param bt BufferedTransformation object with big-endian byte array
  130. /// \param byteCount length of the byte array
  131. /// \param sign enumeration indicating Signedness
  132. /// \param order the ByteOrder of the data to be processed
  133. /// \details Byte order was added at Crypto++ 5.7 to allow use of little-endian
  134. /// integers with curve25519, Poly1305 and Microsoft CAPI.
  135. Integer(BufferedTransformation &bt, size_t byteCount, Signedness sign=UNSIGNED, ByteOrder order = BIG_ENDIAN_ORDER);
  136. /// \brief Convert from a BER encoded byte array
  137. /// \param bt BufferedTransformation object with BER encoded byte array
  138. explicit Integer(BufferedTransformation &bt);
  139. /// \brief Create a random integer
  140. /// \param rng RandomNumberGenerator used to generate material
  141. /// \param bitCount the number of bits in the resulting integer
  142. /// \details The random integer created is uniformly distributed over <tt>[0, 2<sup>bitCount</sup>]</tt>.
  143. Integer(RandomNumberGenerator &rng, size_t bitCount);
  144. /// \brief Integer representing 0
  145. /// \return an Integer representing 0
  146. /// \details Zero() avoids calling constructors for frequently used integers
  147. static const Integer & CRYPTOPP_API Zero();
  148. /// \brief Integer representing 1
  149. /// \return an Integer representing 1
  150. /// \details One() avoids calling constructors for frequently used integers
  151. static const Integer & CRYPTOPP_API One();
  152. /// \brief Integer representing 2
  153. /// \return an Integer representing 2
  154. /// \details Two() avoids calling constructors for frequently used integers
  155. static const Integer & CRYPTOPP_API Two();
  156. /// \brief Create a random integer of special form
  157. /// \param rng RandomNumberGenerator used to generate material
  158. /// \param min the minimum value
  159. /// \param max the maximum value
  160. /// \param rnType RandomNumberType to specify the type
  161. /// \param equiv the equivalence class based on the parameter \p mod
  162. /// \param mod the modulus used to reduce the equivalence class
  163. /// \throw RandomNumberNotFound if the set is empty.
  164. /// \details Ideally, the random integer created should be uniformly distributed
  165. /// over <tt>{x | min \<= x \<= max</tt> and \p x is of rnType and <tt>x \% mod == equiv}</tt>.
  166. /// However the actual distribution may not be uniform because sequential
  167. /// search is used to find an appropriate number from a random starting
  168. /// point.
  169. /// \details May return (with very small probability) a pseudoprime when a prime
  170. /// is requested and <tt>max \> lastSmallPrime*lastSmallPrime</tt>. \p lastSmallPrime
  171. /// is declared in nbtheory.h.
  172. Integer(RandomNumberGenerator &rng, const Integer &min, const Integer &max, RandomNumberType rnType=ANY, const Integer &equiv=Zero(), const Integer &mod=One());
  173. /// \brief Exponentiates to a power of 2
  174. /// \return the Integer 2<sup>e</sup>
  175. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  176. static Integer CRYPTOPP_API Power2(size_t e);
  177. //@}
  178. /// \name ENCODE/DECODE
  179. //@{
  180. /// \brief Minimum number of bytes to encode this integer
  181. /// \param sign enumeration indicating Signedness
  182. /// \note The MinEncodedSize() of 0 is 1.
  183. size_t MinEncodedSize(Signedness sign=UNSIGNED) const;
  184. /// \brief Encode in big-endian format
  185. /// \param output big-endian byte array
  186. /// \param outputLen length of the byte array
  187. /// \param sign enumeration indicating Signedness
  188. /// \details Unsigned means encode absolute value, signed means encode two's complement if negative.
  189. /// \details outputLen can be used to ensure an Integer is encoded to an exact size (rather than a
  190. /// minimum size). An exact size is useful, for example, when encoding to a field element size.
  191. void Encode(byte *output, size_t outputLen, Signedness sign=UNSIGNED) const;
  192. /// \brief Encode in big-endian format
  193. /// \param bt BufferedTransformation object
  194. /// \param outputLen length of the encoding
  195. /// \param sign enumeration indicating Signedness
  196. /// \details Unsigned means encode absolute value, signed means encode two's complement if negative.
  197. /// \details outputLen can be used to ensure an Integer is encoded to an exact size (rather than a
  198. /// minimum size). An exact size is useful, for example, when encoding to a field element size.
  199. void Encode(BufferedTransformation &bt, size_t outputLen, Signedness sign=UNSIGNED) const;
  200. /// \brief Encode in DER format
  201. /// \param bt BufferedTransformation object
  202. /// \details Encodes the Integer using Distinguished Encoding Rules
  203. /// The result is placed into a BufferedTransformation object
  204. void DEREncode(BufferedTransformation &bt) const;
  205. /// \brief Encode absolute value as big-endian octet string
  206. /// \param bt BufferedTransformation object
  207. /// \param length the number of mytes to decode
  208. void DEREncodeAsOctetString(BufferedTransformation &bt, size_t length) const;
  209. /// \brief Encode absolute value in OpenPGP format
  210. /// \param output big-endian byte array
  211. /// \param bufferSize length of the byte array
  212. /// \return length of the output
  213. /// \details OpenPGPEncode places result into the buffer and returns the
  214. /// number of bytes used for the encoding
  215. size_t OpenPGPEncode(byte *output, size_t bufferSize) const;
  216. /// \brief Encode absolute value in OpenPGP format
  217. /// \param bt BufferedTransformation object
  218. /// \return length of the output
  219. /// \details OpenPGPEncode places result into a BufferedTransformation object and returns the
  220. /// number of bytes used for the encoding
  221. size_t OpenPGPEncode(BufferedTransformation &bt) const;
  222. /// \brief Decode from big-endian byte array
  223. /// \param input big-endian byte array
  224. /// \param inputLen length of the byte array
  225. /// \param sign enumeration indicating Signedness
  226. void Decode(const byte *input, size_t inputLen, Signedness sign=UNSIGNED);
  227. /// \brief Decode nonnegative value from big-endian byte array
  228. /// \param bt BufferedTransformation object
  229. /// \param inputLen length of the byte array
  230. /// \param sign enumeration indicating Signedness
  231. /// \note <tt>bt.MaxRetrievable() \>= inputLen</tt>.
  232. void Decode(BufferedTransformation &bt, size_t inputLen, Signedness sign=UNSIGNED);
  233. /// \brief Decode from BER format
  234. /// \param input big-endian byte array
  235. /// \param inputLen length of the byte array
  236. void BERDecode(const byte *input, size_t inputLen);
  237. /// \brief Decode from BER format
  238. /// \param bt BufferedTransformation object
  239. void BERDecode(BufferedTransformation &bt);
  240. /// \brief Decode nonnegative value from big-endian octet string
  241. /// \param bt BufferedTransformation object
  242. /// \param length length of the byte array
  243. void BERDecodeAsOctetString(BufferedTransformation &bt, size_t length);
  244. /// \brief Exception thrown when an error is encountered decoding an OpenPGP integer
  245. class OpenPGPDecodeErr : public Exception
  246. {
  247. public:
  248. OpenPGPDecodeErr() : Exception(INVALID_DATA_FORMAT, "OpenPGP decode error") {}
  249. };
  250. /// \brief Decode from OpenPGP format
  251. /// \param input big-endian byte array
  252. /// \param inputLen length of the byte array
  253. void OpenPGPDecode(const byte *input, size_t inputLen);
  254. /// \brief Decode from OpenPGP format
  255. /// \param bt BufferedTransformation object
  256. void OpenPGPDecode(BufferedTransformation &bt);
  257. //@}
  258. /// \name ACCESSORS
  259. //@{
  260. /// \brief Determines if the Integer is convertable to Long
  261. /// \return true if <tt>*this</tt> can be represented as a signed long
  262. /// \sa ConvertToLong()
  263. bool IsConvertableToLong() const;
  264. /// \brief Convert the Integer to Long
  265. /// \return equivalent signed long if possible, otherwise undefined
  266. /// \sa IsConvertableToLong()
  267. signed long ConvertToLong() const;
  268. /// \brief Determines the number of bits required to represent the Integer
  269. /// \return number of significant bits
  270. /// \details BitCount is calculated as <tt>floor(log2(abs(*this))) + 1</tt>.
  271. unsigned int BitCount() const;
  272. /// \brief Determines the number of bytes required to represent the Integer
  273. /// \return number of significant bytes
  274. /// \details ByteCount is calculated as <tt>ceiling(BitCount()/8)</tt>.
  275. unsigned int ByteCount() const;
  276. /// \brief Determines the number of words required to represent the Integer
  277. /// \return number of significant words
  278. /// \details WordCount is calculated as <tt>ceiling(ByteCount()/sizeof(word))</tt>.
  279. unsigned int WordCount() const;
  280. /// \brief Provides the i-th bit of the Integer
  281. /// \return the i-th bit, i=0 being the least significant bit
  282. bool GetBit(size_t i) const;
  283. /// \brief Provides the i-th byte of the Integer
  284. /// \return the i-th byte
  285. byte GetByte(size_t i) const;
  286. /// \brief Provides the low order bits of the Integer
  287. /// \return n lowest bits of <tt>*this >> i</tt>
  288. lword GetBits(size_t i, size_t n) const;
  289. /// \brief Determines if the Integer is 0
  290. /// \return true if the Integer is 0, false otherwise
  291. bool IsZero() const {return !*this;}
  292. /// \brief Determines if the Integer is non-0
  293. /// \return true if the Integer is non-0, false otherwise
  294. bool NotZero() const {return !IsZero();}
  295. /// \brief Determines if the Integer is negative
  296. /// \return true if the Integer is negative, false otherwise
  297. bool IsNegative() const {return sign == NEGATIVE;}
  298. /// \brief Determines if the Integer is non-negative
  299. /// \return true if the Integer is non-negative, false otherwise
  300. bool NotNegative() const {return !IsNegative();}
  301. /// \brief Determines if the Integer is positive
  302. /// \return true if the Integer is positive, false otherwise
  303. bool IsPositive() const {return NotNegative() && NotZero();}
  304. /// \brief Determines if the Integer is non-positive
  305. /// \return true if the Integer is non-positive, false otherwise
  306. bool NotPositive() const {return !IsPositive();}
  307. /// \brief Determines if the Integer is even parity
  308. /// \return true if the Integer is even, false otherwise
  309. bool IsEven() const {return GetBit(0) == 0;}
  310. /// \brief Determines if the Integer is odd parity
  311. /// \return true if the Integer is odd, false otherwise
  312. bool IsOdd() const {return GetBit(0) == 1;}
  313. //@}
  314. /// \name MANIPULATORS
  315. //@{
  316. /// \brief Assignment
  317. /// \param t the other Integer
  318. /// \return the result of assignment
  319. Integer& operator=(const Integer& t);
  320. /// \brief Addition Assignment
  321. /// \param t the other Integer
  322. /// \return the result of <tt>*this + t</tt>
  323. Integer& operator+=(const Integer& t);
  324. /// \brief Subtraction Assignment
  325. /// \param t the other Integer
  326. /// \return the result of <tt>*this - t</tt>
  327. Integer& operator-=(const Integer& t);
  328. /// \brief Multiplication Assignment
  329. /// \param t the other Integer
  330. /// \return the result of <tt>*this * t</tt>
  331. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  332. Integer& operator*=(const Integer& t) {return *this = Times(t);}
  333. /// \brief Division Assignment
  334. /// \param t the other Integer
  335. /// \return the result of <tt>*this / t</tt>
  336. Integer& operator/=(const Integer& t) {return *this = DividedBy(t);}
  337. /// \brief Remainder Assignment
  338. /// \param t the other Integer
  339. /// \return the result of <tt>*this % t</tt>
  340. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  341. Integer& operator%=(const Integer& t) {return *this = Modulo(t);}
  342. /// \brief Division Assignment
  343. /// \param t the other word
  344. /// \return the result of <tt>*this / t</tt>
  345. Integer& operator/=(word t) {return *this = DividedBy(t);}
  346. /// \brief Remainder Assignment
  347. /// \param t the other word
  348. /// \return the result of <tt>*this % t</tt>
  349. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  350. Integer& operator%=(word t) {return *this = Integer(POSITIVE, 0, Modulo(t));}
  351. /// \brief Left-shift Assignment
  352. /// \param n number of bits to shift
  353. /// \return reference to this Integer
  354. Integer& operator<<=(size_t n);
  355. /// \brief Right-shift Assignment
  356. /// \param n number of bits to shift
  357. /// \return reference to this Integer
  358. Integer& operator>>=(size_t n);
  359. /// \brief Bitwise AND Assignment
  360. /// \param t the other Integer
  361. /// \return the result of <tt>*this & t</tt>
  362. /// \details operator&=() performs a bitwise AND on <tt>*this</tt>. Missing bits are truncated
  363. /// at the most significant bit positions, so the result is as small as the
  364. /// smaller of the operands.
  365. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  366. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  367. /// the integer should be converted to a 2's compliment representation before performing
  368. /// the operation.
  369. /// \since Crypto++ 6.0
  370. Integer& operator&=(const Integer& t);
  371. /// \brief Bitwise OR Assignment
  372. /// \param t the second Integer
  373. /// \return the result of <tt>*this | t</tt>
  374. /// \details operator|=() performs a bitwise OR on <tt>*this</tt>. Missing bits are shifted in
  375. /// at the most significant bit positions, so the result is as large as the
  376. /// larger of the operands.
  377. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  378. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  379. /// the integer should be converted to a 2's compliment representation before performing
  380. /// the operation.
  381. /// \since Crypto++ 6.0
  382. Integer& operator|=(const Integer& t);
  383. /// \brief Bitwise XOR Assignment
  384. /// \param t the other Integer
  385. /// \return the result of <tt>*this ^ t</tt>
  386. /// \details operator^=() performs a bitwise XOR on <tt>*this</tt>. Missing bits are shifted
  387. /// in at the most significant bit positions, so the result is as large as the
  388. /// larger of the operands.
  389. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  390. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  391. /// the integer should be converted to a 2's compliment representation before performing
  392. /// the operation.
  393. /// \since Crypto++ 6.0
  394. Integer& operator^=(const Integer& t);
  395. /// \brief Set this Integer to random integer
  396. /// \param rng RandomNumberGenerator used to generate material
  397. /// \param bitCount the number of bits in the resulting integer
  398. /// \details The random integer created is uniformly distributed over <tt>[0, 2<sup>bitCount</sup>]</tt>.
  399. void Randomize(RandomNumberGenerator &rng, size_t bitCount);
  400. /// \brief Set this Integer to random integer
  401. /// \param rng RandomNumberGenerator used to generate material
  402. /// \param min the minimum value
  403. /// \param max the maximum value
  404. /// \details The random integer created is uniformly distributed over <tt>[min, max]</tt>.
  405. void Randomize(RandomNumberGenerator &rng, const Integer &min, const Integer &max);
  406. /// \brief Set this Integer to random integer of special form
  407. /// \param rng RandomNumberGenerator used to generate material
  408. /// \param min the minimum value
  409. /// \param max the maximum value
  410. /// \param rnType RandomNumberType to specify the type
  411. /// \param equiv the equivalence class based on the parameter \p mod
  412. /// \param mod the modulus used to reduce the equivalence class
  413. /// \throw RandomNumberNotFound if the set is empty.
  414. /// \details Ideally, the random integer created should be uniformly distributed
  415. /// over <tt>{x | min \<= x \<= max</tt> and \p x is of rnType and <tt>x \% mod == equiv}</tt>.
  416. /// However the actual distribution may not be uniform because sequential
  417. /// search is used to find an appropriate number from a random starting
  418. /// point.
  419. /// \details May return (with very small probability) a pseudoprime when a prime
  420. /// is requested and <tt>max \> lastSmallPrime*lastSmallPrime</tt>. \p lastSmallPrime
  421. /// is declared in nbtheory.h.
  422. bool Randomize(RandomNumberGenerator &rng, const Integer &min, const Integer &max, RandomNumberType rnType, const Integer &equiv=Zero(), const Integer &mod=One());
  423. /// \brief Generate a random number
  424. /// \param rng RandomNumberGenerator used to generate material
  425. /// \param params additional parameters that cannot be passed directly to the function
  426. /// \return true if a random number was generated, false otherwise
  427. /// \details GenerateRandomNoThrow attempts to generate a random number according to the
  428. /// parameters specified in params. The function does not throw RandomNumberNotFound.
  429. /// \details The example below generates a prime number using NameValuePairs that Integer
  430. /// class recognizes. The names are not provided in argnames.h.
  431. /// <pre>
  432. /// AutoSeededRandomPool prng;
  433. /// AlgorithmParameters params = MakeParameters("BitLength", 2048)
  434. /// ("RandomNumberType", Integer::PRIME);
  435. /// Integer x;
  436. /// if (x.GenerateRandomNoThrow(prng, params) == false)
  437. /// throw std::runtime_error("Failed to generate prime number");
  438. /// </pre>
  439. bool GenerateRandomNoThrow(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs);
  440. /// \brief Generate a random number
  441. /// \param rng RandomNumberGenerator used to generate material
  442. /// \param params additional parameters that cannot be passed directly to the function
  443. /// \throw RandomNumberNotFound if a random number is not found
  444. /// \details GenerateRandom attempts to generate a random number according to the
  445. /// parameters specified in params.
  446. /// \details The example below generates a prime number using NameValuePairs that Integer
  447. /// class recognizes. The names are not provided in argnames.h.
  448. /// <pre>
  449. /// AutoSeededRandomPool prng;
  450. /// AlgorithmParameters params = MakeParameters("BitLength", 2048)
  451. /// ("RandomNumberType", Integer::PRIME);
  452. /// Integer x;
  453. /// try { x.GenerateRandom(prng, params); }
  454. /// catch (RandomNumberNotFound&) { x = -1; }
  455. /// </pre>
  456. void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs)
  457. {
  458. if (!GenerateRandomNoThrow(rng, params))
  459. throw RandomNumberNotFound();
  460. }
  461. /// \brief Set the n-th bit to value
  462. /// \details 0-based numbering.
  463. void SetBit(size_t n, bool value=1);
  464. /// \brief Set the n-th byte to value
  465. /// \details 0-based numbering.
  466. void SetByte(size_t n, byte value);
  467. /// \brief Reverse the Sign of the Integer
  468. void Negate();
  469. /// \brief Sets the Integer to positive
  470. void SetPositive() {sign = POSITIVE;}
  471. /// \brief Sets the Integer to negative
  472. void SetNegative() {if (!!(*this)) sign = NEGATIVE;}
  473. /// \brief Swaps this Integer with another Integer
  474. void swap(Integer &a);
  475. //@}
  476. /// \name UNARY OPERATORS
  477. //@{
  478. /// \brief Negation
  479. bool operator!() const;
  480. /// \brief Addition
  481. Integer operator+() const {return *this;}
  482. /// \brief Subtraction
  483. Integer operator-() const;
  484. /// \brief Pre-increment
  485. Integer& operator++();
  486. /// \brief Pre-decrement
  487. Integer& operator--();
  488. /// \brief Post-increment
  489. Integer operator++(int) {Integer temp = *this; ++*this; return temp;}
  490. /// \brief Post-decrement
  491. Integer operator--(int) {Integer temp = *this; --*this; return temp;}
  492. //@}
  493. /// \name BINARY OPERATORS
  494. //@{
  495. /// \brief Perform signed comparison
  496. /// \param a the Integer to compare
  497. /// \retval -1 if <tt>*this < a</tt>
  498. /// \retval 0 if <tt>*this = a</tt>
  499. /// \retval 1 if <tt>*this > a</tt>
  500. int Compare(const Integer& a) const;
  501. /// \brief Addition
  502. Integer Plus(const Integer &b) const;
  503. /// \brief Subtraction
  504. Integer Minus(const Integer &b) const;
  505. /// \brief Multiplication
  506. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  507. Integer Times(const Integer &b) const;
  508. /// \brief Division
  509. Integer DividedBy(const Integer &b) const;
  510. /// \brief Remainder
  511. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  512. Integer Modulo(const Integer &b) const;
  513. /// \brief Division
  514. Integer DividedBy(word b) const;
  515. /// \brief Remainder
  516. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  517. word Modulo(word b) const;
  518. /// \brief Bitwise AND
  519. /// \param t the other Integer
  520. /// \return the result of <tt>*this & t</tt>
  521. /// \details And() performs a bitwise AND on the operands. Missing bits are truncated
  522. /// at the most significant bit positions, so the result is as small as the
  523. /// smaller of the operands.
  524. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  525. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  526. /// the integer should be converted to a 2's compliment representation before performing
  527. /// the operation.
  528. /// \since Crypto++ 6.0
  529. Integer And(const Integer& t) const;
  530. /// \brief Bitwise OR
  531. /// \param t the other Integer
  532. /// \return the result of <tt>*this | t</tt>
  533. /// \details Or() performs a bitwise OR on the operands. Missing bits are shifted in
  534. /// at the most significant bit positions, so the result is as large as the
  535. /// larger of the operands.
  536. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  537. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  538. /// the integer should be converted to a 2's compliment representation before performing
  539. /// the operation.
  540. /// \since Crypto++ 6.0
  541. Integer Or(const Integer& t) const;
  542. /// \brief Bitwise XOR
  543. /// \param t the other Integer
  544. /// \return the result of <tt>*this ^ t</tt>
  545. /// \details Xor() performs a bitwise XOR on the operands. Missing bits are shifted in
  546. /// at the most significant bit positions, so the result is as large as the
  547. /// larger of the operands.
  548. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  549. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  550. /// the integer should be converted to a 2's compliment representation before performing
  551. /// the operation.
  552. /// \since Crypto++ 6.0
  553. Integer Xor(const Integer& t) const;
  554. /// \brief Right-shift
  555. Integer operator>>(size_t n) const {return Integer(*this)>>=n;}
  556. /// \brief Left-shift
  557. Integer operator<<(size_t n) const {return Integer(*this)<<=n;}
  558. //@}
  559. /// \name OTHER ARITHMETIC FUNCTIONS
  560. //@{
  561. /// \brief Retrieve the absolute value of this integer
  562. Integer AbsoluteValue() const;
  563. /// \brief Add this integer to itself
  564. Integer Doubled() const {return Plus(*this);}
  565. /// \brief Multiply this integer by itself
  566. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  567. Integer Squared() const {return Times(*this);}
  568. /// \brief Extract square root
  569. /// \details if negative return 0, else return floor of square root
  570. Integer SquareRoot() const;
  571. /// \brief Determine whether this integer is a perfect square
  572. bool IsSquare() const;
  573. /// \brief Determine if 1 or -1
  574. /// \return true if this integer is 1 or -1, false otherwise
  575. bool IsUnit() const;
  576. /// \brief Calculate multiplicative inverse
  577. /// \return MultiplicativeInverse inverse if 1 or -1, otherwise return 0.
  578. Integer MultiplicativeInverse() const;
  579. /// \brief Extended Division
  580. /// \param r a reference for the remainder
  581. /// \param q a reference for the quotient
  582. /// \param a reference to the dividend
  583. /// \param d reference to the divisor
  584. /// \details Divide calculates r and q such that (a == d*q + r) && (0 <= r < abs(d)).
  585. static void CRYPTOPP_API Divide(Integer &r, Integer &q, const Integer &a, const Integer &d);
  586. /// \brief Extended Division
  587. /// \param r a reference for the remainder
  588. /// \param q a reference for the quotient
  589. /// \param a reference to the dividend
  590. /// \param d reference to the divisor
  591. /// \details Divide calculates r and q such that (a == d*q + r) && (0 <= r < abs(d)).
  592. /// This overload uses a faster division algorithm because the divisor is short.
  593. static void CRYPTOPP_API Divide(word &r, Integer &q, const Integer &a, word d);
  594. /// \brief Extended Division
  595. /// \param r a reference for the remainder
  596. /// \param q a reference for the quotient
  597. /// \param a reference to the dividend
  598. /// \param n reference to the divisor
  599. /// \details DivideByPowerOf2 calculates r and q such that (a == d*q + r) && (0 <= r < abs(d)).
  600. /// It returns same result as Divide(r, q, a, Power2(n)), but faster.
  601. /// This overload uses a faster division algorithm because the divisor is a power of 2.
  602. static void CRYPTOPP_API DivideByPowerOf2(Integer &r, Integer &q, const Integer &a, unsigned int n);
  603. /// \brief Calculate greatest common divisor
  604. /// \param a reference to the first number
  605. /// \param n reference to the secind number
  606. /// \return the greatest common divisor <tt>a</tt> and <tt>n</tt>.
  607. static Integer CRYPTOPP_API Gcd(const Integer &a, const Integer &n);
  608. /// \brief Calculate multiplicative inverse
  609. /// \param n reference to the modulus
  610. /// \return an Integer <tt>*this % n</tt>.
  611. /// \details InverseMod returns the multiplicative inverse of the Integer <tt>*this</tt>
  612. /// modulo the Integer <tt>n</tt>. If no Integer exists then Integer 0 is returned.
  613. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  614. Integer InverseMod(const Integer &n) const;
  615. /// \brief Calculate multiplicative inverse
  616. /// \param n the modulus
  617. /// \return a word <tt>*this % n</tt>.
  618. /// \details InverseMod returns the multiplicative inverse of the Integer <tt>*this</tt>
  619. /// modulo the word <tt>n</tt>. If no Integer exists then word 0 is returned.
  620. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  621. word InverseMod(word n) const;
  622. //@}
  623. /// \name INPUT/OUTPUT
  624. //@{
  625. /// \brief Extraction operator
  626. /// \param in reference to a std::istream
  627. /// \param a reference to an Integer
  628. /// \return reference to a std::istream reference
  629. friend CRYPTOPP_DLL std::istream& CRYPTOPP_API operator>>(std::istream& in, Integer &a);
  630. /// \brief Insertion operator
  631. /// \param out reference to a std::ostream
  632. /// \param a a constant reference to an Integer
  633. /// \return reference to a std::ostream reference
  634. /// \details The output integer responds to std::hex, std::oct, std::hex, std::upper and
  635. /// std::lower. The output includes the suffix \a h (for hex), \a . (\a dot, for dec)
  636. /// and \a o (for octal). There is currently no way to suppress the suffix.
  637. /// \details If you want to print an Integer without the suffix or using an arbitrary base, then
  638. /// use IntToString<Integer>().
  639. /// \sa IntToString<Integer>
  640. friend CRYPTOPP_DLL std::ostream& CRYPTOPP_API operator<<(std::ostream& out, const Integer &a);
  641. //@}
  642. /// \brief Modular multiplication
  643. /// \param x reference to the first term
  644. /// \param y reference to the second term
  645. /// \param m reference to the modulus
  646. /// \return an Integer <tt>(a * b) % m</tt>.
  647. CRYPTOPP_DLL friend Integer CRYPTOPP_API a_times_b_mod_c(const Integer &x, const Integer& y, const Integer& m);
  648. /// \brief Modular exponentiation
  649. /// \param x reference to the base
  650. /// \param e reference to the exponent
  651. /// \param m reference to the modulus
  652. /// \return an Integer <tt>(a ^ b) % m</tt>.
  653. CRYPTOPP_DLL friend Integer CRYPTOPP_API a_exp_b_mod_c(const Integer &x, const Integer& e, const Integer& m);
  654. protected:
  655. // http://github.com/weidai11/cryptopp/issues/602
  656. Integer InverseModNext(const Integer &n) const;
  657. private:
  658. Integer(word value, size_t length);
  659. int PositiveCompare(const Integer &t) const;
  660. IntegerSecBlock reg;
  661. Sign sign;
  662. #ifndef CRYPTOPP_DOXYGEN_PROCESSING
  663. friend class ModularArithmetic;
  664. friend class MontgomeryRepresentation;
  665. friend class HalfMontgomeryRepresentation;
  666. friend void PositiveAdd(Integer &sum, const Integer &a, const Integer &b);
  667. friend void PositiveSubtract(Integer &diff, const Integer &a, const Integer &b);
  668. friend void PositiveMultiply(Integer &product, const Integer &a, const Integer &b);
  669. friend void PositiveDivide(Integer &remainder, Integer &quotient, const Integer &dividend, const Integer &divisor);
  670. #endif
  671. };
  672. /// \brief Comparison
  673. inline bool operator==(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)==0;}
  674. /// \brief Comparison
  675. inline bool operator!=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)!=0;}
  676. /// \brief Comparison
  677. inline bool operator> (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)> 0;}
  678. /// \brief Comparison
  679. inline bool operator>=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)>=0;}
  680. /// \brief Comparison
  681. inline bool operator< (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)< 0;}
  682. /// \brief Comparison
  683. inline bool operator<=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)<=0;}
  684. /// \brief Addition
  685. inline CryptoPP::Integer operator+(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Plus(b);}
  686. /// \brief Subtraction
  687. inline CryptoPP::Integer operator-(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Minus(b);}
  688. /// \brief Multiplication
  689. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  690. inline CryptoPP::Integer operator*(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Times(b);}
  691. /// \brief Division
  692. inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.DividedBy(b);}
  693. /// \brief Remainder
  694. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  695. inline CryptoPP::Integer operator%(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Modulo(b);}
  696. /// \brief Division
  697. inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, CryptoPP::word b) {return a.DividedBy(b);}
  698. /// \brief Remainder
  699. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  700. inline CryptoPP::word operator%(const CryptoPP::Integer &a, CryptoPP::word b) {return a.Modulo(b);}
  701. /// \brief Bitwise AND
  702. /// \param a the first Integer
  703. /// \param b the second Integer
  704. /// \return the result of a & b
  705. /// \details operator&() performs a bitwise AND on the operands. Missing bits are truncated
  706. /// at the most significant bit positions, so the result is as small as the
  707. /// smaller of the operands.
  708. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  709. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  710. /// the integer should be converted to a 2's compliment representation before performing
  711. /// the operation.
  712. /// \since Crypto++ 6.0
  713. inline CryptoPP::Integer operator&(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.And(b);}
  714. /// \brief Bitwise OR
  715. /// \param a the first Integer
  716. /// \param b the second Integer
  717. /// \return the result of a | b
  718. /// \details operator|() performs a bitwise OR on the operands. Missing bits are shifted in
  719. /// at the most significant bit positions, so the result is as large as the
  720. /// larger of the operands.
  721. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  722. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  723. /// the integer should be converted to a 2's compliment representation before performing
  724. /// the operation.
  725. /// \since Crypto++ 6.0
  726. inline CryptoPP::Integer operator|(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Or(b);}
  727. /// \brief Bitwise XOR
  728. /// \param a the first Integer
  729. /// \param b the second Integer
  730. /// \return the result of a ^ b
  731. /// \details operator^() performs a bitwise XOR on the operands. Missing bits are shifted
  732. /// in at the most significant bit positions, so the result is as large as the
  733. /// larger of the operands.
  734. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  735. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  736. /// the integer should be converted to a 2's compliment representation before performing
  737. /// the operation.
  738. /// \since Crypto++ 6.0
  739. inline CryptoPP::Integer operator^(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Xor(b);}
  740. NAMESPACE_END
  741. #ifndef __BORLANDC__
  742. NAMESPACE_BEGIN(std)
  743. inline void swap(CryptoPP::Integer &a, CryptoPP::Integer &b)
  744. {
  745. a.swap(b);
  746. }
  747. NAMESPACE_END
  748. #endif
  749. #endif