Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1123 lines
23 KiB

  1. // nbtheory.cpp - written and placed in the public domain by Wei Dai
  2. #include "pch.h"
  3. #ifndef CRYPTOPP_IMPORTS
  4. #include "nbtheory.h"
  5. #include "modarith.h"
  6. #include "algparam.h"
  7. #include <math.h>
  8. #include <vector>
  9. #ifdef _OPENMP
  10. // needed in MSVC 2005 to generate correct manifest
  11. #include <omp.h>
  12. #endif
  13. NAMESPACE_BEGIN(CryptoPP)
  14. const word s_lastSmallPrime = 32719;
  15. struct NewPrimeTable
  16. {
  17. std::vector<word16> * operator()() const
  18. {
  19. const unsigned int maxPrimeTableSize = 3511;
  20. std::auto_ptr<std::vector<word16> > pPrimeTable(new std::vector<word16>);
  21. std::vector<word16> &primeTable = *pPrimeTable;
  22. primeTable.reserve(maxPrimeTableSize);
  23. primeTable.push_back(2);
  24. unsigned int testEntriesEnd = 1;
  25. for (unsigned int p=3; p<=s_lastSmallPrime; p+=2)
  26. {
  27. unsigned int j;
  28. for (j=1; j<testEntriesEnd; j++)
  29. if (p%primeTable[j] == 0)
  30. break;
  31. if (j == testEntriesEnd)
  32. {
  33. primeTable.push_back(p);
  34. testEntriesEnd = UnsignedMin(54U, primeTable.size());
  35. }
  36. }
  37. return pPrimeTable.release();
  38. }
  39. };
  40. const word16 * GetPrimeTable(unsigned int &size)
  41. {
  42. const std::vector<word16> &primeTable = Singleton<std::vector<word16>, NewPrimeTable>().Ref();
  43. size = (unsigned int)primeTable.size();
  44. return &primeTable[0];
  45. }
  46. bool IsSmallPrime(const Integer &p)
  47. {
  48. unsigned int primeTableSize;
  49. const word16 * primeTable = GetPrimeTable(primeTableSize);
  50. if (p.IsPositive() && p <= primeTable[primeTableSize-1])
  51. return std::binary_search(primeTable, primeTable+primeTableSize, (word16)p.ConvertToLong());
  52. else
  53. return false;
  54. }
  55. bool TrialDivision(const Integer &p, unsigned bound)
  56. {
  57. unsigned int primeTableSize;
  58. const word16 * primeTable = GetPrimeTable(primeTableSize);
  59. assert(primeTable[primeTableSize-1] >= bound);
  60. unsigned int i;
  61. for (i = 0; primeTable[i]<bound; i++)
  62. if ((p % primeTable[i]) == 0)
  63. return true;
  64. if (bound == primeTable[i])
  65. return (p % bound == 0);
  66. else
  67. return false;
  68. }
  69. bool SmallDivisorsTest(const Integer &p)
  70. {
  71. unsigned int primeTableSize;
  72. const word16 * primeTable = GetPrimeTable(primeTableSize);
  73. return !TrialDivision(p, primeTable[primeTableSize-1]);
  74. }
  75. bool IsFermatProbablePrime(const Integer &n, const Integer &b)
  76. {
  77. if (n <= 3)
  78. return n==2 || n==3;
  79. assert(n>3 && b>1 && b<n-1);
  80. return a_exp_b_mod_c(b, n-1, n)==1;
  81. }
  82. bool IsStrongProbablePrime(const Integer &n, const Integer &b)
  83. {
  84. if (n <= 3)
  85. return n==2 || n==3;
  86. assert(n>3 && b>1 && b<n-1);
  87. if ((n.IsEven() && n!=2) || GCD(b, n) != 1)
  88. return false;
  89. Integer nminus1 = (n-1);
  90. unsigned int a;
  91. // calculate a = largest power of 2 that divides (n-1)
  92. for (a=0; ; a++)
  93. if (nminus1.GetBit(a))
  94. break;
  95. Integer m = nminus1>>a;
  96. Integer z = a_exp_b_mod_c(b, m, n);
  97. if (z==1 || z==nminus1)
  98. return true;
  99. for (unsigned j=1; j<a; j++)
  100. {
  101. z = z.Squared()%n;
  102. if (z==nminus1)
  103. return true;
  104. if (z==1)
  105. return false;
  106. }
  107. return false;
  108. }
  109. bool RabinMillerTest(RandomNumberGenerator &rng, const Integer &n, unsigned int rounds)
  110. {
  111. if (n <= 3)
  112. return n==2 || n==3;
  113. assert(n>3);
  114. Integer b;
  115. for (unsigned int i=0; i<rounds; i++)
  116. {
  117. b.Randomize(rng, 2, n-2);
  118. if (!IsStrongProbablePrime(n, b))
  119. return false;
  120. }
  121. return true;
  122. }
  123. bool IsLucasProbablePrime(const Integer &n)
  124. {
  125. if (n <= 1)
  126. return false;
  127. if (n.IsEven())
  128. return n==2;
  129. assert(n>2);
  130. Integer b=3;
  131. unsigned int i=0;
  132. int j;
  133. while ((j=Jacobi(b.Squared()-4, n)) == 1)
  134. {
  135. if (++i==64 && n.IsSquare()) // avoid infinite loop if n is a square
  136. return false;
  137. ++b; ++b;
  138. }
  139. if (j==0)
  140. return false;
  141. else
  142. return Lucas(n+1, b, n)==2;
  143. }
  144. bool IsStrongLucasProbablePrime(const Integer &n)
  145. {
  146. if (n <= 1)
  147. return false;
  148. if (n.IsEven())
  149. return n==2;
  150. assert(n>2);
  151. Integer b=3;
  152. unsigned int i=0;
  153. int j;
  154. while ((j=Jacobi(b.Squared()-4, n)) == 1)
  155. {
  156. if (++i==64 && n.IsSquare()) // avoid infinite loop if n is a square
  157. return false;
  158. ++b; ++b;
  159. }
  160. if (j==0)
  161. return false;
  162. Integer n1 = n+1;
  163. unsigned int a;
  164. // calculate a = largest power of 2 that divides n1
  165. for (a=0; ; a++)
  166. if (n1.GetBit(a))
  167. break;
  168. Integer m = n1>>a;
  169. Integer z = Lucas(m, b, n);
  170. if (z==2 || z==n-2)
  171. return true;
  172. for (i=1; i<a; i++)
  173. {
  174. z = (z.Squared()-2)%n;
  175. if (z==n-2)
  176. return true;
  177. if (z==2)
  178. return false;
  179. }
  180. return false;
  181. }
  182. struct NewLastSmallPrimeSquared
  183. {
  184. Integer * operator()() const
  185. {
  186. return new Integer(Integer(s_lastSmallPrime).Squared());
  187. }
  188. };
  189. bool IsPrime(const Integer &p)
  190. {
  191. if (p <= s_lastSmallPrime)
  192. return IsSmallPrime(p);
  193. else if (p <= Singleton<Integer, NewLastSmallPrimeSquared>().Ref())
  194. return SmallDivisorsTest(p);
  195. else
  196. return SmallDivisorsTest(p) && IsStrongProbablePrime(p, 3) && IsStrongLucasProbablePrime(p);
  197. }
  198. bool VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level)
  199. {
  200. bool pass = IsPrime(p) && RabinMillerTest(rng, p, 1);
  201. if (level >= 1)
  202. pass = pass && RabinMillerTest(rng, p, 10);
  203. return pass;
  204. }
  205. unsigned int PrimeSearchInterval(const Integer &max)
  206. {
  207. return max.BitCount();
  208. }
  209. static inline bool FastProbablePrimeTest(const Integer &n)
  210. {
  211. return IsStrongProbablePrime(n,2);
  212. }
  213. AlgorithmParameters MakeParametersForTwoPrimesOfEqualSize(unsigned int productBitLength)
  214. {
  215. if (productBitLength < 16)
  216. throw InvalidArgument("invalid bit length");
  217. Integer minP, maxP;
  218. if (productBitLength%2==0)
  219. {
  220. minP = Integer(182) << (productBitLength/2-8);
  221. maxP = Integer::Power2(productBitLength/2)-1;
  222. }
  223. else
  224. {
  225. minP = Integer::Power2((productBitLength-1)/2);
  226. maxP = Integer(181) << ((productBitLength+1)/2-8);
  227. }
  228. return MakeParameters("RandomNumberType", Integer::PRIME)("Min", minP)("Max", maxP);
  229. }
  230. class PrimeSieve
  231. {
  232. public:
  233. // delta == 1 or -1 means double sieve with p = 2*q + delta
  234. PrimeSieve(const Integer &first, const Integer &last, const Integer &step, signed int delta=0);
  235. bool NextCandidate(Integer &c);
  236. void DoSieve();
  237. static void SieveSingle(std::vector<bool> &sieve, word16 p, const Integer &first, const Integer &step, word16 stepInv);
  238. Integer m_first, m_last, m_step;
  239. signed int m_delta;
  240. word m_next;
  241. std::vector<bool> m_sieve;
  242. };
  243. PrimeSieve::PrimeSieve(const Integer &first, const Integer &last, const Integer &step, signed int delta)
  244. : m_first(first), m_last(last), m_step(step), m_delta(delta), m_next(0)
  245. {
  246. DoSieve();
  247. }
  248. bool PrimeSieve::NextCandidate(Integer &c)
  249. {
  250. bool safe = SafeConvert(std::find(m_sieve.begin()+m_next, m_sieve.end(), false) - m_sieve.begin(), m_next);
  251. assert(safe);
  252. if (m_next == m_sieve.size())
  253. {
  254. m_first += long(m_sieve.size())*m_step;
  255. if (m_first > m_last)
  256. return false;
  257. else
  258. {
  259. m_next = 0;
  260. DoSieve();
  261. return NextCandidate(c);
  262. }
  263. }
  264. else
  265. {
  266. c = m_first + long(m_next)*m_step;
  267. ++m_next;
  268. return true;
  269. }
  270. }
  271. void PrimeSieve::SieveSingle(std::vector<bool> &sieve, word16 p, const Integer &first, const Integer &step, word16 stepInv)
  272. {
  273. if (stepInv)
  274. {
  275. size_t sieveSize = sieve.size();
  276. size_t j = (word32(p-(first%p))*stepInv) % p;
  277. // if the first multiple of p is p, skip it
  278. if (first.WordCount() <= 1 && first + step*long(j) == p)
  279. j += p;
  280. for (; j < sieveSize; j += p)
  281. sieve[j] = true;
  282. }
  283. }
  284. void PrimeSieve::DoSieve()
  285. {
  286. unsigned int primeTableSize;
  287. const word16 * primeTable = GetPrimeTable(primeTableSize);
  288. const unsigned int maxSieveSize = 32768;
  289. unsigned int sieveSize = STDMIN(Integer(maxSieveSize), (m_last-m_first)/m_step+1).ConvertToLong();
  290. m_sieve.clear();
  291. m_sieve.resize(sieveSize, false);
  292. if (m_delta == 0)
  293. {
  294. for (unsigned int i = 0; i < primeTableSize; ++i)
  295. SieveSingle(m_sieve, primeTable[i], m_first, m_step, (word16)m_step.InverseMod(primeTable[i]));
  296. }
  297. else
  298. {
  299. assert(m_step%2==0);
  300. Integer qFirst = (m_first-m_delta) >> 1;
  301. Integer halfStep = m_step >> 1;
  302. for (unsigned int i = 0; i < primeTableSize; ++i)
  303. {
  304. word16 p = primeTable[i];
  305. word16 stepInv = (word16)m_step.InverseMod(p);
  306. SieveSingle(m_sieve, p, m_first, m_step, stepInv);
  307. word16 halfStepInv = 2*stepInv < p ? 2*stepInv : 2*stepInv-p;
  308. SieveSingle(m_sieve, p, qFirst, halfStep, halfStepInv);
  309. }
  310. }
  311. }
  312. bool FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Integer &mod, const PrimeSelector *pSelector)
  313. {
  314. assert(!equiv.IsNegative() && equiv < mod);
  315. Integer gcd = GCD(equiv, mod);
  316. if (gcd != Integer::One())
  317. {
  318. // the only possible prime p such that p%mod==equiv where GCD(mod,equiv)!=1 is GCD(mod,equiv)
  319. if (p <= gcd && gcd <= max && IsPrime(gcd) && (!pSelector || pSelector->IsAcceptable(gcd)))
  320. {
  321. p = gcd;
  322. return true;
  323. }
  324. else
  325. return false;
  326. }
  327. unsigned int primeTableSize;
  328. const word16 * primeTable = GetPrimeTable(primeTableSize);
  329. if (p <= primeTable[primeTableSize-1])
  330. {
  331. const word16 *pItr;
  332. --p;
  333. if (p.IsPositive())
  334. pItr = std::upper_bound(primeTable, primeTable+primeTableSize, (word)p.ConvertToLong());
  335. else
  336. pItr = primeTable;
  337. while (pItr < primeTable+primeTableSize && !(*pItr%mod == equiv && (!pSelector || pSelector->IsAcceptable(*pItr))))
  338. ++pItr;
  339. if (pItr < primeTable+primeTableSize)
  340. {
  341. p = *pItr;
  342. return p <= max;
  343. }
  344. p = primeTable[primeTableSize-1]+1;
  345. }
  346. assert(p > primeTable[primeTableSize-1]);
  347. if (mod.IsOdd())
  348. return FirstPrime(p, max, CRT(equiv, mod, 1, 2, 1), mod<<1, pSelector);
  349. p += (equiv-p)%mod;
  350. if (p>max)
  351. return false;
  352. PrimeSieve sieve(p, max, mod);
  353. while (sieve.NextCandidate(p))
  354. {
  355. if ((!pSelector || pSelector->IsAcceptable(p)) && FastProbablePrimeTest(p) && IsPrime(p))
  356. return true;
  357. }
  358. return false;
  359. }
  360. // the following two functions are based on code and comments provided by Preda Mihailescu
  361. static bool ProvePrime(const Integer &p, const Integer &q)
  362. {
  363. assert(p < q*q*q);
  364. assert(p % q == 1);
  365. // this is the Quisquater test. Numbers p having passed the Lucas - Lehmer test
  366. // for q and verifying p < q^3 can only be built up of two factors, both = 1 mod q,
  367. // or be prime. The next two lines build the discriminant of a quadratic equation
  368. // which holds iff p is built up of two factors (excercise ... )
  369. Integer r = (p-1)/q;
  370. if (((r%q).Squared()-4*(r/q)).IsSquare())
  371. return false;
  372. unsigned int primeTableSize;
  373. const word16 * primeTable = GetPrimeTable(primeTableSize);
  374. assert(primeTableSize >= 50);
  375. for (int i=0; i<50; i++)
  376. {
  377. Integer b = a_exp_b_mod_c(primeTable[i], r, p);
  378. if (b != 1)
  379. return a_exp_b_mod_c(b, q, p) == 1;
  380. }
  381. return false;
  382. }
  383. Integer MihailescuProvablePrime(RandomNumberGenerator &rng, unsigned int pbits)
  384. {
  385. Integer p;
  386. Integer minP = Integer::Power2(pbits-1);
  387. Integer maxP = Integer::Power2(pbits) - 1;
  388. if (maxP <= Integer(s_lastSmallPrime).Squared())
  389. {
  390. // Randomize() will generate a prime provable by trial division
  391. p.Randomize(rng, minP, maxP, Integer::PRIME);
  392. return p;
  393. }
  394. unsigned int qbits = (pbits+2)/3 + 1 + rng.GenerateWord32(0, pbits/36);
  395. Integer q = MihailescuProvablePrime(rng, qbits);
  396. Integer q2 = q<<1;
  397. while (true)
  398. {
  399. // this initializes the sieve to search in the arithmetic
  400. // progression p = p_0 + \lambda * q2 = p_0 + 2 * \lambda * q,
  401. // with q the recursively generated prime above. We will be able
  402. // to use Lucas tets for proving primality. A trick of Quisquater
  403. // allows taking q > cubic_root(p) rather then square_root: this
  404. // decreases the recursion.
  405. p.Randomize(rng, minP, maxP, Integer::ANY, 1, q2);
  406. PrimeSieve sieve(p, STDMIN(p+PrimeSearchInterval(maxP)*q2, maxP), q2);
  407. while (sieve.NextCandidate(p))
  408. {
  409. if (FastProbablePrimeTest(p) && ProvePrime(p, q))
  410. return p;
  411. }
  412. }
  413. // not reached
  414. return p;
  415. }
  416. Integer MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits)
  417. {
  418. const unsigned smallPrimeBound = 29, c_opt=10;
  419. Integer p;
  420. unsigned int primeTableSize;
  421. const word16 * primeTable = GetPrimeTable(primeTableSize);
  422. if (bits < smallPrimeBound)
  423. {
  424. do
  425. p.Randomize(rng, Integer::Power2(bits-1), Integer::Power2(bits)-1, Integer::ANY, 1, 2);
  426. while (TrialDivision(p, 1 << ((bits+1)/2)));
  427. }
  428. else
  429. {
  430. const unsigned margin = bits > 50 ? 20 : (bits-10)/2;
  431. double relativeSize;
  432. do
  433. relativeSize = pow(2.0, double(rng.GenerateWord32())/0xffffffff - 1);
  434. while (bits * relativeSize >= bits - margin);
  435. Integer a,b;
  436. Integer q = MaurerProvablePrime(rng, unsigned(bits*relativeSize));
  437. Integer I = Integer::Power2(bits-2)/q;
  438. Integer I2 = I << 1;
  439. unsigned int trialDivisorBound = (unsigned int)STDMIN((unsigned long)primeTable[primeTableSize-1], (unsigned long)bits*bits/c_opt);
  440. bool success = false;
  441. while (!success)
  442. {
  443. p.Randomize(rng, I, I2, Integer::ANY);
  444. p *= q; p <<= 1; ++p;
  445. if (!TrialDivision(p, trialDivisorBound))
  446. {
  447. a.Randomize(rng, 2, p-1, Integer::ANY);
  448. b = a_exp_b_mod_c(a, (p-1)/q, p);
  449. success = (GCD(b-1, p) == 1) && (a_exp_b_mod_c(b, q, p) == 1);
  450. }
  451. }
  452. }
  453. return p;
  454. }
  455. Integer CRT(const Integer &xp, const Integer &p, const Integer &xq, const Integer &q, const Integer &u)
  456. {
  457. // isn't operator overloading great?
  458. return p * (u * (xq-xp) % q) + xp;
  459. /*
  460. Integer t1 = xq-xp;
  461. cout << hex << t1 << endl;
  462. Integer t2 = u * t1;
  463. cout << hex << t2 << endl;
  464. Integer t3 = t2 % q;
  465. cout << hex << t3 << endl;
  466. Integer t4 = p * t3;
  467. cout << hex << t4 << endl;
  468. Integer t5 = t4 + xp;
  469. cout << hex << t5 << endl;
  470. return t5;
  471. */
  472. }
  473. Integer ModularSquareRoot(const Integer &a, const Integer &p)
  474. {
  475. if (p%4 == 3)
  476. return a_exp_b_mod_c(a, (p+1)/4, p);
  477. Integer q=p-1;
  478. unsigned int r=0;
  479. while (q.IsEven())
  480. {
  481. r++;
  482. q >>= 1;
  483. }
  484. Integer n=2;
  485. while (Jacobi(n, p) != -1)
  486. ++n;
  487. Integer y = a_exp_b_mod_c(n, q, p);
  488. Integer x = a_exp_b_mod_c(a, (q-1)/2, p);
  489. Integer b = (x.Squared()%p)*a%p;
  490. x = a*x%p;
  491. Integer tempb, t;
  492. while (b != 1)
  493. {
  494. unsigned m=0;
  495. tempb = b;
  496. do
  497. {
  498. m++;
  499. b = b.Squared()%p;
  500. if (m==r)
  501. return Integer::Zero();
  502. }
  503. while (b != 1);
  504. t = y;
  505. for (unsigned i=0; i<r-m-1; i++)
  506. t = t.Squared()%p;
  507. y = t.Squared()%p;
  508. r = m;
  509. x = x*t%p;
  510. b = tempb*y%p;
  511. }
  512. assert(x.Squared()%p == a);
  513. return x;
  514. }
  515. bool SolveModularQuadraticEquation(Integer &r1, Integer &r2, const Integer &a, const Integer &b, const Integer &c, const Integer &p)
  516. {
  517. Integer D = (b.Squared() - 4*a*c) % p;
  518. switch (Jacobi(D, p))
  519. {
  520. default:
  521. assert(false); // not reached
  522. return false;
  523. case -1:
  524. return false;
  525. case 0:
  526. r1 = r2 = (-b*(a+a).InverseMod(p)) % p;
  527. assert(((r1.Squared()*a + r1*b + c) % p).IsZero());
  528. return true;
  529. case 1:
  530. Integer s = ModularSquareRoot(D, p);
  531. Integer t = (a+a).InverseMod(p);
  532. r1 = (s-b)*t % p;
  533. r2 = (-s-b)*t % p;
  534. assert(((r1.Squared()*a + r1*b + c) % p).IsZero());
  535. assert(((r2.Squared()*a + r2*b + c) % p).IsZero());
  536. return true;
  537. }
  538. }
  539. Integer ModularRoot(const Integer &a, const Integer &dp, const Integer &dq,
  540. const Integer &p, const Integer &q, const Integer &u)
  541. {
  542. Integer p2, q2;
  543. #pragma omp parallel
  544. #pragma omp sections
  545. {
  546. #pragma omp section
  547. p2 = ModularExponentiation((a % p), dp, p);
  548. #pragma omp section
  549. q2 = ModularExponentiation((a % q), dq, q);
  550. }
  551. return CRT(p2, p, q2, q, u);
  552. }
  553. Integer ModularRoot(const Integer &a, const Integer &e,
  554. const Integer &p, const Integer &q)
  555. {
  556. Integer dp = EuclideanMultiplicativeInverse(e, p-1);
  557. Integer dq = EuclideanMultiplicativeInverse(e, q-1);
  558. Integer u = EuclideanMultiplicativeInverse(p, q);
  559. assert(!!dp && !!dq && !!u);
  560. return ModularRoot(a, dp, dq, p, q, u);
  561. }
  562. /*
  563. Integer GCDI(const Integer &x, const Integer &y)
  564. {
  565. Integer a=x, b=y;
  566. unsigned k=0;
  567. assert(!!a && !!b);
  568. while (a[0]==0 && b[0]==0)
  569. {
  570. a >>= 1;
  571. b >>= 1;
  572. k++;
  573. }
  574. while (a[0]==0)
  575. a >>= 1;
  576. while (b[0]==0)
  577. b >>= 1;
  578. while (1)
  579. {
  580. switch (a.Compare(b))
  581. {
  582. case -1:
  583. b -= a;
  584. while (b[0]==0)
  585. b >>= 1;
  586. break;
  587. case 0:
  588. return (a <<= k);
  589. case 1:
  590. a -= b;
  591. while (a[0]==0)
  592. a >>= 1;
  593. break;
  594. default:
  595. assert(false);
  596. }
  597. }
  598. }
  599. Integer EuclideanMultiplicativeInverse(const Integer &a, const Integer &b)
  600. {
  601. assert(b.Positive());
  602. if (a.Negative())
  603. return EuclideanMultiplicativeInverse(a%b, b);
  604. if (b[0]==0)
  605. {
  606. if (!b || a[0]==0)
  607. return Integer::Zero(); // no inverse
  608. if (a==1)
  609. return 1;
  610. Integer u = EuclideanMultiplicativeInverse(b, a);
  611. if (!u)
  612. return Integer::Zero(); // no inverse
  613. else
  614. return (b*(a-u)+1)/a;
  615. }
  616. Integer u=1, d=a, v1=b, v3=b, t1, t3, b2=(b+1)>>1;
  617. if (a[0])
  618. {
  619. t1 = Integer::Zero();
  620. t3 = -b;
  621. }
  622. else
  623. {
  624. t1 = b2;
  625. t3 = a>>1;
  626. }
  627. while (!!t3)
  628. {
  629. while (t3[0]==0)
  630. {
  631. t3 >>= 1;
  632. if (t1[0]==0)
  633. t1 >>= 1;
  634. else
  635. {
  636. t1 >>= 1;
  637. t1 += b2;
  638. }
  639. }
  640. if (t3.Positive())
  641. {
  642. u = t1;
  643. d = t3;
  644. }
  645. else
  646. {
  647. v1 = b-t1;
  648. v3 = -t3;
  649. }
  650. t1 = u-v1;
  651. t3 = d-v3;
  652. if (t1.Negative())
  653. t1 += b;
  654. }
  655. if (d==1)
  656. return u;
  657. else
  658. return Integer::Zero(); // no inverse
  659. }
  660. */
  661. int Jacobi(const Integer &aIn, const Integer &bIn)
  662. {
  663. assert(bIn.IsOdd());
  664. Integer b = bIn, a = aIn%bIn;
  665. int result = 1;
  666. while (!!a)
  667. {
  668. unsigned i=0;
  669. while (a.GetBit(i)==0)
  670. i++;
  671. a>>=i;
  672. if (i%2==1 && (b%8==3 || b%8==5))
  673. result = -result;
  674. if (a%4==3 && b%4==3)
  675. result = -result;
  676. std::swap(a, b);
  677. a %= b;
  678. }
  679. return (b==1) ? result : 0;
  680. }
  681. Integer Lucas(const Integer &e, const Integer &pIn, const Integer &n)
  682. {
  683. unsigned i = e.BitCount();
  684. if (i==0)
  685. return Integer::Two();
  686. MontgomeryRepresentation m(n);
  687. Integer p=m.ConvertIn(pIn%n), two=m.ConvertIn(Integer::Two());
  688. Integer v=p, v1=m.Subtract(m.Square(p), two);
  689. i--;
  690. while (i--)
  691. {
  692. if (e.GetBit(i))
  693. {
  694. // v = (v*v1 - p) % m;
  695. v = m.Subtract(m.Multiply(v,v1), p);
  696. // v1 = (v1*v1 - 2) % m;
  697. v1 = m.Subtract(m.Square(v1), two);
  698. }
  699. else
  700. {
  701. // v1 = (v*v1 - p) % m;
  702. v1 = m.Subtract(m.Multiply(v,v1), p);
  703. // v = (v*v - 2) % m;
  704. v = m.Subtract(m.Square(v), two);
  705. }
  706. }
  707. return m.ConvertOut(v);
  708. }
  709. // This is Peter Montgomery's unpublished Lucas sequence evalutation algorithm.
  710. // The total number of multiplies and squares used is less than the binary
  711. // algorithm (see above). Unfortunately I can't get it to run as fast as
  712. // the binary algorithm because of the extra overhead.
  713. /*
  714. Integer Lucas(const Integer &n, const Integer &P, const Integer &modulus)
  715. {
  716. if (!n)
  717. return 2;
  718. #define f(A, B, C) m.Subtract(m.Multiply(A, B), C)
  719. #define X2(A) m.Subtract(m.Square(A), two)
  720. #define X3(A) m.Multiply(A, m.Subtract(m.Square(A), three))
  721. MontgomeryRepresentation m(modulus);
  722. Integer two=m.ConvertIn(2), three=m.ConvertIn(3);
  723. Integer A=m.ConvertIn(P), B, C, p, d=n, e, r, t, T, U;
  724. while (d!=1)
  725. {
  726. p = d;
  727. unsigned int b = WORD_BITS * p.WordCount();
  728. Integer alpha = (Integer(5)<<(2*b-2)).SquareRoot() - Integer::Power2(b-1);
  729. r = (p*alpha)>>b;
  730. e = d-r;
  731. B = A;
  732. C = two;
  733. d = r;
  734. while (d!=e)
  735. {
  736. if (d<e)
  737. {
  738. swap(d, e);
  739. swap(A, B);
  740. }
  741. unsigned int dm2 = d[0], em2 = e[0];
  742. unsigned int dm3 = d%3, em3 = e%3;
  743. // if ((dm6+em6)%3 == 0 && d <= e + (e>>2))
  744. if ((dm3+em3==0 || dm3+em3==3) && (t = e, t >>= 2, t += e, d <= t))
  745. {
  746. // #1
  747. // t = (d+d-e)/3;
  748. // t = d; t += d; t -= e; t /= 3;
  749. // e = (e+e-d)/3;
  750. // e += e; e -= d; e /= 3;
  751. // d = t;
  752. // t = (d+e)/3
  753. t = d; t += e; t /= 3;
  754. e -= t;
  755. d -= t;
  756. T = f(A, B, C);
  757. U = f(T, A, B);
  758. B = f(T, B, A);
  759. A = U;
  760. continue;
  761. }
  762. // if (dm6 == em6 && d <= e + (e>>2))
  763. if (dm3 == em3 && dm2 == em2 && (t = e, t >>= 2, t += e, d <= t))
  764. {
  765. // #2
  766. // d = (d-e)>>1;
  767. d -= e; d >>= 1;
  768. B = f(A, B, C);
  769. A = X2(A);
  770. continue;
  771. }
  772. // if (d <= (e<<2))
  773. if (d <= (t = e, t <<= 2))
  774. {
  775. // #3
  776. d -= e;
  777. C = f(A, B, C);
  778. swap(B, C);
  779. continue;
  780. }
  781. if (dm2 == em2)
  782. {
  783. // #4
  784. // d = (d-e)>>1;
  785. d -= e; d >>= 1;
  786. B = f(A, B, C);
  787. A = X2(A);
  788. continue;
  789. }
  790. if (dm2 == 0)
  791. {
  792. // #5
  793. d >>= 1;
  794. C = f(A, C, B);
  795. A = X2(A);
  796. continue;
  797. }
  798. if (dm3 == 0)
  799. {
  800. // #6
  801. // d = d/3 - e;
  802. d /= 3; d -= e;
  803. T = X2(A);
  804. C = f(T, f(A, B, C), C);
  805. swap(B, C);
  806. A = f(T, A, A);
  807. continue;
  808. }
  809. if (dm3+em3==0 || dm3+em3==3)
  810. {
  811. // #7
  812. // d = (d-e-e)/3;
  813. d -= e; d -= e; d /= 3;
  814. T = f(A, B, C);
  815. B = f(T, A, B);
  816. A = X3(A);
  817. continue;
  818. }
  819. if (dm3 == em3)
  820. {
  821. // #8
  822. // d = (d-e)/3;
  823. d -= e; d /= 3;
  824. T = f(A, B, C);
  825. C = f(A, C, B);
  826. B = T;
  827. A = X3(A);
  828. continue;
  829. }
  830. assert(em2 == 0);
  831. // #9
  832. e >>= 1;
  833. C = f(C, B, A);
  834. B = X2(B);
  835. }
  836. A = f(A, B, C);
  837. }
  838. #undef f
  839. #undef X2
  840. #undef X3
  841. return m.ConvertOut(A);
  842. }
  843. */
  844. Integer InverseLucas(const Integer &e, const Integer &m, const Integer &p, const Integer &q, const Integer &u)
  845. {
  846. Integer d = (m*m-4);
  847. Integer p2, q2;
  848. #pragma omp parallel
  849. #pragma omp sections
  850. {
  851. #pragma omp section
  852. {
  853. p2 = p-Jacobi(d,p);
  854. p2 = Lucas(EuclideanMultiplicativeInverse(e,p2), m, p);
  855. }
  856. #pragma omp section
  857. {
  858. q2 = q-Jacobi(d,q);
  859. q2 = Lucas(EuclideanMultiplicativeInverse(e,q2), m, q);
  860. }
  861. }
  862. return CRT(p2, p, q2, q, u);
  863. }
  864. unsigned int FactoringWorkFactor(unsigned int n)
  865. {
  866. // extrapolated from the table in Odlyzko's "The Future of Integer Factorization"
  867. // updated to reflect the factoring of RSA-130
  868. if (n<5) return 0;
  869. else return (unsigned int)(2.4 * pow((double)n, 1.0/3.0) * pow(log(double(n)), 2.0/3.0) - 5);
  870. }
  871. unsigned int DiscreteLogWorkFactor(unsigned int n)
  872. {
  873. // assuming discrete log takes about the same time as factoring
  874. if (n<5) return 0;
  875. else return (unsigned int)(2.4 * pow((double)n, 1.0/3.0) * pow(log(double(n)), 2.0/3.0) - 5);
  876. }
  877. // ********************************************************
  878. void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned int qbits)
  879. {
  880. // no prime exists for delta = -1, qbits = 4, and pbits = 5
  881. assert(qbits > 4);
  882. assert(pbits > qbits);
  883. if (qbits+1 == pbits)
  884. {
  885. Integer minP = Integer::Power2(pbits-1);
  886. Integer maxP = Integer::Power2(pbits) - 1;
  887. bool success = false;
  888. while (!success)
  889. {
  890. p.Randomize(rng, minP, maxP, Integer::ANY, 6+5*delta, 12);
  891. PrimeSieve sieve(p, STDMIN(p+PrimeSearchInterval(maxP)*12, maxP), 12, delta);
  892. while (sieve.NextCandidate(p))
  893. {
  894. assert(IsSmallPrime(p) || SmallDivisorsTest(p));
  895. q = (p-delta) >> 1;
  896. assert(IsSmallPrime(q) || SmallDivisorsTest(q));
  897. if (FastProbablePrimeTest(q) && FastProbablePrimeTest(p) && IsPrime(q) && IsPrime(p))
  898. {
  899. success = true;
  900. break;
  901. }
  902. }
  903. }
  904. if (delta == 1)
  905. {
  906. // find g such that g is a quadratic residue mod p, then g has order q
  907. // g=4 always works, but this way we get the smallest quadratic residue (other than 1)
  908. for (g=2; Jacobi(g, p) != 1; ++g) {}
  909. // contributed by Walt Tuvell: g should be the following according to the Law of Quadratic Reciprocity
  910. assert((p%8==1 || p%8==7) ? g==2 : (p%12==1 || p%12==11) ? g==3 : g==4);
  911. }
  912. else
  913. {
  914. assert(delta == -1);
  915. // find g such that g*g-4 is a quadratic non-residue,
  916. // and such that g has order q
  917. for (g=3; ; ++g)
  918. if (Jacobi(g*g-4, p)==-1 && Lucas(q, g, p)==2)
  919. break;
  920. }
  921. }
  922. else
  923. {
  924. Integer minQ = Integer::Power2(qbits-1);
  925. Integer maxQ = Integer::Power2(qbits) - 1;
  926. Integer minP = Integer::Power2(pbits-1);
  927. Integer maxP = Integer::Power2(pbits) - 1;
  928. do
  929. {
  930. q.Randomize(rng, minQ, maxQ, Integer::PRIME);
  931. } while (!p.Randomize(rng, minP, maxP, Integer::PRIME, delta%q, q));
  932. // find a random g of order q
  933. if (delta==1)
  934. {
  935. do
  936. {
  937. Integer h(rng, 2, p-2, Integer::ANY);
  938. g = a_exp_b_mod_c(h, (p-1)/q, p);
  939. } while (g <= 1);
  940. assert(a_exp_b_mod_c(g, q, p)==1);
  941. }
  942. else
  943. {
  944. assert(delta==-1);
  945. do
  946. {
  947. Integer h(rng, 3, p-1, Integer::ANY);
  948. if (Jacobi(h*h-4, p)==1)
  949. continue;
  950. g = Lucas((p+1)/q, h, p);
  951. } while (g <= 2);
  952. assert(Lucas(q, g, p) == 2);
  953. }
  954. }
  955. }
  956. NAMESPACE_END
  957. #endif