prime.c
上传用户:zbbssh
上传日期:2007-01-08
资源大小:196k
文件大小:20k
源码类别:

CA认证

开发平台:

C/C++

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