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