1 /* $OpenBSD: moduli.c,v 1.3 2003/12/07 06:34:18 djm Exp $ */
3 * Copyright 1994 Phil Karn <karn@qualcomm.com>
4 * Copyright 1996-1998, 2003 William Allen Simpson <wsimpson@greendragon.com>
5 * Copyright 2000 Niels Provos <provos@citi.umich.edu>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * Two-step process to generate safe primes for DHGEX
32 * Sieve candidates for "safe" primes,
33 * suitable for use as Diffie-Hellman moduli;
34 * that is, where q = (p-1)/2 is also prime.
36 * First step: generate candidate primes (memory intensive)
37 * Second step: test primes' safety (processor intensive)
45 #include <openssl/bn.h>
51 /* need line long enough for largest moduli plus headers */
52 #define QLINESIZE (100+8192)
55 * Specifies the internal structure of the prime modulus.
57 #define QTYPE_UNKNOWN (0)
58 #define QTYPE_UNSTRUCTURED (1)
59 #define QTYPE_SAFE (2)
60 #define QTYPE_SCHNOOR (3)
61 #define QTYPE_SOPHIE_GERMAINE (4)
62 #define QTYPE_STRONG (5)
64 /* Tests: decimal (bit field).
65 * Specifies the methods used in checking for primality.
66 * Usually, more than one test is used.
68 #define QTEST_UNTESTED (0x00)
69 #define QTEST_COMPOSITE (0x01)
70 #define QTEST_SIEVE (0x02)
71 #define QTEST_MILLER_RABIN (0x04)
72 #define QTEST_JACOBI (0x08)
73 #define QTEST_ELLIPTIC (0x10)
76 * Specifies the number of the most significant bit (0 to M).
77 ** WARNING: internally, usually 1 to N.
79 #define QSIZE_MINIMUM (511)
82 * Prime sieving defines
85 /* Constant: assuming 8 bit bytes and 32 bit words */
87 #define SHIFT_BYTE (2)
88 #define SHIFT_WORD (SHIFT_BIT+SHIFT_BYTE)
89 #define SHIFT_MEGABYTE (20)
90 #define SHIFT_MEGAWORD (SHIFT_MEGABYTE-SHIFT_BYTE)
93 * Constant: when used with 32-bit integers, the largest sieve prime
94 * has to be less than 2**32.
96 #define SMALL_MAXIMUM (0xffffffffUL)
98 /* Constant: can sieve all primes less than 2**32, as 65537**2 > 2**32-1. */
99 #define TINY_NUMBER (1UL<<16)
101 /* Ensure enough bit space for testing 2*q. */
102 #define TEST_MAXIMUM (1UL<<16)
103 #define TEST_MINIMUM (QSIZE_MINIMUM + 1)
104 /* real TEST_MINIMUM (1UL << (SHIFT_WORD - TEST_POWER)) */
105 #define TEST_POWER (3) /* 2**n, n < SHIFT_WORD */
107 /* bit operations on 32-bit words */
108 #define BIT_CLEAR(a,n) ((a)[(n)>>SHIFT_WORD] &= ~(1L << ((n) & 31)))
109 #define BIT_SET(a,n) ((a)[(n)>>SHIFT_WORD] |= (1L << ((n) & 31)))
110 #define BIT_TEST(a,n) ((a)[(n)>>SHIFT_WORD] & (1L << ((n) & 31)))
113 * Prime testing defines
117 * Sieving data (XXX - move to struct)
121 static u_int32_t *TinySieve, tinybits;
123 /* sieve 2**30 in 2**16 parts */
124 static u_int32_t *SmallSieve, smallbits, smallbase;
126 /* sieve relative to the initial value */
127 static u_int32_t *LargeSieve, largewords, largetries, largenumbers;
128 static u_int32_t largebits, largememory; /* megabytes */
129 static BIGNUM *largebase;
133 * print moduli out in consistent form,
136 qfileout(FILE * ofile, u_int32_t otype, u_int32_t otests, u_int32_t otries,
137 u_int32_t osize, u_int32_t ogenerator, BIGNUM * omodulus)
144 gtm = gmtime(&time_now);
146 res = fprintf(ofile, "%04d%02d%02d%02d%02d%02d %u %u %u %u %x ",
147 gtm->tm_year + 1900, gtm->tm_mon + 1, gtm->tm_mday,
148 gtm->tm_hour, gtm->tm_min, gtm->tm_sec,
149 otype, otests, otries, osize, ogenerator);
154 if (BN_print_fp(ofile, omodulus) < 1)
157 res = fprintf(ofile, "\n");
160 return (res > 0 ? 0 : -1);
165 ** Sieve p's and q's with small factors
168 sieve_large(u_int32_t s)
172 debug2("sieve_large %u", s);
174 /* r = largebase mod s */
175 r = BN_mod_word(largebase, s);
177 u = 0; /* s divides into largebase exactly */
179 u = s - r; /* largebase+u is first entry divisible by s */
181 if (u < largebits * 2) {
183 * The sieve omits p's and q's divisible by 2, so ensure that
184 * largebase+u is odd. Then, step through the sieve in
188 u += s; /* Make largebase+u odd, and u even */
190 /* Mark all multiples of 2*s */
191 for (u /= 2; u < largebits; u += s)
192 BIT_SET(LargeSieve, u);
198 u = 0; /* s divides p exactly */
200 u = s - r; /* p+u is first entry divisible by s */
202 if (u < largebits * 4) {
204 * The sieve omits p's divisible by 4, so ensure that
205 * largebase+u is not. Then, step through the sieve in
209 if (SMALL_MAXIMUM - u < s)
214 /* Mark all multiples of 4*s */
215 for (u /= 4; u < largebits; u += s)
216 BIT_SET(LargeSieve, u);
221 * list candidates for Sophie-Germaine primes (where q = (p-1)/2)
222 * to standard output.
223 * The list is checked against small known primes (less than 2**30).
226 gen_candidates(FILE *out, int memory, int power, BIGNUM *start)
229 u_int32_t j, r, s, t;
230 u_int32_t smallwords = TINY_NUMBER >> 6;
231 u_int32_t tinywords = TINY_NUMBER >> 6;
232 time_t time_start, time_stop;
235 largememory = memory;
238 * Set power to the length in bits of the prime to be generated.
239 * This is changed to 1 less than the desired safe prime moduli p.
241 if (power > TEST_MAXIMUM) {
242 error("Too many bits: %u > %lu", power, TEST_MAXIMUM);
244 } else if (power < TEST_MINIMUM) {
245 error("Too few bits: %u < %u", power, TEST_MINIMUM);
248 power--; /* decrement before squaring */
251 * The density of ordinary primes is on the order of 1/bits, so the
252 * density of safe primes should be about (1/bits)**2. Set test range
253 * to something well above bits**2 to be reasonably sure (but not
254 * guaranteed) of catching at least one safe prime.
256 largewords = ((power * power) >> (SHIFT_WORD - TEST_POWER));
259 * Need idea of how much memory is available. We don't have to use all
262 if (largememory > LARGE_MAXIMUM) {
263 logit("Limited memory: %u MB; limit %lu MB",
264 largememory, LARGE_MAXIMUM);
265 largememory = LARGE_MAXIMUM;
268 if (largewords <= (largememory << SHIFT_MEGAWORD)) {
269 logit("Increased memory: %u MB; need %u bytes",
270 largememory, (largewords << SHIFT_BYTE));
271 largewords = (largememory << SHIFT_MEGAWORD);
272 } else if (largememory > 0) {
273 logit("Decreased memory: %u MB; want %u bytes",
274 largememory, (largewords << SHIFT_BYTE));
275 largewords = (largememory << SHIFT_MEGAWORD);
278 TinySieve = calloc(tinywords, sizeof(u_int32_t));
279 if (TinySieve == NULL) {
280 error("Insufficient memory for tiny sieve: need %u bytes",
281 tinywords << SHIFT_BYTE);
284 tinybits = tinywords << SHIFT_WORD;
286 SmallSieve = calloc(smallwords, sizeof(u_int32_t));
287 if (SmallSieve == NULL) {
288 error("Insufficient memory for small sieve: need %u bytes",
289 smallwords << SHIFT_BYTE);
293 smallbits = smallwords << SHIFT_WORD;
296 * dynamically determine available memory
298 while ((LargeSieve = calloc(largewords, sizeof(u_int32_t))) == NULL)
299 largewords -= (1L << (SHIFT_MEGAWORD - 2)); /* 1/4 MB chunks */
301 largebits = largewords << SHIFT_WORD;
302 largenumbers = largebits * 2; /* even numbers excluded */
304 /* validation check: count the number of primes tried */
309 * Generate random starting point for subprime search, or use
310 * specified parameter.
312 largebase = BN_new();
314 BN_rand(largebase, power, 1, 1);
316 BN_copy(largebase, start);
319 BN_set_bit(largebase, 0);
323 logit("%.24s Sieve next %u plus %u-bit", ctime(&time_start),
324 largenumbers, power);
325 debug2("start point: 0x%s", BN_bn2hex(largebase));
330 for (i = 0; i < tinybits; i++) {
331 if (BIT_TEST(TinySieve, i))
332 continue; /* 2*i+3 is composite */
334 /* The next tiny prime */
337 /* Mark all multiples of t */
338 for (j = i + t; j < tinybits; j += t)
339 BIT_SET(TinySieve, j);
345 * Start the small block search at the next possible prime. To avoid
346 * fencepost errors, the last pass is skipped.
348 for (smallbase = TINY_NUMBER + 3;
349 smallbase < (SMALL_MAXIMUM - TINY_NUMBER);
350 smallbase += TINY_NUMBER) {
351 for (i = 0; i < tinybits; i++) {
352 if (BIT_TEST(TinySieve, i))
353 continue; /* 2*i+3 is composite */
355 /* The next tiny prime */
360 s = 0; /* t divides into smallbase exactly */
362 /* smallbase+s is first entry divisible by t */
367 * The sieve omits even numbers, so ensure that
368 * smallbase+s is odd. Then, step through the sieve
369 * in increments of 2*t
372 s += t; /* Make smallbase+s odd, and s even */
374 /* Mark all multiples of 2*t */
375 for (s /= 2; s < smallbits; s += t)
376 BIT_SET(SmallSieve, s);
382 for (i = 0; i < smallbits; i++) {
383 if (BIT_TEST(SmallSieve, i))
384 continue; /* 2*i+smallbase is composite */
386 /* The next small prime */
387 sieve_large((2 * i) + smallbase);
390 memset(SmallSieve, 0, smallwords << SHIFT_BYTE);
395 logit("%.24s Sieved with %u small primes in %ld seconds",
396 ctime(&time_stop), largetries, (long) (time_stop - time_start));
398 for (j = r = 0; j < largebits; j++) {
399 if (BIT_TEST(LargeSieve, j))
400 continue; /* Definitely composite, skip */
402 debug2("test q = largebase+%u", 2 * j);
403 BN_set_word(q, 2 * j);
404 BN_add(q, q, largebase);
405 if (qfileout(out, QTYPE_SOPHIE_GERMAINE, QTEST_SIEVE,
406 largetries, (power - 1) /* MSB */, (0), q) == -1) {
420 logit("%.24s Found %u candidates", ctime(&time_stop), r);
426 * perform a Miller-Rabin primality test
427 * on the list of candidates
428 * (checking both q and p)
429 * The result is a list of so-call "safe" primes
432 prime_test(FILE *in, FILE *out, u_int32_t trials,
433 u_int32_t generator_wanted)
438 u_int32_t count_in = 0, count_out = 0, count_possible = 0;
439 u_int32_t generator_known, in_tests, in_tries, in_type, in_size;
440 time_t time_start, time_stop;
449 debug2("%.24s Final %u Miller-Rabin trials (%x generator)",
450 ctime(&time_start), trials, generator_wanted);
453 lp = xmalloc(QLINESIZE + 1);
454 while (fgets(lp, QLINESIZE, in) != NULL) {
458 if (ll < 14 || *lp == '!' || *lp == '#') {
459 debug2("%10u: comment or short line", count_in);
463 /* XXX - fragile parser */
465 cp = &lp[14]; /* (skip) */
468 in_type = strtoul(cp, &cp, 10);
471 in_tests = strtoul(cp, &cp, 10);
473 if (in_tests & QTEST_COMPOSITE) {
474 debug2("%10u: known composite", count_in);
478 in_tries = strtoul(cp, &cp, 10);
480 /* size (most significant bit) */
481 in_size = strtoul(cp, &cp, 10);
483 /* generator (hex) */
484 generator_known = strtoul(cp, &cp, 16);
486 /* Skip white space */
487 cp += strspn(cp, " ");
491 case QTYPE_SOPHIE_GERMAINE:
492 debug2("%10u: (%u) Sophie-Germaine", count_in, in_type);
502 debug2("%10u: (%u)", count_in, in_type);
511 * due to earlier inconsistencies in interpretation, check
512 * the proposed bit size.
514 if (BN_num_bits(p) != (in_size + 1)) {
515 debug2("%10u: bit size %u mismatch", count_in, in_size);
518 if (in_size < QSIZE_MINIMUM) {
519 debug2("%10u: bit size %u too short", count_in, in_size);
523 if (in_tests & QTEST_MILLER_RABIN)
528 * guess unknown generator
530 if (generator_known == 0) {
531 if (BN_mod_word(p, 24) == 11)
533 else if (BN_mod_word(p, 12) == 5)
536 u_int32_t r = BN_mod_word(p, 10);
538 if (r == 3 || r == 7) {
544 * skip tests when desired generator doesn't match
546 if (generator_wanted > 0 &&
547 generator_wanted != generator_known) {
548 debug2("%10u: generator %d != %d",
549 count_in, generator_known, generator_wanted);
556 * The (1/4)^N performance bound on Miller-Rabin is
557 * extremely pessimistic, so don't spend a lot of time
558 * really verifying that q is prime until after we know
559 * that p is also prime. A single pass will weed out the
560 * vast majority of composite q's.
562 if (BN_is_prime(q, 1, NULL, ctx, NULL) <= 0) {
563 debug2("%10u: q failed first possible prime test",
569 * q is possibly prime, so go ahead and really make sure
570 * that p is prime. If it is, then we can go back and do
571 * the same for q. If p is composite, chances are that
572 * will show up on the first Rabin-Miller iteration so it
573 * doesn't hurt to specify a high iteration count.
575 if (!BN_is_prime(p, trials, NULL, ctx, NULL)) {
576 debug2("%10u: p is not prime", count_in);
579 debug("%10u: p is almost certainly prime", count_in);
581 /* recheck q more rigorously */
582 if (!BN_is_prime(q, trials - 1, NULL, ctx, NULL)) {
583 debug("%10u: q is not prime", count_in);
586 debug("%10u: q is almost certainly prime", count_in);
588 if (qfileout(out, QTYPE_SAFE, (in_tests | QTEST_MILLER_RABIN),
589 in_tries, in_size, generator_known, p)) {
603 logit("%.24s Found %u safe primes of %u candidates in %ld seconds",
604 ctime(&time_stop), count_out, count_possible,
605 (long) (time_stop - time_start));