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