2
0

prime.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. /*
  2. * Copyright (c) 1995 Colin Plumb. All rights reserved.
  3. * For licensing and other legal details, see the file legal.c.
  4. *
  5. * Prime generation using the bignum library and sieving.
  6. */
  7. #ifndef HAVE_CONFIG_H
  8. #define HAVE_CONFIG_H 0
  9. #endif
  10. #if HAVE_CONFIG_H
  11. #include "bnconfig.h"
  12. #endif
  13. /*
  14. * Some compilers complain about #if FOO if FOO isn't defined,
  15. * so do the ANSI-mandated thing explicitly...
  16. */
  17. #ifndef NO_ASSERT_H
  18. #define NO_ASSERT_H 0
  19. #endif
  20. #if !NO_ASSERT_H
  21. #include <assert.h>
  22. #else
  23. #define assert(x) (void)0
  24. #endif
  25. #include <stdarg.h> /* We just can't live without this... */
  26. #ifndef BNDEBUG
  27. #define BNDEBUG 1
  28. #endif
  29. #if BNDEBUG
  30. #include <stdio.h>
  31. #endif
  32. #include "bn.h"
  33. #include "lbnmem.h"
  34. #include "prime.h"
  35. #include "sieve.h"
  36. #include "kludge.h"
  37. /* Size of the shuffle table */
  38. #define SHUFFLE 256
  39. /* Size of the sieve area */
  40. #define SIEVE 32768u/16
  41. /* Confirmation tests. The first one *must* be 2 */
  42. static unsigned const confirm[] = {2, 3, 5, 7, 11, 13, 17};
  43. #define CONFIRMTESTS (sizeof(confirm)/sizeof(*confirm))
  44. /*
  45. * Helper function that does the slow primality test.
  46. * bn is the input bignum; a and e are temporary buffers that are
  47. * allocated by the caller to save overhead.
  48. *
  49. * Returns 0 if prime, >0 if not prime, and -1 on error (out of memory).
  50. * If not prime, returns the number of modular exponentiations performed.
  51. * Calls the given progress function with a '*' for each primality test
  52. * that is passed.
  53. *
  54. * The testing consists of strong pseudoprimality tests, to the bases given
  55. * in the confirm[] array above. (Also called Miller-Rabin, although that's
  56. * not technically correct if we're using fixed bases.) Some people worry
  57. * that this might not be enough. Number theorists may wish to generate
  58. * primality proofs, but for random inputs, this returns non-primes with
  59. * a probability which is quite negligible, which is good enough.
  60. *
  61. * It has been proved (see Carl Pomerance, "On the Distribution of
  62. * Pseudoprimes", Math. Comp. v.37 (1981) pp. 587-593) that the number of
  63. * pseudoprimes (composite numbers that pass a Fermat test to the base 2)
  64. * less than x is bounded by:
  65. * exp(ln(x)^(5/14)) <= P_2(x) ### CHECK THIS FORMULA - it looks wrong! ###
  66. * P_2(x) <= x * exp(-1/2 * ln(x) * ln(ln(ln(x))) / ln(ln(x))).
  67. * Thus, the local density of Pseudoprimes near x is at most
  68. * exp(-1/2 * ln(x) * ln(ln(ln(x))) / ln(ln(x))), and at least
  69. * exp(ln(x)^(5/14) - ln(x)). Here are some values of this function
  70. * for various k-bit numbers x = 2^k:
  71. * Bits Density <= Bit equivalent Density >= Bit equivalent
  72. * 128 3.577869e-07 21.414396 4.202213e-37 120.840190
  73. * 192 4.175629e-10 31.157288 4.936250e-56 183.724558
  74. * 256 5.804314e-13 40.647940 4.977813e-75 246.829095
  75. * 384 1.578039e-18 59.136573 3.938861e-113 373.400096
  76. * 512 5.858255e-24 77.175803 2.563353e-151 500.253110
  77. * 768 1.489276e-34 112.370944 7.872825e-228 754.422724
  78. * 1024 6.633188e-45 146.757062 1.882404e-304 1008.953565
  79. *
  80. * As you can see, there's quite a bit of slop between these estimates.
  81. * In fact, the density of pseudoprimes is conjectured to be closer to the
  82. * square of that upper bound. E.g. the density of pseudoprimes of size
  83. * 256 is around 3 * 10^-27. The density of primes is very high, from
  84. * 0.005636 at 256 bits to 0.001409 at 1024 bits, i.e. more than 10^-3.
  85. *
  86. * For those people used to cryptographic levels of security where the
  87. * 56 bits of DES key space is too small because it's exhaustible with
  88. * custom hardware searching engines, note that you are not generating
  89. * 50,000,000 primes per second on each of 56,000 custom hardware chips
  90. * for several hours. The chances that another Dinosaur Killer asteroid
  91. * will land today is about 10^-11 or 2^-36, so it would be better to
  92. * spend your time worrying about *that*. Well, okay, there should be
  93. * some derating for the chance that astronomers haven't seen it yet,
  94. * but I think you get the idea. For a good feel about the probability
  95. * of various events, I have heard that a good book is by E'mile Borel,
  96. * "Les Probabilite's et la vie". (The 's are accents, not apostrophes.)
  97. *
  98. * For more on the subject, try "Finding Four Million Large Random Primes",
  99. * by Ronald Rivest, in Advancess in Cryptology: Proceedings of Crypto
  100. * '90. He used a small-divisor test, then a Fermat test to the base 2,
  101. * and then 8 iterations of a Miller-Rabin test. About 718 million random
  102. * 256-bit integers were generated, 43,741,404 passed the small divisor
  103. * test, 4,058,000 passed the Fermat test, and all 4,058,000 passed all
  104. * 8 iterations of the Miller-Rabin test, proving their primality beyond
  105. * most reasonable doubts.
  106. *
  107. * If the probability of getting a pseudoprime is some small p, then the
  108. * probability of not getting it in t trials is (1-p)^t. Remember that,
  109. * for small p, (1-p)^(1/p) ~ 1/e, the base of natural logarithms.
  110. * (This is more commonly expressed as e = lim_{x\to\infty} (1+1/x)^x.)
  111. * Thus, (1-p)^t ~ e^(-p*t) = exp(-p*t). So the odds of being able to
  112. * do this many tests without seeing a pseudoprime if you assume that
  113. * p = 10^-6 (one in a million) is one in 57.86. If you assume that
  114. * p = 2*10^-6, it's one in 3347.6. So it's implausible that the density
  115. * of pseudoprimes is much more than one millionth the density of primes.
  116. *
  117. * He also gives a theoretical argument that the chance of finding a
  118. * 256-bit non-prime which satisfies one Fermat test to the base 2 is
  119. * less than 10^-22. The small divisor test improves this number, and
  120. * if the numbers are 512 bits (as needed for a 1024-bit key) the odds
  121. * of failure shrink to about 10^-44. Thus, he concludes, for practical
  122. * purposes *one* Fermat test to the base 2 is sufficient.
  123. */
  124. static int
  125. primeTest(struct BigNum const *bn, struct BigNum *e, struct BigNum *a,
  126. int (*f)(void *arg, int c), void *arg)
  127. {
  128. unsigned i, j;
  129. unsigned k, l;
  130. int err;
  131. #if BNDEBUG /* Debugging */
  132. /*
  133. * This is debugging code to test the sieving stage.
  134. * If the sieving is wrong, it will let past numbers with
  135. * small divisors. The prime test here will still work, and
  136. * weed them out, but you'll be doing a lot more slow tests,
  137. * and presumably excluding from consideration some other numbers
  138. * which might be prime. This check just verifies that none
  139. * of the candidates have any small divisors. If this
  140. * code is enabled and never triggers, you can feel quite
  141. * confident that the sieving is doing its job.
  142. */
  143. i = bnLSWord(bn);
  144. if (!(i % 2)) printf("bn div by 2!");
  145. i = bnModQ(bn, 51051); /* 51051 = 3 * 7 * 11 * 13 * 17 */
  146. if (!(i % 3)) printf("bn div by 3!");
  147. if (!(i % 7)) printf("bn div by 7!");
  148. if (!(i % 11)) printf("bn div by 11!");
  149. if (!(i % 13)) printf("bn div by 13!");
  150. if (!(i % 17)) printf("bn div by 17!");
  151. i = bnModQ(bn, 63365); /* 63365 = 5 * 19 * 23 * 29 */
  152. if (!(i % 5)) printf("bn div by 5!");
  153. if (!(i % 19)) printf("bn div by 19!");
  154. if (!(i % 23)) printf("bn div by 23!");
  155. if (!(i % 29)) printf("bn div by 29!");
  156. i = bnModQ(bn, 47027); /* 47027 = 31 * 37 * 41 */
  157. if (!(i % 31)) printf("bn div by 31!");
  158. if (!(i % 37)) printf("bn div by 37!");
  159. if (!(i % 41)) printf("bn div by 41!");
  160. #endif
  161. /*
  162. * Now, check that bn is prime. If it passes to the base 2,
  163. * it's prime beyond all reasonable doubt, and everything else
  164. * is just gravy, but it gives people warm fuzzies to do it.
  165. *
  166. * This starts with verifying Euler's criterion for a base of 2.
  167. * This is the fastest pseudoprimality test that I know of,
  168. * saving a modular squaring over a Fermat test, as well as
  169. * being stronger. 7/8 of the time, it's as strong as a strong
  170. * pseudoprimality test, too. (The exception being when bn ==
  171. * 1 mod 8 and 2 is a quartic residue, i.e. bn is of the form
  172. * a^2 + (8*b)^2.) The precise series of tricks used here is
  173. * not documented anywhere, so here's an explanation.
  174. * Euler's criterion states that if p is prime then a^((p-1)/2)
  175. * is congruent to Jacobi(a,p), modulo p. Jacobi(a,p) is
  176. * a function which is +1 if a is a square modulo p, and -1 if
  177. * it is not. For a = 2, this is particularly simple. It's
  178. * +1 if p == +/-1 (mod 8), and -1 if m == +/-3 (mod 8).
  179. * If p == 3 mod 4, then all a strong test does is compute
  180. * 2^((p-1)/2). and see if it's +1 or -1. (Euler's criterion
  181. * says *which* it should be.) If p == 5 (mod 8), then
  182. * 2^((p-1)/2) is -1, so the initial step in a strong test,
  183. * looking at 2^((p-1)/4), is wasted - you're not going to
  184. * find a +/-1 before then if it *is* prime, and it shouldn't
  185. * have either of those values if it isn't. So don't bother.
  186. *
  187. * The remaining case is p == 1 (mod 8). In this case, we
  188. * expect 2^((p-1)/2) == 1 (mod p), so we expect that the
  189. * square root of this, 2^((p-1)/4), will be +/-1 (mod p).
  190. * Evaluating this saves us a modular squaring 1/4 of the time.
  191. * If it's -1, a strong pseudoprimality test would call p
  192. * prime as well. Only if the result is +1, indicating that
  193. * 2 is not only a quadratic residue, but a quartic one as well,
  194. * does a strong pseudoprimality test verify more things than
  195. * this test does. Good enough.
  196. *
  197. * We could back that down another step, looking at 2^((p-1)/8)
  198. * if there was a cheap way to determine if 2 were expected to
  199. * be a quartic residue or not. Dirichlet proved that 2 is
  200. * a quartic residue iff p is of the form a^2 + (8*b^2).
  201. * All primes == 1 (mod 4) can be expressed as a^2 + (2*b)^2,
  202. * but I see no cheap way to evaluate this condition.
  203. */
  204. if (bnCopy(e, bn) < 0)
  205. return -1;
  206. (void)bnSubQ(e, 1);
  207. l = bnLSWord(e);
  208. j = 1; /* Where to start in prime array for strong prime tests */
  209. if (l & 7) {
  210. bnRShift(e, 1);
  211. if (bnTwoExpMod(a, e, bn) < 0)
  212. return -1;
  213. if ((l & 7) == 6) {
  214. /* bn == 7 mod 8, expect +1 */
  215. if (bnBits(a) != 1)
  216. return 1; /* Not prime */
  217. k = 1;
  218. } else {
  219. /* bn == 3 or 5 mod 8, expect -1 == bn-1 */
  220. if (bnAddQ(a, 1) < 0)
  221. return -1;
  222. if (bnCmp(a, bn) != 0)
  223. return 1; /* Not prime */
  224. k = 1;
  225. if (l & 4) {
  226. /* bn == 5 mod 8, make odd for strong tests */
  227. bnRShift(e, 1);
  228. k = 2;
  229. }
  230. }
  231. } else {
  232. /* bn == 1 mod 8, expect 2^((bn-1)/4) == +/-1 mod bn */
  233. bnRShift(e, 2);
  234. if (bnTwoExpMod(a, e, bn) < 0)
  235. return -1;
  236. if (bnBits(a) == 1) {
  237. j = 0; /* Re-do strong prime test to base 2 */
  238. } else {
  239. if (bnAddQ(a, 1) < 0)
  240. return -1;
  241. if (bnCmp(a, bn) != 0)
  242. return 1; /* Not prime */
  243. }
  244. k = 2 + bnMakeOdd(e);
  245. }
  246. /* It's prime! Now go on to confirmation tests */
  247. /*
  248. * Now, e = (bn-1)/2^k is odd. k >= 1, and has a given value
  249. * with probability 2^-k, so its expected value is 2.
  250. * j = 1 in the usual case when the previous test was as good as
  251. * a strong prime test, but 1/8 of the time, j = 0 because
  252. * the strong prime test to the base 2 needs to be re-done.
  253. */
  254. for (i = j; i < CONFIRMTESTS; i++) {
  255. if (f && (err = f(arg, '*')) < 0)
  256. return err;
  257. (void)bnSetQ(a, confirm[i]);
  258. if (bnExpMod(a, a, e, bn) < 0)
  259. return -1;
  260. if (bnBits(a) == 1)
  261. continue; /* Passed this test */
  262. l = k;
  263. for (;;) {
  264. if (bnAddQ(a, 1) < 0)
  265. return -1;
  266. if (bnCmp(a, bn) == 0) /* Was result bn-1? */
  267. break; /* Prime */
  268. if (!--l) /* Reached end, not -1? luck? */
  269. return i+2-j; /* Failed, not prime */
  270. /* This portion is executed, on average, once. */
  271. (void)bnSubQ(a, 1); /* Put a back where it was. */
  272. if (bnSquare(a, a) < 0 || bnMod(a, a, bn) < 0)
  273. return -1;
  274. if (bnBits(a) == 1)
  275. return i+2-j; /* Failed, not prime */
  276. }
  277. /* It worked (to the base confirm[i]) */
  278. }
  279. /* Yes, we've decided that it's prime. */
  280. if (f && (err = f(arg, '*')) < 0)
  281. return err;
  282. return 0; /* Prime! */
  283. }
  284. /*
  285. * Add x*y to bn, which is usually (but not always) < 65536.
  286. * Do it in a simple linear manner.
  287. */
  288. static int
  289. bnAddMult(struct BigNum *bn, unsigned x, unsigned y)
  290. {
  291. unsigned long z = (unsigned long)x * y;
  292. while (z > 65535) {
  293. if (bnAddQ(bn, 65535) < 0)
  294. return -1;
  295. z -= 65535;
  296. }
  297. return bnAddQ(bn, (unsigned)z);
  298. }
  299. static int
  300. bnSubMult(struct BigNum *bn, unsigned x, unsigned y)
  301. {
  302. unsigned long z = (unsigned long)x * y;
  303. while (z > 65535) {
  304. if (bnSubQ(bn, 65535) < 0)
  305. return -1;
  306. z -= 65535;
  307. }
  308. return bnSubQ(bn, (unsigned)z);
  309. }
  310. /*
  311. * Modifies the bignum to return a nearby (slightly larger) number which
  312. * is a probable prime. Returns >=0 on success or -1 on failure (out of
  313. * memory). The return value is the number of unsuccessful modular
  314. * exponentiations performed. This never gives up searching.
  315. *
  316. * All other arguments are optional. They may be NULL. They are:
  317. *
  318. * unsigned (*rand)(unsigned limit)
  319. * For better distributed numbers, supply a non-null pointer to a
  320. * function which returns a random x, 0 <= x < limit. (It may make it
  321. * simpler to know that 0 < limit <= SHUFFLE, so you need at most a byte.)
  322. * The program generates a large window of sieve data and then does
  323. * pseudoprimality tests on the data. If a rand function is supplied,
  324. * the candidates which survive sieving are shuffled with a window of
  325. * size SHUFFLE before testing to increase the uniformity of the prime
  326. * selection. This isn't perfect, but it reduces the correlation between
  327. * the size of the prime-free gap before a prime and the probability
  328. * that that prime will be found by a sequential search.
  329. *
  330. * If rand is NULL, sequential search is used. If you want sequential
  331. * search, note that the search begins with the given number; if you're
  332. * trying to generate consecutive primes, you must increment the previous
  333. * one by two before calling this again.
  334. *
  335. * int (*f)(void *arg, int c), void *arg
  336. * The function f argument, if non-NULL, is called with progress indicator
  337. * characters for printing. A dot (.) is written every time a primality test
  338. * is failed, a star (*) every time one is passed, and a slash (/) in the
  339. * (very rare) case that the sieve was emptied without finding a prime
  340. * and is being refilled. f is also passed the void *arg argument for
  341. * private context storage. If f returns < 0, the test aborts and returns
  342. * that value immediately. (bn is set to the last value tested, so you
  343. * can increment bn and continue.)
  344. *
  345. * The "exponent" argument, and following unsigned numbers, are exponents
  346. * for which an inverse is desired, modulo p. For a d to exist such that
  347. * (x^e)^d == x (mod p), then d*e == 1 (mod p-1), so gcd(e,p-1) must be 1.
  348. * The prime returned is constrained to not be congruent to 1 modulo
  349. * any of the zero-terminated list of 16-bit numbers. Note that this list
  350. * should contain all the small prime factors of e. (You'll have to test
  351. * for large prime factors of e elsewhere, but the chances of needing to
  352. * generate another prime are low.)
  353. *
  354. * The list is terminated by a 0, and may be empty.
  355. */
  356. int
  357. primeGen(struct BigNum *bn, unsigned (*rand)(unsigned),
  358. int (*f)(void *arg, int c), void *arg, unsigned exponent, ...)
  359. {
  360. int retval;
  361. int modexps = 0;
  362. unsigned short offsets[SHUFFLE];
  363. unsigned i, j;
  364. unsigned p, q, prev;
  365. struct BigNum a, e;
  366. #ifdef MSDOS
  367. unsigned char *sieve;
  368. #else
  369. unsigned char sieve[SIEVE];
  370. #endif
  371. #ifdef MSDOS
  372. sieve = lbnMemAlloc(SIEVE);
  373. if (!sieve)
  374. return -1;
  375. #endif
  376. bnBegin(&a);
  377. bnBegin(&e);
  378. #if 0 /* Self-test (not used for production) */
  379. {
  380. struct BigNum t;
  381. static unsigned char const prime1[] = {5};
  382. static unsigned char const prime2[] = {7};
  383. static unsigned char const prime3[] = {11};
  384. static unsigned char const prime4[] = {1, 1}; /* 257 */
  385. static unsigned char const prime5[] = {0xFF, 0xF1}; /* 65521 */
  386. static unsigned char const prime6[] = {1, 0, 1}; /* 65537 */
  387. static unsigned char const prime7[] = {1, 0, 3}; /* 65539 */
  388. /* A small prime: 1234567891 */
  389. static unsigned char const prime8[] = {0x49, 0x96, 0x02, 0xD3};
  390. /* A slightly larger prime: 12345678901234567891 */
  391. static unsigned char const prime9[] = {
  392. 0xAB, 0x54, 0xA9, 0x8C, 0xEB, 0x1F, 0x0A, 0xD3 };
  393. /*
  394. * No, 123456789012345678901234567891 isn't prime; it's just a
  395. * lucky, easy-to-remember conicidence. (You have to go to
  396. * ...4567907 for a prime.)
  397. */
  398. static struct {
  399. unsigned char const *prime;
  400. unsigned size;
  401. } const primelist[] = {
  402. { prime1, sizeof(prime1) },
  403. { prime2, sizeof(prime2) },
  404. { prime3, sizeof(prime3) },
  405. { prime4, sizeof(prime4) },
  406. { prime5, sizeof(prime5) },
  407. { prime6, sizeof(prime6) },
  408. { prime7, sizeof(prime7) },
  409. { prime8, sizeof(prime8) },
  410. { prime9, sizeof(prime9) } };
  411. bnBegin(&t);
  412. for (i = 0; i < sizeof(primelist)/sizeof(primelist[0]); i++) {
  413. bnInsertBytes(&t, primelist[i].prime, 0,
  414. primelist[i].size);
  415. bnCopy(&e, &t);
  416. (void)bnSubQ(&e, 1);
  417. bnTwoExpMod(&a, &e, &t);
  418. p = bnBits(&a);
  419. if (p != 1) {
  420. printf(
  421. "Bug: Fermat(2) %u-bit output (1 expected)\n", p);
  422. fputs("Prime = 0x", stdout);
  423. for (j = 0; j < primelist[i].size; j++)
  424. printf("%02X", primelist[i].prime[j]);
  425. putchar('\n');
  426. }
  427. bnSetQ(&a, 3);
  428. bnExpMod(&a, &a, &e, &t);
  429. p = bnBits(&a);
  430. if (p != 1) {
  431. printf(
  432. "Bug: Fermat(3) %u-bit output (1 expected)\n", p);
  433. fputs("Prime = 0x", stdout);
  434. for (j = 0; j < primelist[i].size; j++)
  435. printf("%02X", primelist[i].prime[j]);
  436. putchar('\n');
  437. }
  438. }
  439. bnEnd(&t);
  440. }
  441. #endif
  442. /* First, make sure that bn is odd. */
  443. if ((bnLSWord(bn) & 1) == 0)
  444. (void)bnAddQ(bn, 1);
  445. retry:
  446. /* Then build a sieve starting at bn. */
  447. sieveBuild(sieve, SIEVE, bn, 2, 0);
  448. /* Do the extra exponent sieving */
  449. if (exponent) {
  450. va_list ap;
  451. unsigned t = exponent;
  452. va_start(ap, exponent);
  453. do {
  454. /* The exponent had better be odd! */
  455. assert(t & 1);
  456. i = bnModQ(bn, t);
  457. /* Find 1-i */
  458. if (i == 0)
  459. i = 1;
  460. else if (--i)
  461. i = t - i;
  462. /* Divide by 2, modulo the exponent */
  463. i = (i & 1) ? i/2 + t/2 + 1 : i/2;
  464. /* Remove all following multiples from the sieve. */
  465. sieveSingle(sieve, SIEVE, i, t);
  466. /* Get the next exponent value */
  467. t = va_arg(ap, unsigned);
  468. } while (t);
  469. va_end(ap);
  470. }
  471. /* Fill up the offsets array with the first SHUFFLE candidates */
  472. i = p = 0;
  473. /* Get first prime */
  474. if (sieve[0] & 1 || (p = sieveSearch(sieve, SIEVE, p)) != 0) {
  475. offsets[i++] = p;
  476. p = sieveSearch(sieve, SIEVE, p);
  477. }
  478. /*
  479. * Okay, from this point onwards, p is always the next entry
  480. * from the sieve, that has not been added to the shuffle table,
  481. * and is 0 iff the sieve has been exhausted.
  482. *
  483. * If we want to shuffle, then fill the shuffle table until the
  484. * sieve is exhausted or the table is full.
  485. */
  486. if (rand && p) {
  487. do {
  488. offsets[i++] = p;
  489. p = sieveSearch(sieve, SIEVE, p);
  490. } while (p && i < SHUFFLE);
  491. }
  492. /* Choose a random candidate for experimentation */
  493. prev = 0;
  494. while (i) {
  495. /* Pick a random entry from the shuffle table */
  496. j = rand ? rand(i) : 0;
  497. q = offsets[j]; /* The entry to use */
  498. /* Replace the entry with some more data, if possible */
  499. if (p) {
  500. offsets[j] = p;
  501. p = sieveSearch(sieve, SIEVE, p);
  502. } else {
  503. offsets[j] = offsets[--i];
  504. offsets[i] = 0;
  505. }
  506. /* Adjust bn to have the right value */
  507. if ((q > prev ? bnAddMult(bn, q-prev, 2)
  508. : bnSubMult(bn, prev-q, 2)) < 0)
  509. goto failed;
  510. prev = q;
  511. /* Now do the Fermat tests */
  512. retval = primeTest(bn, &e, &a, f, arg);
  513. if (retval <= 0)
  514. goto done; /* Success or error */
  515. modexps += retval;
  516. if (f && (retval = f(arg, '.')) < 0)
  517. goto done;
  518. }
  519. /* Ran out of sieve space - increase bn and keep trying. */
  520. if (bnAddMult(bn, SIEVE*8-prev, 2) < 0)
  521. goto failed;
  522. if (f && (retval = f(arg, '/')) < 0)
  523. goto done;
  524. goto retry;
  525. failed:
  526. retval = -1;
  527. done:
  528. bnEnd(&e);
  529. bnEnd(&a);
  530. lbnMemWipe(offsets, sizeof(offsets));
  531. #ifdef MSDOS
  532. lbnMemFree(sieve, SIEVE);
  533. #else
  534. lbnMemWipe(sieve, sizeof(sieve));
  535. #endif
  536. return retval < 0 ? retval : modexps + CONFIRMTESTS;
  537. }
  538. /*
  539. * Similar, but searches forward from the given starting value in steps of
  540. * "step" rather than 1. The step size must be even, and bn must be odd.
  541. * Among other possibilities, this can be used to generate "strong"
  542. * primes, where p-1 has a large prime factor.
  543. */
  544. int
  545. primeGenStrong(struct BigNum *bn, struct BigNum const *step,
  546. int (*f)(void *arg, int c), void *arg)
  547. {
  548. int retval;
  549. unsigned p, prev;
  550. struct BigNum a, e;
  551. int modexps = 0;
  552. #ifdef MSDOS
  553. unsigned char *sieve;
  554. #else
  555. unsigned char sieve[SIEVE];
  556. #endif
  557. #ifdef MSDOS
  558. sieve = lbnMemAlloc(SIEVE);
  559. if (!sieve)
  560. return -1;
  561. #endif
  562. /* Step must be even and bn must be odd */
  563. assert((bnLSWord(step) & 1) == 0);
  564. assert((bnLSWord(bn) & 1) == 1);
  565. bnBegin(&a);
  566. bnBegin(&e);
  567. for (;;) {
  568. if (sieveBuildBig(sieve, SIEVE, bn, step, 0) < 0)
  569. goto failed;
  570. p = prev = 0;
  571. if (sieve[0] & 1 || (p = sieveSearch(sieve, SIEVE, p)) != 0) {
  572. do {
  573. /*
  574. * Adjust bn to have the right value,
  575. * adding (p-prev) * 2*step.
  576. */
  577. assert(p >= prev);
  578. /* Compute delta into a */
  579. if (bnMulQ(&a, step, p-prev) < 0)
  580. goto failed;
  581. if (bnAdd(bn, &a) < 0)
  582. goto failed;
  583. prev = p;
  584. retval = primeTest(bn, &e, &a, f, arg);
  585. if (retval <= 0)
  586. goto done; /* Success! */
  587. modexps += retval;
  588. if (f && (retval = f(arg, '.')) < 0)
  589. goto done;
  590. /* And try again */
  591. p = sieveSearch(sieve, SIEVE, p);
  592. } while (p);
  593. }
  594. /* Ran out of sieve space - increase bn and keep trying. */
  595. #if SIEVE*8 == 65536
  596. /* Corner case that will never actually happen */
  597. if (!prev) {
  598. if (bnAdd(bn, step) < 0)
  599. goto failed;
  600. p = 65535;
  601. } else {
  602. p = (unsigned)(SIEVE*8 - prev);
  603. }
  604. #else
  605. p = SIEVE*8 - prev;
  606. #endif
  607. if (bnMulQ(&a, step, p) < 0 || bnAdd(bn, &a) < 0)
  608. goto failed;
  609. if (f && (retval = f(arg, '/')) < 0)
  610. goto done;
  611. } /* for (;;) */
  612. failed:
  613. retval = -1;
  614. done:
  615. bnEnd(&e);
  616. bnEnd(&a);
  617. #ifdef MSDOS
  618. lbnMemFree(sieve, SIEVE);
  619. #else
  620. lbnMemWipe(sieve, sizeof(sieve));
  621. #endif
  622. return retval < 0 ? retval : modexps + CONFIRMTESTS;
  623. }