integer.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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. /// \note If \p bitCount is 0, then this Integer is set to 0 (and not 0 or 1).
  400. void Randomize(RandomNumberGenerator &rng, size_t bitCount);
  401. /// \brief Set this Integer to random integer
  402. /// \param rng RandomNumberGenerator used to generate material
  403. /// \param min the minimum value
  404. /// \param max the maximum value
  405. /// \details The random integer created is uniformly distributed over <tt>[min, max]</tt>.
  406. void Randomize(RandomNumberGenerator &rng, const Integer &min, const Integer &max);
  407. /// \brief Set this Integer to random integer of special form
  408. /// \param rng RandomNumberGenerator used to generate material
  409. /// \param min the minimum value
  410. /// \param max the maximum value
  411. /// \param rnType RandomNumberType to specify the type
  412. /// \param equiv the equivalence class based on the parameter \p mod
  413. /// \param mod the modulus used to reduce the equivalence class
  414. /// \throw RandomNumberNotFound if the set is empty.
  415. /// \details Ideally, the random integer created should be uniformly distributed
  416. /// over <tt>{x | min \<= x \<= max</tt> and \p x is of rnType and <tt>x \% mod == equiv}</tt>.
  417. /// However the actual distribution may not be uniform because sequential
  418. /// search is used to find an appropriate number from a random starting
  419. /// point.
  420. /// \details May return (with very small probability) a pseudoprime when a prime
  421. /// is requested and <tt>max \> lastSmallPrime*lastSmallPrime</tt>. \p lastSmallPrime
  422. /// is declared in nbtheory.h.
  423. bool Randomize(RandomNumberGenerator &rng, const Integer &min, const Integer &max, RandomNumberType rnType, const Integer &equiv=Zero(), const Integer &mod=One());
  424. /// \brief Generate a random number
  425. /// \param rng RandomNumberGenerator used to generate material
  426. /// \param params additional parameters that cannot be passed directly to the function
  427. /// \return true if a random number was generated, false otherwise
  428. /// \details GenerateRandomNoThrow attempts to generate a random number according to the
  429. /// parameters specified in params. The function does not throw RandomNumberNotFound.
  430. /// \details The example below generates a prime number using NameValuePairs that Integer
  431. /// class recognizes. The names are not provided in argnames.h.
  432. /// <pre>
  433. /// AutoSeededRandomPool prng;
  434. /// AlgorithmParameters params = MakeParameters("BitLength", 2048)
  435. /// ("RandomNumberType", Integer::PRIME);
  436. /// Integer x;
  437. /// if (x.GenerateRandomNoThrow(prng, params) == false)
  438. /// throw std::runtime_error("Failed to generate prime number");
  439. /// </pre>
  440. bool GenerateRandomNoThrow(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs);
  441. /// \brief Generate a random number
  442. /// \param rng RandomNumberGenerator used to generate material
  443. /// \param params additional parameters that cannot be passed directly to the function
  444. /// \throw RandomNumberNotFound if a random number is not found
  445. /// \details GenerateRandom attempts to generate a random number according to the
  446. /// parameters specified in params.
  447. /// \details The example below generates a prime number using NameValuePairs that Integer
  448. /// class recognizes. The names are not provided in argnames.h.
  449. /// <pre>
  450. /// AutoSeededRandomPool prng;
  451. /// AlgorithmParameters params = MakeParameters("BitLength", 2048)
  452. /// ("RandomNumberType", Integer::PRIME);
  453. /// Integer x;
  454. /// try { x.GenerateRandom(prng, params); }
  455. /// catch (RandomNumberNotFound&) { x = -1; }
  456. /// </pre>
  457. void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs)
  458. {
  459. if (!GenerateRandomNoThrow(rng, params))
  460. throw RandomNumberNotFound();
  461. }
  462. /// \brief Set the n-th bit to value
  463. /// \details 0-based numbering.
  464. void SetBit(size_t n, bool value=1);
  465. /// \brief Set the n-th byte to value
  466. /// \details 0-based numbering.
  467. void SetByte(size_t n, byte value);
  468. /// \brief Reverse the Sign of the Integer
  469. void Negate();
  470. /// \brief Sets the Integer to positive
  471. void SetPositive() {sign = POSITIVE;}
  472. /// \brief Sets the Integer to negative
  473. void SetNegative() {if (!!(*this)) sign = NEGATIVE;}
  474. /// \brief Swaps this Integer with another Integer
  475. void swap(Integer &a);
  476. //@}
  477. /// \name UNARY OPERATORS
  478. //@{
  479. /// \brief Negation
  480. bool operator!() const;
  481. /// \brief Addition
  482. Integer operator+() const {return *this;}
  483. /// \brief Subtraction
  484. Integer operator-() const;
  485. /// \brief Pre-increment
  486. Integer& operator++();
  487. /// \brief Pre-decrement
  488. Integer& operator--();
  489. /// \brief Post-increment
  490. Integer operator++(int) {Integer temp = *this; ++*this; return temp;}
  491. /// \brief Post-decrement
  492. Integer operator--(int) {Integer temp = *this; --*this; return temp;}
  493. //@}
  494. /// \name BINARY OPERATORS
  495. //@{
  496. /// \brief Perform signed comparison
  497. /// \param a the Integer to compare
  498. /// \retval -1 if <tt>*this < a</tt>
  499. /// \retval 0 if <tt>*this = a</tt>
  500. /// \retval 1 if <tt>*this > a</tt>
  501. int Compare(const Integer& a) const;
  502. /// \brief Addition
  503. Integer Plus(const Integer &b) const;
  504. /// \brief Subtraction
  505. Integer Minus(const Integer &b) const;
  506. /// \brief Multiplication
  507. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  508. Integer Times(const Integer &b) const;
  509. /// \brief Division
  510. Integer DividedBy(const Integer &b) const;
  511. /// \brief Remainder
  512. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  513. Integer Modulo(const Integer &b) const;
  514. /// \brief Division
  515. Integer DividedBy(word b) const;
  516. /// \brief Remainder
  517. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  518. word Modulo(word b) const;
  519. /// \brief Bitwise AND
  520. /// \param t the other Integer
  521. /// \return the result of <tt>*this & t</tt>
  522. /// \details And() performs a bitwise AND on the operands. Missing bits are truncated
  523. /// at the most significant bit positions, so the result is as small as the
  524. /// smaller of the operands.
  525. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  526. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  527. /// the integer should be converted to a 2's compliment representation before performing
  528. /// the operation.
  529. /// \since Crypto++ 6.0
  530. Integer And(const Integer& t) const;
  531. /// \brief Bitwise OR
  532. /// \param t the other Integer
  533. /// \return the result of <tt>*this | t</tt>
  534. /// \details Or() performs a bitwise OR on the operands. Missing bits are shifted in
  535. /// at the most significant bit positions, so the result is as large as the
  536. /// larger of the operands.
  537. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  538. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  539. /// the integer should be converted to a 2's compliment representation before performing
  540. /// the operation.
  541. /// \since Crypto++ 6.0
  542. Integer Or(const Integer& t) const;
  543. /// \brief Bitwise XOR
  544. /// \param t the other Integer
  545. /// \return the result of <tt>*this ^ t</tt>
  546. /// \details Xor() performs a bitwise XOR on the operands. Missing bits are shifted in
  547. /// at the most significant bit positions, so the result is as large as the
  548. /// larger of the operands.
  549. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  550. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  551. /// the integer should be converted to a 2's compliment representation before performing
  552. /// the operation.
  553. /// \since Crypto++ 6.0
  554. Integer Xor(const Integer& t) const;
  555. /// \brief Right-shift
  556. Integer operator>>(size_t n) const {return Integer(*this)>>=n;}
  557. /// \brief Left-shift
  558. Integer operator<<(size_t n) const {return Integer(*this)<<=n;}
  559. //@}
  560. /// \name OTHER ARITHMETIC FUNCTIONS
  561. //@{
  562. /// \brief Retrieve the absolute value of this integer
  563. Integer AbsoluteValue() const;
  564. /// \brief Add this integer to itself
  565. Integer Doubled() const {return Plus(*this);}
  566. /// \brief Multiply this integer by itself
  567. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  568. Integer Squared() const {return Times(*this);}
  569. /// \brief Extract square root
  570. /// \details if negative return 0, else return floor of square root
  571. Integer SquareRoot() const;
  572. /// \brief Determine whether this integer is a perfect square
  573. bool IsSquare() const;
  574. /// \brief Determine if 1 or -1
  575. /// \return true if this integer is 1 or -1, false otherwise
  576. bool IsUnit() const;
  577. /// \brief Calculate multiplicative inverse
  578. /// \return MultiplicativeInverse inverse if 1 or -1, otherwise return 0.
  579. Integer MultiplicativeInverse() const;
  580. /// \brief Extended Division
  581. /// \param r a reference for the remainder
  582. /// \param q a reference for the quotient
  583. /// \param a reference to the dividend
  584. /// \param d reference to the divisor
  585. /// \details Divide calculates r and q such that (a == d*q + r) && (0 <= r < abs(d)).
  586. static void CRYPTOPP_API Divide(Integer &r, Integer &q, const Integer &a, const Integer &d);
  587. /// \brief Extended Division
  588. /// \param r a reference for the remainder
  589. /// \param q a reference for the quotient
  590. /// \param a reference to the dividend
  591. /// \param d reference to the divisor
  592. /// \details Divide calculates r and q such that (a == d*q + r) && (0 <= r < abs(d)).
  593. /// This overload uses a faster division algorithm because the divisor is short.
  594. static void CRYPTOPP_API Divide(word &r, Integer &q, const Integer &a, word d);
  595. /// \brief Extended Division
  596. /// \param r a reference for the remainder
  597. /// \param q a reference for the quotient
  598. /// \param a reference to the dividend
  599. /// \param n reference to the divisor
  600. /// \details DivideByPowerOf2 calculates r and q such that (a == d*q + r) && (0 <= r < abs(d)).
  601. /// It returns same result as Divide(r, q, a, Power2(n)), but faster.
  602. /// This overload uses a faster division algorithm because the divisor is a power of 2.
  603. static void CRYPTOPP_API DivideByPowerOf2(Integer &r, Integer &q, const Integer &a, unsigned int n);
  604. /// \brief Calculate greatest common divisor
  605. /// \param a reference to the first number
  606. /// \param n reference to the secind number
  607. /// \return the greatest common divisor <tt>a</tt> and <tt>n</tt>.
  608. static Integer CRYPTOPP_API Gcd(const Integer &a, const Integer &n);
  609. /// \brief Calculate multiplicative inverse
  610. /// \param n reference to the modulus
  611. /// \return an Integer <tt>*this % n</tt>.
  612. /// \details InverseMod returns the multiplicative inverse of the Integer <tt>*this</tt>
  613. /// modulo the Integer <tt>n</tt>. If no Integer exists then Integer 0 is returned.
  614. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  615. Integer InverseMod(const Integer &n) const;
  616. /// \brief Calculate multiplicative inverse
  617. /// \param n the modulus
  618. /// \return a word <tt>*this % n</tt>.
  619. /// \details InverseMod returns the multiplicative inverse of the Integer <tt>*this</tt>
  620. /// modulo the word <tt>n</tt>. If no Integer exists then word 0 is returned.
  621. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  622. word InverseMod(word n) const;
  623. //@}
  624. /// \name INPUT/OUTPUT
  625. //@{
  626. /// \brief Extraction operator
  627. /// \param in reference to a std::istream
  628. /// \param a reference to an Integer
  629. /// \return reference to a std::istream reference
  630. friend CRYPTOPP_DLL std::istream& CRYPTOPP_API operator>>(std::istream& in, Integer &a);
  631. /// \brief Insertion operator
  632. /// \param out reference to a std::ostream
  633. /// \param a a constant reference to an Integer
  634. /// \return reference to a std::ostream reference
  635. /// \details The output integer responds to hex, std::oct, std::hex, std::upper and
  636. /// std::lower. The output includes the suffix \a h (for hex), \a . (\a dot, for dec)
  637. /// and \a o (for octal). There is currently no way to suppress the suffix.
  638. /// \details If you want to print an Integer without the suffix or using an arbitrary base, then
  639. /// use IntToString<Integer>().
  640. /// \sa IntToString<Integer>
  641. friend CRYPTOPP_DLL std::ostream& CRYPTOPP_API operator<<(std::ostream& out, const Integer &a);
  642. //@}
  643. /// \brief Modular multiplication
  644. /// \param x reference to the first term
  645. /// \param y reference to the second term
  646. /// \param m reference to the modulus
  647. /// \return an Integer <tt>(a * b) % m</tt>.
  648. CRYPTOPP_DLL friend Integer CRYPTOPP_API a_times_b_mod_c(const Integer &x, const Integer& y, const Integer& m);
  649. /// \brief Modular exponentiation
  650. /// \param x reference to the base
  651. /// \param e reference to the exponent
  652. /// \param m reference to the modulus
  653. /// \return an Integer <tt>(a ^ b) % m</tt>.
  654. CRYPTOPP_DLL friend Integer CRYPTOPP_API a_exp_b_mod_c(const Integer &x, const Integer& e, const Integer& m);
  655. protected:
  656. // http://github.com/weidai11/cryptopp/issues/602
  657. Integer InverseModNext(const Integer &n) const;
  658. private:
  659. Integer(word value, size_t length);
  660. int PositiveCompare(const Integer &t) const;
  661. IntegerSecBlock reg;
  662. Sign sign;
  663. #ifndef CRYPTOPP_DOXYGEN_PROCESSING
  664. friend class ModularArithmetic;
  665. friend class MontgomeryRepresentation;
  666. friend class HalfMontgomeryRepresentation;
  667. friend void PositiveAdd(Integer &sum, const Integer &a, const Integer &b);
  668. friend void PositiveSubtract(Integer &diff, const Integer &a, const Integer &b);
  669. friend void PositiveMultiply(Integer &product, const Integer &a, const Integer &b);
  670. friend void PositiveDivide(Integer &remainder, Integer &quotient, const Integer &dividend, const Integer &divisor);
  671. #endif
  672. };
  673. /// \brief Comparison
  674. inline bool operator==(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)==0;}
  675. /// \brief Comparison
  676. inline bool operator!=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)!=0;}
  677. /// \brief Comparison
  678. inline bool operator> (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)> 0;}
  679. /// \brief Comparison
  680. inline bool operator>=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)>=0;}
  681. /// \brief Comparison
  682. inline bool operator< (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)< 0;}
  683. /// \brief Comparison
  684. inline bool operator<=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)<=0;}
  685. /// \brief Addition
  686. inline CryptoPP::Integer operator+(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Plus(b);}
  687. /// \brief Subtraction
  688. inline CryptoPP::Integer operator-(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Minus(b);}
  689. /// \brief Multiplication
  690. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  691. inline CryptoPP::Integer operator*(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Times(b);}
  692. /// \brief Division
  693. inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.DividedBy(b);}
  694. /// \brief Remainder
  695. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  696. inline CryptoPP::Integer operator%(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Modulo(b);}
  697. /// \brief Division
  698. inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, CryptoPP::word b) {return a.DividedBy(b);}
  699. /// \brief Remainder
  700. /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
  701. inline CryptoPP::word operator%(const CryptoPP::Integer &a, CryptoPP::word b) {return a.Modulo(b);}
  702. /// \brief Bitwise AND
  703. /// \param a the first Integer
  704. /// \param b the second Integer
  705. /// \return the result of a & b
  706. /// \details operator&() performs a bitwise AND on the operands. Missing bits are truncated
  707. /// at the most significant bit positions, so the result is as small as the
  708. /// smaller of the operands.
  709. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  710. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  711. /// the integer should be converted to a 2's compliment representation before performing
  712. /// the operation.
  713. /// \since Crypto++ 6.0
  714. inline CryptoPP::Integer operator&(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.And(b);}
  715. /// \brief Bitwise OR
  716. /// \param a the first Integer
  717. /// \param b the second Integer
  718. /// \return the result of a | b
  719. /// \details operator|() performs a bitwise OR on the operands. Missing bits are shifted in
  720. /// at the most significant bit positions, so the result is as large as the
  721. /// larger of the operands.
  722. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  723. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  724. /// the integer should be converted to a 2's compliment representation before performing
  725. /// the operation.
  726. /// \since Crypto++ 6.0
  727. inline CryptoPP::Integer operator|(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Or(b);}
  728. /// \brief Bitwise XOR
  729. /// \param a the first Integer
  730. /// \param b the second Integer
  731. /// \return the result of a ^ b
  732. /// \details operator^() performs a bitwise XOR on the operands. Missing bits are shifted
  733. /// in at the most significant bit positions, so the result is as large as the
  734. /// larger of the operands.
  735. /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
  736. /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
  737. /// the integer should be converted to a 2's compliment representation before performing
  738. /// the operation.
  739. /// \since Crypto++ 6.0
  740. inline CryptoPP::Integer operator^(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Xor(b);}
  741. NAMESPACE_END
  742. #ifndef __BORLANDC__
  743. NAMESPACE_BEGIN(std)
  744. inline void swap(CryptoPP::Integer &a, CryptoPP::Integer &b)
  745. {
  746. a.swap(b);
  747. }
  748. NAMESPACE_END
  749. #endif
  750. #endif