Crypto++  5.6.5
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 {
31  InitializeInteger();
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
274  void BERDecode(BufferedTransformation &bt);
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  bool GenerateRandomNoThrow(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs);
451  void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs)
452  {
453  if (!GenerateRandomNoThrow(rng, params))
454  throw RandomNumberNotFound();
455  }
456 
457  /// \brief Set the n-th bit to value
458  /// \details 0-based numbering.
459  void SetBit(size_t n, bool value=1);
460 
461  /// \brief Set the n-th byte to value
462  /// \details 0-based numbering.
463  void SetByte(size_t n, byte value);
464 
465  /// \brief Reverse the Sign of the Integer
466  void Negate();
467 
468  /// \brief Sets the Integer to positive
469  void SetPositive() {sign = POSITIVE;}
470 
471  /// \brief Sets the Integer to negative
472  void SetNegative() {if (!!(*this)) sign = NEGATIVE;}
473 
474  /// \brief Swaps this Integer with another Integer
475  void swap(Integer &a);
476  //@}
477 
478  /// \name UNARY OPERATORS
479  //@{
480  /// \brief Negation
481  bool operator!() const;
482  /// \brief Addition
483  Integer operator+() const {return *this;}
484  /// \brief Subtraction
485  Integer operator-() const;
486  /// \brief Pre-increment
487  Integer& operator++();
488  /// \brief Pre-decrement
489  Integer& operator--();
490  /// \brief Post-increment
491  Integer operator++(int) {Integer temp = *this; ++*this; return temp;}
492  /// \brief Post-decrement
493  Integer operator--(int) {Integer temp = *this; --*this; return temp;}
494  //@}
495 
496  /// \name BINARY OPERATORS
497  //@{
498  /// \brief Perform signed comparison
499  /// \param a the Integer to comapre
500  /// \retval -1 if <tt>*this < a</tt>
501  /// \retval 0 if <tt>*this = a</tt>
502  /// \retval 1 if <tt>*this > a</tt>
503  int Compare(const Integer& a) const;
504 
505  /// \brief Addition
506  Integer Plus(const Integer &b) const;
507  /// \brief Subtraction
508  Integer Minus(const Integer &b) const;
509  /// \brief Multiplication
510  /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
511  Integer Times(const Integer &b) const;
512  /// \brief Division
513  Integer DividedBy(const Integer &b) const;
514  /// \brief Remainder
515  /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
516  Integer Modulo(const Integer &b) const;
517  /// \brief Division
518  Integer DividedBy(word b) const;
519  /// \brief Remainder
520  /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
521  word Modulo(word b) const;
522 
523  /// \brief Bitwise AND
524  /// \param t the other Integer
525  /// \returns the result of <tt>*this & t</tt>
526  /// \details And() performs a bitwise AND on the operands. Missing bits are truncated
527  /// at the most significant bit positions, so the result is as small as the
528  /// smaller of the operands.
529  /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
530  /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
531  /// the integer should be converted to a 2's compliment representation before performing
532  /// the operation.
533  /// \since Crypto++ 6.0
534  Integer And(const Integer& t) const;
535 
536  /// \brief Bitwise OR
537  /// \param t the other Integer
538  /// \returns the result of <tt>*this | t</tt>
539  /// \details Or() performs a bitwise OR on the operands. Missing bits are shifted in
540  /// at the most significant bit positions, so the result is as large as the
541  /// larger of the operands.
542  /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
543  /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
544  /// the integer should be converted to a 2's compliment representation before performing
545  /// the operation.
546  /// \since Crypto++ 6.0
547  Integer Or(const Integer& t) const;
548 
549  /// \brief Bitwise XOR
550  /// \param t the other Integer
551  /// \returns the result of <tt>*this ^ t</tt>
552  /// \details Xor() performs a bitwise XOR on the operands. Missing bits are shifted in
553  /// at the most significant bit positions, so the result is as large as the
554  /// larger of the operands.
555  /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
556  /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
557  /// the integer should be converted to a 2's compliment representation before performing
558  /// the operation.
559  /// \since Crypto++ 6.0
560  Integer Xor(const Integer& t) const;
561 
562  /// \brief Right-shift
563  Integer operator>>(size_t n) const {return Integer(*this)>>=n;}
564  /// \brief Left-shift
565  Integer operator<<(size_t n) const {return Integer(*this)<<=n;}
566  //@}
567 
568  /// \name OTHER ARITHMETIC FUNCTIONS
569  //@{
570  /// \brief Retrieve the absolute value of this integer
571  Integer AbsoluteValue() const;
572  /// \brief Add this integer to itself
573  Integer Doubled() const {return Plus(*this);}
574  /// \brief Multiply this integer by itself
575  /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
576  Integer Squared() const {return Times(*this);}
577  /// \brief Extract square root
578  /// \details if negative return 0, else return floor of square root
579  Integer SquareRoot() const;
580  /// \brief Determine whether this integer is a perfect square
581  bool IsSquare() const;
582 
583  /// is 1 or -1
584  bool IsUnit() const;
585  /// return inverse if 1 or -1, otherwise return 0
586  Integer MultiplicativeInverse() const;
587 
588  /// \brief calculate r and q such that (a == d*q + r) && (0 <= r < abs(d))
589  static void CRYPTOPP_API Divide(Integer &r, Integer &q, const Integer &a, const Integer &d);
590  /// \brief use a faster division algorithm when divisor is short
591  static void CRYPTOPP_API Divide(word &r, Integer &q, const Integer &a, word d);
592 
593  /// \brief returns same result as Divide(r, q, a, Power2(n)), but faster
594  static void CRYPTOPP_API DivideByPowerOf2(Integer &r, Integer &q, const Integer &a, unsigned int n);
595 
596  /// greatest common divisor
597  static Integer CRYPTOPP_API Gcd(const Integer &a, const Integer &n);
598  /// \brief calculate multiplicative inverse of *this mod n
599  Integer InverseMod(const Integer &n) const;
600  ///
601  /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
602  word InverseMod(word n) const;
603  //@}
604 
605  /// \name INPUT/OUTPUT
606  //@{
607  /// \brief Extraction operator
608  /// \param in a reference to a std::istream
609  /// \param a a reference to an Integer
610  /// \returns a reference to a std::istream reference
611  friend CRYPTOPP_DLL std::istream& CRYPTOPP_API operator>>(std::istream& in, Integer &a);
612  ///
613  /// \brief Insertion operator
614  /// \param out a reference to a std::ostream
615  /// \param a a constant reference to an Integer
616  /// \returns a reference to a std::ostream reference
617  /// \details The output integer responds to std::hex, std::oct, std::hex, std::upper and
618  /// std::lower. The output includes the suffix \a \b h (for hex), \a \b . (\a \b dot, for dec)
619  /// and \a \b o (for octal). There is currently no way to suppress the suffix.
620  /// \details If you want to print an Integer without the suffix or using an arbitrary base, then
621  /// use IntToString<Integer>().
622  /// \sa IntToString<Integer>
623  friend CRYPTOPP_DLL std::ostream& CRYPTOPP_API operator<<(std::ostream& out, const Integer &a);
624  //@}
625 
626 #ifndef CRYPTOPP_DOXYGEN_PROCESSING
627  /// modular multiplication
628  CRYPTOPP_DLL friend Integer CRYPTOPP_API a_times_b_mod_c(const Integer &x, const Integer& y, const Integer& m);
629  /// modular exponentiation
630  CRYPTOPP_DLL friend Integer CRYPTOPP_API a_exp_b_mod_c(const Integer &x, const Integer& e, const Integer& m);
631 #endif
632 
633 private:
634 
635  Integer(word value, size_t length);
636  int PositiveCompare(const Integer &t) const;
637 
638  IntegerSecBlock reg;
639  Sign sign;
640 
641 #ifndef CRYPTOPP_DOXYGEN_PROCESSING
642  friend class ModularArithmetic;
643  friend class MontgomeryRepresentation;
644  friend class HalfMontgomeryRepresentation;
645 
646  friend void PositiveAdd(Integer &sum, const Integer &a, const Integer &b);
647  friend void PositiveSubtract(Integer &diff, const Integer &a, const Integer &b);
648  friend void PositiveMultiply(Integer &product, const Integer &a, const Integer &b);
649  friend void PositiveDivide(Integer &remainder, Integer &quotient, const Integer &dividend, const Integer &divisor);
650 #endif
651 };
652 
653 /// \brief Comparison
654 inline bool operator==(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)==0;}
655 /// \brief Comparison
656 inline bool operator!=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)!=0;}
657 /// \brief Comparison
658 inline bool operator> (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)> 0;}
659 /// \brief Comparison
660 inline bool operator>=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)>=0;}
661 /// \brief Comparison
662 inline bool operator< (const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)< 0;}
663 /// \brief Comparison
664 inline bool operator<=(const CryptoPP::Integer& a, const CryptoPP::Integer& b) {return a.Compare(b)<=0;}
665 /// \brief Addition
666 inline CryptoPP::Integer operator+(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Plus(b);}
667 /// \brief Subtraction
668 inline CryptoPP::Integer operator-(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Minus(b);}
669 /// \brief Multiplication
670 /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
671 inline CryptoPP::Integer operator*(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Times(b);}
672 /// \brief Division
673 inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.DividedBy(b);}
674 /// \brief Remainder
675 /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
676 inline CryptoPP::Integer operator%(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Modulo(b);}
677 /// \brief Division
678 inline CryptoPP::Integer operator/(const CryptoPP::Integer &a, CryptoPP::word b) {return a.DividedBy(b);}
679 /// \brief Remainder
680 /// \sa a_times_b_mod_c() and a_exp_b_mod_c()
681 inline CryptoPP::word operator%(const CryptoPP::Integer &a, CryptoPP::word b) {return a.Modulo(b);}
682 
683 /// \brief Bitwise AND
684 /// \param a the first Integer
685 /// \param b the second Integer
686 /// \returns the result of a & b
687 /// \details operator&() performs a bitwise AND on the operands. Missing bits are truncated
688 /// at the most significant bit positions, so the result is as small as the
689 /// smaller of the operands.
690 /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
691 /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
692 /// the integer should be converted to a 2's compliment representation before performing
693 /// the operation.
694 /// \since Crypto++ 6.0
695 inline CryptoPP::Integer operator&(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.And(b);}
696 
697 /// \brief Bitwise OR
698 /// \param a the first Integer
699 /// \param b the second Integer
700 /// \returns the result of a | b
701 /// \details operator|() performs a bitwise OR on the operands. Missing bits are shifted in
702 /// at the most significant bit positions, so the result is as large as the
703 /// larger of the operands.
704 /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
705 /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
706 /// the integer should be converted to a 2's compliment representation before performing
707 /// the operation.
708 /// \since Crypto++ 6.0
709 inline CryptoPP::Integer operator|(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Or(b);}
710 
711 /// \brief Bitwise XOR
712 /// \param a the first Integer
713 /// \param b the second Integer
714 /// \returns the result of a ^ b
715 /// \details operator^() performs a bitwise XOR on the operands. Missing bits are shifted
716 /// in at the most significant bit positions, so the result is as large as the
717 /// larger of the operands.
718 /// \details Internally, Crypto++ uses a sign-magnitude representation. The library
719 /// does not attempt to interpret bits, and the result is always POSITIVE. If needed,
720 /// the integer should be converted to a 2's compliment representation before performing
721 /// the operation.
722 /// \since Crypto++ 6.0
723 inline CryptoPP::Integer operator^(const CryptoPP::Integer &a, const CryptoPP::Integer &b) {return a.Xor(b);}
724 
725 NAMESPACE_END
726 
727 #ifndef __BORLANDC__
728 NAMESPACE_BEGIN(std)
729 inline void swap(CryptoPP::Integer &a, CryptoPP::Integer &b)
730 {
731  a.swap(b);
732 }
733 NAMESPACE_END
734 #endif
735 
736 #endif
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:157
void SetNegative()
Sets the Integer to negative.
Definition: integer.h:472
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:671
Integer & operator/=(word t)
Division Assignment.
Definition: integer.h:372
Integer Or(const Integer &t) const
Bitwise OR.
Definition: integer.cpp:3778
Integer And(const Integer &t) const
Bitwise AND.
Definition: integer.cpp:3752
Integer Plus(const Integer &b) const
Addition.
Definition: integer.cpp:3904
Integer operator--(int)
Post-decrement.
Definition: integer.h:493
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:141
an unsigned value
Definition: integer.h:85
void SetPositive()
Sets the Integer to positive.
Definition: integer.h:469
inline ::Integer operator%(const ::Integer &a, const ::Integer &b)
Remainder.
Definition: integer.h:676
Secure memory block with allocator and cleanup.
Definition: secblock.h:459
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:39
STL namespace.
Interface for random number generators.
Definition: cryptlib.h:1339
Interface for buffered transformations.
Definition: cryptlib.h:1486
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:654
inline ::Integer operator+(const ::Integer &a, const ::Integer &b)
Addition.
Definition: integer.h:666
Sign
Used internally to represent the integer.
Definition: integer.h:73
Classes and functions for secure memory allocations.
Integer Modulo(const Integer &b) const
Remainder.
Definition: integer.cpp:4211
Integer & operator/=(const Integer &t)
Division Assignment.
Definition: integer.h:367
inline ::Integer operator-(const ::Integer &a, const ::Integer &b)
Subtraction.
Definition: integer.h:668
Integer DividedBy(const Integer &b) const
Division.
Definition: integer.cpp:4204
Integer Times(const Integer &b) const
Multiplication.
Definition: integer.cpp:4100
a number with no special properties
Definition: integer.h:93
bool operator!=(const ::Integer &a, const ::Integer &b)
Comparison.
Definition: integer.h:656
bool operator<=(const ::Integer &a, const ::Integer &b)
Comparison.
Definition: integer.h:664
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:3052
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:695
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:145
Integer & operator*=(const Integer &t)
Multiplication Assignment.
Definition: integer.h:365
bool operator>(const ::Integer &a, const ::Integer &b)
Comparison.
Definition: integer.h:658
inline ::Integer operator^(const ::Integer &a, const ::Integer &b)
Bitwise XOR.
Definition: integer.h:723
Integer operator++(int)
Post-increment.
Definition: integer.h:491
Exception thrown when division by 0 is encountered.
Definition: integer.h:55
const NameValuePairs g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.h:501
Integer Squared() const
Multiply this integer by itself.
Definition: integer.h:576
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:276
Integer operator<<(size_t n) const
Left-shift.
Definition: integer.h:565
Integer Minus(const Integer &b) const
Subtraction.
Definition: integer.cpp:3950
Integer Doubled() const
Add this integer to itself.
Definition: integer.h:573
Integer operator>>(size_t n) const
Right-shift.
Definition: integer.h:563
bool NotPositive() const
Determines if the Integer is non-positive.
Definition: integer.h:345
Integer operator+() const
Addition.
Definition: integer.h:483
Integer Xor(const Integer &t) const
Bitwise XOR.
Definition: integer.cpp:3804
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:1825
bool operator<(const ::Integer &a, const ::Integer &b)
Comparison.
Definition: integer.h:662
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:709
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:660
inline ::Integer operator/(const ::Integer &a, const ::Integer &b)
Division.
Definition: integer.h:673
Interface for retrieving values given their names.
Definition: cryptlib.h:294