Crypto++ 8.0 Free C++ class library of cryptographic schemes

nbtheory.h
Go to the documentation of this file.
1 // nbtheory.h - originally written and placed in the public domain by Wei Dai
2
3 /// \file nbtheory.h
4 /// \brief Classes and functions for number theoretic operations
5
6 #ifndef CRYPTOPP_NBTHEORY_H
7 #define CRYPTOPP_NBTHEORY_H
8
9 #include "cryptlib.h"
10 #include "integer.h"
11 #include "algparam.h"
12
13 NAMESPACE_BEGIN(CryptoPP)
14
15 /// \brief The Small Prime table
16 /// \details GetPrimeTable obtains pointer to small prime table and provides the size of the table.
17 CRYPTOPP_DLL const word16 * CRYPTOPP_API GetPrimeTable(unsigned int &size);
18
19 // ************ primality testing ****************
20
21 /// \brief Generates a provable prime
22 /// \param rng a RandomNumberGenerator to produce random material
23 /// \param bits the number of bits in the prime number
24 /// \returns Integer() meeting Maurer's tests for primality
25 CRYPTOPP_DLL Integer CRYPTOPP_API MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits);
26
27 /// \brief Generates a provable prime
28 /// \param rng a RandomNumberGenerator to produce random material
29 /// \param bits the number of bits in the prime number
30 /// \returns Integer() meeting Mihailescu's tests for primality
31 /// \details Mihailescu's methods performs a search using algorithmic progressions.
32 CRYPTOPP_DLL Integer CRYPTOPP_API MihailescuProvablePrime(RandomNumberGenerator &rng, unsigned int bits);
33
34 /// \brief Tests whether a number is a small prime
35 /// \param p a candidate prime to test
36 /// \returns true if p is a small prime, false otherwise
37 /// \details Internally, the library maintains a table of the first 32719 prime numbers
38 /// in sorted order. IsSmallPrime searches the table and returns true if p is
39 /// in the table.
40 CRYPTOPP_DLL bool CRYPTOPP_API IsSmallPrime(const Integer &p);
41
42 /// \brief Tests whether a number is divisible by a small prime
43 /// \returns true if p is divisible by some prime less than bound.
44 /// \details TrialDivision() returns <tt>true</tt> if <tt>p</tt> is divisible by some prime less
45 /// than <tt>bound</tt>. <tt>bound</tt> should not be greater than the largest entry in the
46 /// prime table, which is 32719.
47 CRYPTOPP_DLL bool CRYPTOPP_API TrialDivision(const Integer &p, unsigned bound);
48
49 /// \brief Tests whether a number is divisible by a small prime
50 /// \returns true if p is NOT divisible by small primes.
51 /// \details SmallDivisorsTest() returns <tt>true</tt> if <tt>p</tt> is NOT divisible by some
52 /// prime less than 32719.
53 CRYPTOPP_DLL bool CRYPTOPP_API SmallDivisorsTest(const Integer &p);
54
55 /// \brief Determine if a number is probably prime
56 /// \param n the number to test
57 /// \param b the base to exponentiate
58 /// \returns true if the number n is probably prime, false otherwise.
59 /// \details IsFermatProbablePrime raises <tt>b</tt> to the <tt>n-1</tt> power and checks if
60 /// the result is congruent to 1 modulo <tt>n</tt>.
61 /// \details These is no reason to use IsFermatProbablePrime, use IsStrongProbablePrime or
62 /// IsStrongLucasProbablePrime instead.
63 /// \sa IsStrongProbablePrime, IsStrongLucasProbablePrime
64 CRYPTOPP_DLL bool CRYPTOPP_API IsFermatProbablePrime(const Integer &n, const Integer &b);
65
66 /// \brief Determine if a number is probably prime
67 /// \param n the number to test
68 /// \returns true if the number n is probably prime, false otherwise.
69 /// \details These is no reason to use IsLucasProbablePrime, use IsStrongProbablePrime or
70 /// IsStrongLucasProbablePrime instead.
71 /// \sa IsStrongProbablePrime, IsStrongLucasProbablePrime
72 CRYPTOPP_DLL bool CRYPTOPP_API IsLucasProbablePrime(const Integer &n);
73
74 /// \brief Determine if a number is probably prime
75 /// \param n the number to test
76 /// \param b the base to exponentiate
77 /// \returns true if the number n is probably prime, false otherwise.
78 CRYPTOPP_DLL bool CRYPTOPP_API IsStrongProbablePrime(const Integer &n, const Integer &b);
79
80 /// \brief Determine if a number is probably prime
81 /// \param n the number to test
82 /// \returns true if the number n is probably prime, false otherwise.
83 CRYPTOPP_DLL bool CRYPTOPP_API IsStrongLucasProbablePrime(const Integer &n);
84
85 /// \brief Determine if a number is probably prime
86 /// \param rng a RandomNumberGenerator to produce random material
87 /// \param n the number to test
88 /// \param rounds the number of tests to perform
89 /// \details This is the Rabin-Miller primality test, i.e. repeating the strong probable prime
90 /// test for several rounds with random bases
91 /// \sa <A HREF="https://crypto.stackexchange.com/q/17707/10496">Trial divisions before
92 /// Miller-Rabin checks?</A> on Crypto Stack Exchange
93 CRYPTOPP_DLL bool CRYPTOPP_API RabinMillerTest(RandomNumberGenerator &rng, const Integer &n, unsigned int rounds);
94
95 /// \brief Verifies a number is probably prime
96 /// \param p a candidate prime to test
97 /// \returns true if p is a probable prime, false otherwise
98 /// \details IsPrime() is suitable for testing candidate primes when creating them. Internally,
99 /// IsPrime() utilizes SmallDivisorsTest(), IsStrongProbablePrime() and IsStrongLucasProbablePrime().
100 CRYPTOPP_DLL bool CRYPTOPP_API IsPrime(const Integer &p);
101
102 /// \brief Verifies a number is probably prime
103 /// \param rng a RandomNumberGenerator for randomized testing
104 /// \param p a candidate prime to test
105 /// \param level the level of thoroughness of testing
106 /// \returns true if p is a strong probable prime, false otherwise
107 /// \details VerifyPrime() is suitable for testing candidate primes created by others. Internally,
108 /// VerifyPrime() utilizes IsPrime() and one-round RabinMillerTest(). If the candiate passes and
109 /// level is greater than 1, then 10 round RabinMillerTest() primality testing is performed.
110 CRYPTOPP_DLL bool CRYPTOPP_API VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level = 1);
111
112 /// \brief Application callback to signal suitability of a cabdidate prime
113 class CRYPTOPP_DLL PrimeSelector
114 {
115 public:
116 const PrimeSelector *GetSelectorPointer() const {return this;}
117 virtual bool IsAcceptable(const Integer &candidate) const =0;
118 };
119
120 /// \brief Finds a random prime of special form
121 /// \param p an Integer reference to receive the prime
122 /// \param max the maximum value
123 /// \param equiv the equivalence class based on the parameter mod
124 /// \param mod the modulus used to reduce the equivalence class
125 /// \param pSelector pointer to a PrimeSelector function for the application to signal suitability
126 /// \returns true if and only if FirstPrime() finds a prime and returns the prime through p. If FirstPrime()
127 /// returns false, then no such prime exists and the value of p is undefined
128 /// \details FirstPrime() uses a fast sieve to find the first probable prime
129 /// in <tt>{x | p<=x<=max and x%mod==equiv}</tt>
130 CRYPTOPP_DLL bool CRYPTOPP_API FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Integer &mod, const PrimeSelector *pSelector);
131
132 CRYPTOPP_DLL unsigned int CRYPTOPP_API PrimeSearchInterval(const Integer &max);
133
134 CRYPTOPP_DLL AlgorithmParameters CRYPTOPP_API MakeParametersForTwoPrimesOfEqualSize(unsigned int productBitLength);
135
136 // ********** other number theoretic functions ************
137
138 /// \brief Calculate the greatest common divisor
139 /// \param a the first term
140 /// \param b the second term
141 /// \returns the greatest common divisor if one exists, 0 otherwise.
142 inline Integer GCD(const Integer &a, const Integer &b)
143 {return Integer::Gcd(a,b);}
144
145 /// \brief Determine relative primality
146 /// \param a the first term
147 /// \param b the second term
148 /// \returns true if <tt>a</tt> and <tt>b</tt> are relatively prime, false otherwise.
149 inline bool RelativelyPrime(const Integer &a, const Integer &b)
150 {return Integer::Gcd(a,b) == Integer::One();}
151
152 /// \brief Calculate the least common multiple
153 /// \param a the first term
154 /// \param b the second term
155 /// \returns the least common multiple of <tt>a</tt> and <tt>b</tt>.
156 inline Integer LCM(const Integer &a, const Integer &b)
157 {return a/Integer::Gcd(a,b)*b;}
158
159 /// \brief Calculate multiplicative inverse
160 /// \param a the number to test
161 /// \param b the modulus
162 /// \returns an Integer <tt>(a ^ -1) % n</tt> or 0 if none exists.
163 /// \details EuclideanMultiplicativeInverse returns the multiplicative inverse of the Integer
164 /// <tt>*a</tt> modulo the Integer <tt>b</tt>. If no Integer exists then Integer 0 is returned.
165 inline Integer EuclideanMultiplicativeInverse(const Integer &a, const Integer &b)
166 {return a.InverseMod(b);}
167
168
169 /// \brief Chinese Remainder Theorem
170 /// \param xp the first number, mod p
171 /// \param p the first prime modulus
172 /// \param xq the second number, mod q
173 /// \param q the second prime modulus
174 /// \param u inverse of p mod q
175 /// \returns the CRT value of the parameters
176 /// \details CRT uses the Chinese Remainder Theorem to calculate <tt>x</tt> given
177 /// <tt>x mod p</tt> and <tt>x mod q</tt>, and <tt>u</tt> the inverse of <tt>p mod q</tt>.
178 CRYPTOPP_DLL Integer CRYPTOPP_API CRT(const Integer &xp, const Integer &p, const Integer &xq, const Integer &q, const Integer &u);
179
180 /// \brief Calculate the Jacobi symbol
181 /// \param a the first term
182 /// \param b the second term
183 /// \returns the the Jacobi symbol.
184 /// \details Jacobi symbols are calculated using the following rules:
185 /// -# if <tt>b</tt> is prime, then <tt>Jacobi(a, b)</tt>, then return 0
186 /// -# if <tt>a%b</tt>==0 AND <tt>a</tt> is quadratic residue <tt>mod b</tt>, then return 1
187 /// -# return -1 otherwise
188 /// \details Refer to a number theory book for what Jacobi symbol means when <tt>b</tt> is not prime.
189 CRYPTOPP_DLL int CRYPTOPP_API Jacobi(const Integer &a, const Integer &b);
190
191 /// \brief Calculate the Lucas value
192 /// \returns the Lucas value
193 /// \details Lucas() calculates the Lucas function <tt>V_e(p, 1) mod n</tt>.
194 CRYPTOPP_DLL Integer CRYPTOPP_API Lucas(const Integer &e, const Integer &p, const Integer &n);
195
196 /// \brief Calculate the inverse Lucas value
197 /// \returns the inverse Lucas value
198 /// \details InverseLucas() calculates <tt>x</tt> such that <tt>m==Lucas(e, x, p*q)</tt>,
199 /// <tt>p q</tt> primes, <tt>u</tt> is inverse of <tt>p mod q</tt>.
200 CRYPTOPP_DLL Integer CRYPTOPP_API InverseLucas(const Integer &e, const Integer &m, const Integer &p, const Integer &q, const Integer &u);
201
202 /// \brief Modular multiplication
203 /// \param x the first term
204 /// \param y the second term
205 /// \param m the modulus
206 /// \returns an Integer <tt>(x * y) % m</tt>.
207 inline Integer ModularMultiplication(const Integer &x, const Integer &y, const Integer &m)
208 {return a_times_b_mod_c(x, y, m);}
209
210 /// \brief Modular exponentiation
211 /// \param x the base
212 /// \param e the exponent
213 /// \param m the modulus
214 /// \returns an Integer <tt>(a ^ b) % m</tt>.
215 inline Integer ModularExponentiation(const Integer &x, const Integer &e, const Integer &m)
216 {return a_exp_b_mod_c(x, e, m);}
217
218 /// \brief Extract a modular square root
219 /// \param a the number to extract square root
220 /// \param p the prime modulus
221 /// \returns the modular square root if it exists
222 /// \details ModularSquareRoot returns <tt>x</tt> such that <tt>x*x%p == a</tt>, <tt>p</tt> prime
223 CRYPTOPP_DLL Integer CRYPTOPP_API ModularSquareRoot(const Integer &a, const Integer &p);
224
225 /// \brief Extract a modular root
226 /// \returns a modular root if it exists
227 /// \details ModularRoot returns <tt>x</tt> such that <tt>a==ModularExponentiation(x, e, p*q)</tt>,
228 /// <tt>p</tt> <tt>q</tt> primes, and <tt>e</tt> relatively prime to <tt>(p-1)*(q-1)</tt>,
229 /// <tt>dp=d%(p-1)</tt>, <tt>dq=d%(q-1)</tt>, (d is inverse of <tt>e mod (p-1)*(q-1)</tt>)
230 /// and <tt>u=inverse of p mod q</tt>.
231 CRYPTOPP_DLL Integer CRYPTOPP_API ModularRoot(const Integer &a, const Integer &dp, const Integer &dq, const Integer &p, const Integer &q, const Integer &u);
232
233 /// \brief Solve a Modular Quadratic Equation
234 /// \param r1 the first residue
235 /// \param r2 the second residue
236 /// \param a the first coefficient
237 /// \param b the second coefficient
238 /// \param c the third constant
239 /// \param p the prime modulus
240 /// \returns true if solutions exist
241 /// \details SolveModularQuadraticEquation() finds <tt>r1</tt> and <tt>r2</tt> such that <tt>ax^2 +
242 /// bx + c == 0 (mod p)</tt> for x in <tt>{r1, r2}</tt>, <tt>p</tt> prime.
243 CRYPTOPP_DLL bool CRYPTOPP_API SolveModularQuadraticEquation(Integer &r1, Integer &r2, const Integer &a, const Integer &b, const Integer &c, const Integer &p);
244
245 /// \brief Estimate work factor
246 /// \param bitlength the size of the number, in bits
247 /// \returns the estimated work factor, in operations
248 /// \details DiscreteLogWorkFactor returns log base 2 of estimated number of operations to
249 /// calculate discrete log or factor a number.
250 CRYPTOPP_DLL unsigned int CRYPTOPP_API DiscreteLogWorkFactor(unsigned int bitlength);
251
252 /// \brief Estimate work factor
253 /// \param bitlength the size of the number, in bits
254 /// \returns the estimated work factor, in operations
255 /// \details FactoringWorkFactor returns log base 2 of estimated number of operations to
256 /// calculate discrete log or factor a number.
257 CRYPTOPP_DLL unsigned int CRYPTOPP_API FactoringWorkFactor(unsigned int bitlength);
258
259 // ********************************************************
260
261 /// \brief Generator of prime numbers of special forms
262 class CRYPTOPP_DLL PrimeAndGenerator
263 {
264 public:
265 /// \brief Construct a PrimeAndGenerator
266 PrimeAndGenerator() {}
267
268 /// \brief Construct a PrimeAndGenerator
269 /// \param delta +1 or -1
270 /// \param rng a RandomNumberGenerator derived class
271 /// \param pbits the number of bits in the prime p
272 /// \details PrimeAndGenerator() generates a random prime p of the form <tt>2*q+delta</tt>, where delta is 1 or -1 and q is
273 /// also prime. Internally the constructor calls <tt>Generate(delta, rng, pbits, pbits-1)</tt>.
274 /// \pre <tt>pbits > 5</tt>
275 /// \warning This PrimeAndGenerator() is slow because primes of this form are harder to find.
276 PrimeAndGenerator(signed int delta, RandomNumberGenerator &rng, unsigned int pbits)
277 {Generate(delta, rng, pbits, pbits-1);}
278
279 /// \brief Construct a PrimeAndGenerator
280 /// \param delta +1 or -1
281 /// \param rng a RandomNumberGenerator derived class
282 /// \param pbits the number of bits in the prime p
283 /// \param qbits the number of bits in the prime q
284 /// \details PrimeAndGenerator() generates a random prime p of the form <tt>2*r*q+delta</tt>, where q is also prime.
285 /// Internally the constructor calls <tt>Generate(delta, rng, pbits, qbits)</tt>.
286 /// \pre <tt>qbits > 4 && pbits > qbits</tt>
287 PrimeAndGenerator(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned qbits)
288 {Generate(delta, rng, pbits, qbits);}
289
290 /// \brief Generate a Prime and Generator
291 /// \param delta +1 or -1
292 /// \param rng a RandomNumberGenerator derived class
293 /// \param pbits the number of bits in the prime p
294 /// \param qbits the number of bits in the prime q
295 /// \details Generate() generates a random prime p of the form <tt>2*r*q+delta</tt>, where q is also prime.
296 void Generate(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned qbits);
297
298 /// \brief Retrieve first prime
299 /// \returns Prime() returns the prime p.
300 const Integer& Prime() const {return p;}
301
302 /// \brief Retrieve second prime
303 /// \returns SubPrime() returns the prime q.
304 const Integer& SubPrime() const {return q;}
305
306 /// \brief Retrieve the generator
307 /// \returns Generator() returns the the generator g.
308 const Integer& Generator() const {return g;}
309
310 private:
311 Integer p, q, g;
312 };
313
314 NAMESPACE_END
315
316 #endif
CRT
Integer CRT(const Integer &xp, const Integer &p, const Integer &xq, const Integer &q, const Integer &u)
Chinese Remainder Theorem.
Definition: nbtheory.cpp:553
GetPrimeTable
const word16 * GetPrimeTable(unsigned int &size)
The Small Prime table.
Definition: nbtheory.cpp:53
algparam.h
Classes for working with NameValuePairs.
IsLucasProbablePrime
bool IsLucasProbablePrime(const Integer &n)
Determine if a number is probably prime.
Definition: nbtheory.cpp:155
FirstPrime
bool FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Integer &mod, const PrimeSelector *pSelector)
Finds a random prime of special form.
Definition: nbtheory.cpp:379
Integer::Gcd
static Integer Gcd(const Integer &a, const Integer &n)
Calculate greatest common divisor.
Definition: integer.cpp:4416
SmallDivisorsTest
bool SmallDivisorsTest(const Integer &p)
Tests whether a number is divisible by a small prime.
Definition: nbtheory.cpp:89
IsStrongLucasProbablePrime
bool IsStrongLucasProbablePrime(const Integer &n)
Determine if a number is probably prime.
Definition: nbtheory.cpp:182
cryptlib.h
Abstract base classes that provide a uniform interface to this library.
MaurerProvablePrime
Integer MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits)
Generates a provable prime.
Definition: nbtheory.cpp:510
IsSmallPrime
bool IsSmallPrime(const Integer &p)
Tests whether a number is a small prime.
Definition: nbtheory.cpp:60
RandomNumberGenerator
Interface for random number generators.
Definition: cryptlib.h:1383
IsFermatProbablePrime
bool IsFermatProbablePrime(const Integer &n, const Integer &b)
Determine if a number is probably prime.
Definition: nbtheory.cpp:96
Jacobi
int Jacobi(const Integer &a, const Integer &b)
Calculate the Jacobi symbol.
Definition: nbtheory.cpp:785
PrimeAndGenerator::PrimeAndGenerator
PrimeAndGenerator(signed int delta, RandomNumberGenerator &rng, unsigned int pbits)
Construct a PrimeAndGenerator.
Definition: nbtheory.h:276
PrimeAndGenerator
Generator of prime numbers of special forms.
Definition: nbtheory.h:262
ModularSquareRoot
Integer ModularSquareRoot(const Integer &a, const Integer &p)
Extract a modular square root.
Definition: nbtheory.cpp:572
Integer::One
static const Integer & One()
Integer representing 1.
Definition: integer.cpp:4868
InverseLucas
Integer InverseLucas(const Integer &e, const Integer &m, const Integer &p, const Integer &q, const Integer &u)
Calculate the inverse Lucas value.
Definition: nbtheory.cpp:998
IsStrongProbablePrime
bool IsStrongProbablePrime(const Integer &n, const Integer &b)
Determine if a number is probably prime.
Definition: nbtheory.cpp:105
MihailescuProvablePrime
Integer MihailescuProvablePrime(RandomNumberGenerator &rng, unsigned int bits)
Generates a provable prime.
Definition: nbtheory.cpp:470
GCD
Integer GCD(const Integer &a, const Integer &b)
Calculate the greatest common divisor.
Definition: nbtheory.h:142
PrimeAndGenerator::SubPrime
const Integer & SubPrime() const
Retrieve second prime.
Definition: nbtheory.h:304
PrimeAndGenerator::Prime
const Integer & Prime() const
Retrieve first prime.
Definition: nbtheory.h:300
Lucas
Integer Lucas(const Integer &e, const Integer &p, const Integer &n)
Calculate the Lucas value.
Definition: nbtheory.cpp:812
VerifyPrime
bool VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level=1)
Verifies a number is probably prime.
Definition: nbtheory.cpp:247
PrimeSelector
Application callback to signal suitability of a cabdidate prime.
Definition: nbtheory.h:113
Integer
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
LCM
Integer LCM(const Integer &a, const Integer &b)
Calculate the least common multiple.
Definition: nbtheory.h:156
ModularMultiplication
Integer ModularMultiplication(const Integer &x, const Integer &y, const Integer &m)
Modular multiplication.
Definition: nbtheory.h:207
IsPrime
bool IsPrime(const Integer &p)
Verifies a number is probably prime.
Definition: nbtheory.cpp:237
PrimeAndGenerator::PrimeAndGenerator
PrimeAndGenerator(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned qbits)
Construct a PrimeAndGenerator.
Definition: nbtheory.h:287
TrialDivision
bool TrialDivision(const Integer &p, unsigned bound)
Tests whether a number is divisible by a small prime.
Definition: nbtheory.cpp:71
DiscreteLogWorkFactor
unsigned int DiscreteLogWorkFactor(unsigned int bitlength)
Estimate work factor.
Definition: nbtheory.cpp:1027
ModularRoot
Integer ModularRoot(const Integer &a, const Integer &dp, const Integer &dq, const Integer &p, const Integer &q, const Integer &u)
Extract a modular root.
Definition: nbtheory.cpp:646
EuclideanMultiplicativeInverse
Integer EuclideanMultiplicativeInverse(const Integer &a, const Integer &b)
Calculate multiplicative inverse.
Definition: nbtheory.h:165
RelativelyPrime
bool RelativelyPrime(const Integer &a, const Integer &b)
Determine relative primality.
Definition: nbtheory.h:149
AlgorithmParameters
An object that implements NameValuePairs.
Definition: algparam.h:419
RabinMillerTest
bool RabinMillerTest(RandomNumberGenerator &rng, const Integer &n, unsigned int rounds)
Determine if a number is probably prime.
Definition: nbtheory.cpp:138
integer.h
Multiple precision integer with arithmetic operations.
CryptoPP
Crypto++ library namespace.
SolveModularQuadraticEquation
bool SolveModularQuadraticEquation(Integer &r1, Integer &r2, const Integer &a, const Integer &b, const Integer &c, const Integer &p)
Solve a Modular Quadratic Equation.
Definition: nbtheory.cpp:621
ModularExponentiation
Integer ModularExponentiation(const Integer &x, const Integer &e, const Integer &m)
Modular exponentiation.
Definition: nbtheory.h:215
PrimeAndGenerator::PrimeAndGenerator
PrimeAndGenerator()
Construct a PrimeAndGenerator.
Definition: nbtheory.h:266
FactoringWorkFactor
unsigned int FactoringWorkFactor(unsigned int bitlength)
Estimate work factor.
Definition: nbtheory.cpp:1019
PrimeAndGenerator::Generator
const Integer & Generator() const
Retrieve the generator.
Definition: nbtheory.h:308