nbtheory.h 15 KB

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