Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

420 lines
13 KiB

  1. #ifndef CRYPTOPP_INTEGER_H
  2. #define CRYPTOPP_INTEGER_H
  3. /** \file */
  4. #include "cryptlib.h"
  5. #include "secblock.h"
  6. #include <iosfwd>
  7. #include <algorithm>
  8. NAMESPACE_BEGIN(CryptoPP)
  9. struct InitializeInteger // used to initialize static variables
  10. {
  11. InitializeInteger();
  12. };
  13. typedef SecBlock<word, AllocatorWithCleanup<word, CRYPTOPP_BOOL_X86> > IntegerSecBlock;
  14. //! multiple precision integer and basic arithmetics
  15. /*! This class can represent positive and negative integers
  16. with absolute value less than (256**sizeof(word)) ** (256**sizeof(int)).
  17. \nosubgrouping
  18. */
  19. class CRYPTOPP_DLL Integer : private InitializeInteger, public ASN1Object
  20. {
  21. public:
  22. //! \name ENUMS, EXCEPTIONS, and TYPEDEFS
  23. //@{
  24. //! division by zero exception
  25. class DivideByZero : public Exception
  26. {
  27. public:
  28. DivideByZero() : Exception(OTHER_ERROR, "Integer: division by zero") {}
  29. };
  30. //!
  31. class RandomNumberNotFound : public Exception
  32. {
  33. public:
  34. RandomNumberNotFound() : Exception(OTHER_ERROR, "Integer: no integer satisfies the given parameters") {}
  35. };
  36. //!
  37. enum Sign {POSITIVE=0, NEGATIVE=1};
  38. //!
  39. enum Signedness {
  40. //!
  41. UNSIGNED,
  42. //!
  43. SIGNED};
  44. //!
  45. enum RandomNumberType {
  46. //!
  47. ANY,
  48. //!
  49. PRIME};
  50. //@}
  51. //! \name CREATORS
  52. //@{
  53. //! creates the zero integer
  54. Integer();
  55. //! copy constructor
  56. Integer(const Integer& t);
  57. //! convert from signed long
  58. Integer(signed long value);
  59. //! convert from lword
  60. Integer(Sign s, lword value);
  61. //! convert from two words
  62. Integer(Sign s, word highWord, word lowWord);
  63. //! convert from string
  64. /*! str can be in base 2, 8, 10, or 16. Base is determined by a
  65. case insensitive suffix of 'h', 'o', or 'b'. No suffix means base 10.
  66. */
  67. explicit Integer(const char *str);
  68. explicit Integer(const wchar_t *str);
  69. //! convert from big-endian byte array
  70. Integer(const byte *encodedInteger, size_t byteCount, Signedness s=UNSIGNED);
  71. //! convert from big-endian form stored in a BufferedTransformation
  72. Integer(BufferedTransformation &bt, size_t byteCount, Signedness s=UNSIGNED);
  73. //! convert from BER encoded byte array stored in a BufferedTransformation object
  74. explicit Integer(BufferedTransformation &bt);
  75. //! create a random integer
  76. /*! The random integer created is uniformly distributed over [0, 2**bitcount). */
  77. Integer(RandomNumberGenerator &rng, size_t bitcount);
  78. //! avoid calling constructors for these frequently used integers
  79. static const Integer & CRYPTOPP_API Zero();
  80. //! avoid calling constructors for these frequently used integers
  81. static const Integer & CRYPTOPP_API One();
  82. //! avoid calling constructors for these frequently used integers
  83. static const Integer & CRYPTOPP_API Two();
  84. //! create a random integer of special type
  85. /*! Ideally, the random integer created should be uniformly distributed
  86. over {x | min <= x <= max and x is of rnType and x % mod == equiv}.
  87. However the actual distribution may not be uniform because sequential
  88. search is used to find an appropriate number from a random starting
  89. point.
  90. May return (with very small probability) a pseudoprime when a prime
  91. is requested and max > lastSmallPrime*lastSmallPrime (lastSmallPrime
  92. is declared in nbtheory.h).
  93. \throw RandomNumberNotFound if the set is empty.
  94. */
  95. Integer(RandomNumberGenerator &rng, const Integer &min, const Integer &max, RandomNumberType rnType=ANY, const Integer &equiv=Zero(), const Integer &mod=One());
  96. //! return the integer 2**e
  97. static Integer CRYPTOPP_API Power2(size_t e);
  98. //@}
  99. //! \name ENCODE/DECODE
  100. //@{
  101. //! minimum number of bytes to encode this integer
  102. /*! MinEncodedSize of 0 is 1 */
  103. size_t MinEncodedSize(Signedness=UNSIGNED) const;
  104. //! encode in big-endian format
  105. /*! unsigned means encode absolute value, signed means encode two's complement if negative.
  106. if outputLen < MinEncodedSize, the most significant bytes will be dropped
  107. if outputLen > MinEncodedSize, the most significant bytes will be padded
  108. */
  109. void Encode(byte *output, size_t outputLen, Signedness=UNSIGNED) const;
  110. //!
  111. void Encode(BufferedTransformation &bt, size_t outputLen, Signedness=UNSIGNED) const;
  112. //! encode using Distinguished Encoding Rules, put result into a BufferedTransformation object
  113. void DEREncode(BufferedTransformation &bt) const;
  114. //! encode absolute value as big-endian octet string
  115. void DEREncodeAsOctetString(BufferedTransformation &bt, size_t length) const;
  116. //! encode absolute value in OpenPGP format, return length of output
  117. size_t OpenPGPEncode(byte *output, size_t bufferSize) const;
  118. //! encode absolute value in OpenPGP format, put result into a BufferedTransformation object
  119. size_t OpenPGPEncode(BufferedTransformation &bt) const;
  120. //!
  121. void Decode(const byte *input, size_t inputLen, Signedness=UNSIGNED);
  122. //!
  123. //* Precondition: bt.MaxRetrievable() >= inputLen
  124. void Decode(BufferedTransformation &bt, size_t inputLen, Signedness=UNSIGNED);
  125. //!
  126. void BERDecode(const byte *input, size_t inputLen);
  127. //!
  128. void BERDecode(BufferedTransformation &bt);
  129. //! decode nonnegative value as big-endian octet string
  130. void BERDecodeAsOctetString(BufferedTransformation &bt, size_t length);
  131. class OpenPGPDecodeErr : public Exception
  132. {
  133. public:
  134. OpenPGPDecodeErr() : Exception(INVALID_DATA_FORMAT, "OpenPGP decode error") {}
  135. };
  136. //!
  137. void OpenPGPDecode(const byte *input, size_t inputLen);
  138. //!
  139. void OpenPGPDecode(BufferedTransformation &bt);
  140. //@}
  141. //! \name ACCESSORS
  142. //@{
  143. //! return true if *this can be represented as a signed long
  144. bool IsConvertableToLong() const;
  145. //! return equivalent signed long if possible, otherwise undefined
  146. signed long ConvertToLong() const;
  147. //! number of significant bits = floor(log2(abs(*this))) + 1
  148. unsigned int BitCount() const;
  149. //! number of significant bytes = ceiling(BitCount()/8)
  150. unsigned int ByteCount() const;
  151. //! number of significant words = ceiling(ByteCount()/sizeof(word))
  152. unsigned int WordCount() const;
  153. //! return the i-th bit, i=0 being the least significant bit
  154. bool GetBit(size_t i) const;
  155. //! return the i-th byte
  156. byte GetByte(size_t i) const;
  157. //! return n lowest bits of *this >> i
  158. lword GetBits(size_t i, size_t n) const;
  159. //!
  160. bool IsZero() const {return !*this;}
  161. //!
  162. bool NotZero() const {return !IsZero();}
  163. //!
  164. bool IsNegative() const {return sign == NEGATIVE;}
  165. //!
  166. bool NotNegative() const {return !IsNegative();}
  167. //!
  168. bool IsPositive() const {return NotNegative() && NotZero();}
  169. //!
  170. bool NotPositive() const {return !IsPositive();}
  171. //!
  172. bool IsEven() const {return GetBit(0) == 0;}
  173. //!
  174. bool IsOdd() const {return GetBit(0) == 1;}
  175. //@}
  176. //! \name MANIPULATORS
  177. //@{
  178. //!
  179. Integer& operator=(const Integer& t);
  180. //!
  181. Integer& operator+=(const Integer& t);
  182. //!
  183. Integer& operator-=(const Integer& t);
  184. //!
  185. Integer& operator*=(const Integer& t) {return *this = Times(t);}
  186. //!
  187. Integer& operator/=(const Integer& t) {return *this = DividedBy(t);}
  188. //!
  189. Integer& operator%=(const Integer& t) {return *this = Modulo(t);}
  190. //!
  191. Integer& operator/=(word t) {return *this = DividedBy(t);}
  192. //!
  193. Integer& operator%=(word t) {return *this = Integer(POSITIVE, 0, Modulo(t));}
  194. //!
  195. Integer& operator<<=(size_t);
  196. //!
  197. Integer& operator>>=(size_t);
  198. //!
  199. void Randomize(RandomNumberGenerator &rng, size_t bitcount);
  200. //!
  201. void Randomize(RandomNumberGenerator &rng, const Integer &min, const Integer &max);
  202. //! set this Integer to a random element of {x | min <= x <= max and x is of rnType and x % mod == equiv}
  203. /*! returns false if the set is empty */
  204. bool Randomize(RandomNumberGenerator &rng, const Integer &min, const Integer &max, RandomNumberType rnType, const Integer &equiv=Zero(), const Integer &mod=One());
  205. bool GenerateRandomNoThrow(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs);
  206. void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs)
  207. {
  208. if (!GenerateRandomNoThrow(rng, params))
  209. throw RandomNumberNotFound();
  210. }
  211. //! set the n-th bit to value
  212. void SetBit(size_t n, bool value=1);
  213. //! set the n-th byte to value
  214. void SetByte(size_t n, byte value);
  215. //!
  216. void Negate();
  217. //!
  218. void SetPositive() {sign = POSITIVE;}
  219. //!
  220. void SetNegative() {if (!!(*this)) sign = NEGATIVE;}
  221. //!
  222. void swap(Integer &a);
  223. //@}
  224. //! \name UNARY OPERATORS
  225. //@{
  226. //!
  227. bool operator!() const;
  228. //!
  229. Integer operator+() const {return *this;}
  230. //!
  231. Integer operator-() const;
  232. //!
  233. Integer& operator++();
  234. //!
  235. Integer& operator--();
  236. //!
  237. Integer operator++(int) {Integer temp = *this; ++*this; return temp;}
  238. //!
  239. Integer operator--(int) {Integer temp = *this; --*this; return temp;}
  240. //@}
  241. //! \name BINARY OPERATORS
  242. //@{
  243. //! signed comparison
  244. /*! \retval -1 if *this < a
  245. \retval 0 if *this = a
  246. \retval 1 if *this > a
  247. */
  248. int Compare(const Integer& a) const;
  249. //!
  250. Integer Plus(const Integer &b) const;
  251. //!
  252. Integer Minus(const Integer &b) const;
  253. //!
  254. Integer Times(const Integer &b) const;
  255. //!
  256. Integer DividedBy(const Integer &b) const;
  257. //!
  258. Integer Modulo(const Integer &b) const;
  259. //!
  260. Integer DividedBy(word b) const;
  261. //!
  262. word Modulo(word b) const;
  263. //!
  264. Integer operator>>(size_t n) const {return Integer(*this)>>=n;}
  265. //!
  266. Integer operator<<(size_t n) const {return Integer(*this)<<=n;}
  267. //@}
  268. //! \name OTHER ARITHMETIC FUNCTIONS
  269. //@{
  270. //!
  271. Integer AbsoluteValue() const;
  272. //!
  273. Integer Doubled() const {return Plus(*this);}
  274. //!
  275. Integer Squared() const {return Times(*this);}
  276. //! extract square root, if negative return 0, else return floor of square root
  277. Integer SquareRoot() const;
  278. //! return whether this integer is a perfect square
  279. bool IsSquare() const;
  280. //! is 1 or -1
  281. bool IsUnit() const;
  282. //! return inverse if 1 or -1, otherwise return 0
  283. Integer MultiplicativeInverse() const;
  284. //! modular multiplication
  285. CRYPTOPP_DLL friend Integer CRYPTOPP_API a_times_b_mod_c(const Integer &x, const Integer& y, const Integer& m);
  286. //! modular exponentiation
  287. CRYPTOPP_DLL friend Integer CRYPTOPP_API a_exp_b_mod_c(const Integer &x, const Integer& e, const Integer& m);
  288. //! calculate r and q such that (a == d*q + r) && (0 <= r < abs(d))
  289. static void CRYPTOPP_API Divide(Integer &r, Integer &q, const Integer &a, const Integer &d);
  290. //! use a faster division algorithm when divisor is short
  291. static void CRYPTOPP_API Divide(word &r, Integer &q, const Integer &a, word d);
  292. //! returns same result as Divide(r, q, a, Power2(n)), but faster
  293. static void CRYPTOPP_API DivideByPowerOf2(Integer &r, Integer &q, const Integer &a, unsigned int n);
  294. //! greatest common divisor
  295. static Integer CRYPTOPP_API Gcd(const Integer &a, const Integer &n);
  296. //! calculate multiplicative inverse of *this mod n
  297. Integer InverseMod(const Integer &n) const;
  298. //!
  299. word InverseMod(word n) const;
  300. //@}
  301. //! \name INPUT/OUTPUT
  302. //@{
  303. //!
  304. friend CRYPTOPP_DLL std::istream& CRYPTOPP_API operator>>(std::istream& in, Integer &a);
  305. //!
  306. friend CRYPTOPP_DLL std::ostream& CRYPTOPP_API operator<<(std::ostream& out, const Integer &a);
  307. //@}
  308. private:
  309. friend class ModularArithmetic;
  310. friend class MontgomeryRepresentation;
  311. friend class HalfMontgomeryRepresentation;
  312. Integer(word value, size_t length);
  313. int PositiveCompare(const Integer &t) const;
  314. friend void PositiveAdd(Integer &sum, const Integer &a, const Integer &b);
  315. friend void PositiveSubtract(Integer &diff, const Integer &a, const Integer &b);
  316. friend void PositiveMultiply(Integer &product, const Integer &a, const Integer &b);
  317. friend void PositiveDivide(Integer &remainder, Integer &quotient, const Integer &dividend, const Integer &divisor);
  318. IntegerSecBlock reg;
  319. Sign sign;
  320. };
  321. //!
  322. inline bool operator==(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)==0;}
  323. //!
  324. inline bool operator!=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)!=0;}
  325. //!
  326. inline bool operator> (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)> 0;}
  327. //!
  328. inline bool operator>=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)>=0;}
  329. //!
  330. inline bool operator< (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)< 0;}
  331. //!
  332. inline bool operator<=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)<=0;}
  333. //!
  334. inline CryptoPP::Integer operator+(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Plus(b);}
  335. //!
  336. inline CryptoPP::Integer operator-(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Minus(b);}
  337. //!
  338. inline CryptoPP::Integer operator*(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Times(b);}
  339. //!
  340. inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.DividedBy(b);}
  341. //!
  342. inline CryptoPP::Integer operator%(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Modulo(b);}
  343. //!
  344. inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, CryptoPP::word b) {return a.DividedBy(b);}
  345. //!
  346. inline CryptoPP::word operator%(const CryptoPP::Integer &a, CryptoPP::word b) {return a.Modulo(b);}
  347. NAMESPACE_END
  348. #ifndef __BORLANDC__
  349. NAMESPACE_BEGIN(std)
  350. inline void swap(CryptoPP::Integer &a, CryptoPP::Integer &b)
  351. {
  352. a.swap(b);
  353. }
  354. NAMESPACE_END
  355. #endif
  356. #endif