1 /* $OpenBSD: moduli.c,v 1.5 2003/12/22 09:16:57 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)
77 * Specifies the number of the most significant bit (0 to M).
78 * WARNING: internally, usually 1 to N.
80 #define QSIZE_MINIMUM (511)
83 * Prime sieving defines
86 /* Constant: assuming 8 bit bytes and 32 bit words */
88 #define SHIFT_BYTE (2)
89 #define SHIFT_WORD (SHIFT_BIT+SHIFT_BYTE)
90 #define SHIFT_MEGABYTE (20)
91 #define SHIFT_MEGAWORD (SHIFT_MEGABYTE-SHIFT_BYTE)
94 * Constant: when used with 32-bit integers, the largest sieve prime
95 * has to be less than 2**32.
97 #define SMALL_MAXIMUM (0xffffffffUL)
99 /* Constant: can sieve all primes less than 2**32, as 65537**2 > 2**32-1. */
100 #define TINY_NUMBER (1UL<<16)
102 /* Ensure enough bit space for testing 2*q. */
103 #define TEST_MAXIMUM (1UL<<16)
104 #define TEST_MINIMUM (QSIZE_MINIMUM + 1)
105 /* real TEST_MINIMUM (1UL << (SHIFT_WORD - TEST_POWER)) */
106 #define TEST_POWER (3) /* 2**n, n < SHIFT_WORD */
108 /* bit operations on 32-bit words */
109 #define BIT_CLEAR(a,n) ((a)[(n)>>SHIFT_WORD] &= ~(1L << ((n) & 31)))
110 #define BIT_SET(a,n) ((a)[(n)>>SHIFT_WORD] |= (1L << ((n) & 31)))
111 #define BIT_TEST(a,n) ((a)[(n)>>SHIFT_WORD] & (1L << ((n) & 31)))
114 * Prime testing defines
118 * Sieving data (XXX - move to struct)
122 static u_int32_t *TinySieve, tinybits;
124 /* sieve 2**30 in 2**16 parts */
125 static u_int32_t *SmallSieve, smallbits, smallbase;
127 /* sieve relative to the initial value */
128 static u_int32_t *LargeSieve, largewords, largetries, largenumbers;
129 static u_int32_t largebits, largememory; /* megabytes */
130 static BIGNUM *largebase;
134 * print moduli out in consistent form,
137 qfileout(FILE * ofile, u_int32_t otype, u_int32_t otests, u_int32_t otries,
138 u_int32_t osize, u_int32_t ogenerator, BIGNUM * omodulus)
145 gtm = gmtime(&time_now);
147 res = fprintf(ofile, "%04d%02d%02d%02d%02d%02d %u %u %u %u %x ",
148 gtm->tm_year + 1900, gtm->tm_mon + 1, gtm->tm_mday,
149 gtm->tm_hour, gtm->tm_min, gtm->tm_sec,
150 otype, otests, otries, osize, ogenerator);
155 if (BN_print_fp(ofile, omodulus) < 1)
158 res = fprintf(ofile, "\n");
161 return (res > 0 ? 0 : -1);
166 ** Sieve p's and q's with small factors
169 sieve_large(u_int32_t s)
173 debug3("sieve_large %u", s);
175 /* r = largebase mod s */
176 r = BN_mod_word(largebase, s);
178 u = 0; /* s divides into largebase exactly */
180 u = s - r; /* largebase+u is first entry divisible by s */
182 if (u < largebits * 2) {
184 * The sieve omits p's and q's divisible by 2, so ensure that
185 * largebase+u is odd. Then, step through the sieve in
189 u += s; /* Make largebase+u odd, and u even */
191 /* Mark all multiples of 2*s */
192 for (u /= 2; u < largebits; u += s)
193 BIT_SET(LargeSieve, u);
199 u = 0; /* s divides p exactly */
201 u = s - r; /* p+u is first entry divisible by s */
203 if (u < largebits * 4) {
205 * The sieve omits p's divisible by 4, so ensure that
206 * largebase+u is not. Then, step through the sieve in
210 if (SMALL_MAXIMUM - u < s)
215 /* Mark all multiples of 4*s */
216 for (u /= 4; u < largebits; u += s)
217 BIT_SET(LargeSieve, u);
222 * list candidates for Sophie-Germaine primes (where q = (p-1)/2)
223 * to standard output.
224 * The list is checked against small known primes (less than 2**30).
227 gen_candidates(FILE *out, int memory, int power, BIGNUM *start)
230 u_int32_t j, r, s, t;
231 u_int32_t smallwords = TINY_NUMBER >> 6;
232 u_int32_t tinywords = TINY_NUMBER >> 6;
233 time_t time_start, time_stop;
236 largememory = memory;
239 * Set power to the length in bits of the prime to be generated.
240 * This is changed to 1 less than the desired safe prime moduli p.
242 if (power > TEST_MAXIMUM) {
243 error("Too many bits: %u > %lu", power, TEST_MAXIMUM);
245 } else if (power < TEST_MINIMUM) {
246 error("Too few bits: %u < %u", power, TEST_MINIMUM);
249 power--; /* decrement before squaring */
252 * The density of ordinary primes is on the order of 1/bits, so the
253 * density of safe primes should be about (1/bits)**2. Set test range
254 * to something well above bits**2 to be reasonably sure (but not
255 * guaranteed) of catching at least one safe prime.
257 largewords = ((power * power) >> (SHIFT_WORD - TEST_POWER));
260 * Need idea of how much memory is available. We don't have to use all
263 if (largememory > LARGE_MAXIMUM) {
264 logit("Limited memory: %u MB; limit %lu MB",
265 largememory, LARGE_MAXIMUM);
266 largememory = LARGE_MAXIMUM;
269 if (largewords <= (largememory << SHIFT_MEGAWORD)) {
270 logit("Increased memory: %u MB; need %u bytes",
271 largememory, (largewords << SHIFT_BYTE));
272 largewords = (largememory << SHIFT_MEGAWORD);
273 } else if (largememory > 0) {
274 logit("Decreased memory: %u MB; want %u bytes",
275 largememory, (largewords << SHIFT_BYTE));
276 largewords = (largememory << SHIFT_MEGAWORD);
279 TinySieve = calloc(tinywords, sizeof(u_int32_t));
280 if (TinySieve == NULL) {
281 error("Insufficient memory for tiny sieve: need %u bytes",
282 tinywords << SHIFT_BYTE);
285 tinybits = tinywords << SHIFT_WORD;
287 SmallSieve = calloc(smallwords, sizeof(u_int32_t));
288 if (SmallSieve == NULL) {
289 error("Insufficient memory for small sieve: need %u bytes",
290 smallwords << SHIFT_BYTE);
294 smallbits = smallwords << SHIFT_WORD;
297 * dynamically determine available memory
299 while ((LargeSieve = calloc(largewords, sizeof(u_int32_t))) == NULL)
300 largewords -= (1L << (SHIFT_MEGAWORD - 2)); /* 1/4 MB chunks */
302 largebits = largewords << SHIFT_WORD;
303 largenumbers = largebits * 2; /* even numbers excluded */
305 /* validation check: count the number of primes tried */
310 * Generate random starting point for subprime search, or use
311 * specified parameter.
313 largebase = BN_new();
315 BN_rand(largebase, power, 1, 1);
317 BN_copy(largebase, start);
320 BN_set_bit(largebase, 0);
324 logit("%.24s Sieve next %u plus %u-bit", ctime(&time_start),
325 largenumbers, power);
326 debug2("start point: 0x%s", BN_bn2hex(largebase));
331 for (i = 0; i < tinybits; i++) {
332 if (BIT_TEST(TinySieve, i))
333 continue; /* 2*i+3 is composite */
335 /* The next tiny prime */
338 /* Mark all multiples of t */
339 for (j = i + t; j < tinybits; j += t)
340 BIT_SET(TinySieve, j);
346 * Start the small block search at the next possible prime. To avoid
347 * fencepost errors, the last pass is skipped.
349 for (smallbase = TINY_NUMBER + 3;
350 smallbase < (SMALL_MAXIMUM - TINY_NUMBER);
351 smallbase += TINY_NUMBER) {
352 for (i = 0; i < tinybits; i++) {
353 if (BIT_TEST(TinySieve, i))
354 continue; /* 2*i+3 is composite */
356 /* The next tiny prime */
361 s = 0; /* t divides into smallbase exactly */
363 /* smallbase+s is first entry divisible by t */
368 * The sieve omits even numbers, so ensure that
369 * smallbase+s is odd. Then, step through the sieve
370 * in increments of 2*t
373 s += t; /* Make smallbase+s odd, and s even */
375 /* Mark all multiples of 2*t */
376 for (s /= 2; s < smallbits; s += t)
377 BIT_SET(SmallSieve, s);
383 for (i = 0; i < smallbits; i++) {
384 if (BIT_TEST(SmallSieve, i))
385 continue; /* 2*i+smallbase is composite */
387 /* The next small prime */
388 sieve_large((2 * i) + smallbase);
391 memset(SmallSieve, 0, smallwords << SHIFT_BYTE);
396 logit("%.24s Sieved with %u small primes in %ld seconds",
397 ctime(&time_stop), largetries, (long) (time_stop - time_start));
399 for (j = r = 0; j < largebits; j++) {
400 if (BIT_TEST(LargeSieve, j))
401 continue; /* Definitely composite, skip */
403 debug2("test q = largebase+%u", 2 * j);
404 BN_set_word(q, 2 * j);
405 BN_add(q, q, largebase);
406 if (qfileout(out, QTYPE_SOPHIE_GERMAINE, QTEST_SIEVE,
407 largetries, (power - 1) /* MSB */, (0), q) == -1) {
421 logit("%.24s Found %u candidates", ctime(&time_stop), r);
427 * perform a Miller-Rabin primality test
428 * on the list of candidates
429 * (checking both q and p)
430 * The result is a list of so-call "safe" primes
433 prime_test(FILE *in, FILE *out, u_int32_t trials,
434 u_int32_t generator_wanted)
439 u_int32_t count_in = 0, count_out = 0, count_possible = 0;
440 u_int32_t generator_known, in_tests, in_tries, in_type, in_size;
441 time_t time_start, time_stop;
450 debug2("%.24s Final %u Miller-Rabin trials (%x generator)",
451 ctime(&time_start), trials, generator_wanted);
454 lp = xmalloc(QLINESIZE + 1);
455 while (fgets(lp, QLINESIZE, in) != NULL) {
459 if (ll < 14 || *lp == '!' || *lp == '#') {
460 debug2("%10u: comment or short line", count_in);
464 /* XXX - fragile parser */
466 cp = &lp[14]; /* (skip) */
469 in_type = strtoul(cp, &cp, 10);
472 in_tests = strtoul(cp, &cp, 10);
474 if (in_tests & QTEST_COMPOSITE) {
475 debug2("%10u: known composite", count_in);
480 in_tries = strtoul(cp, &cp, 10);
482 /* size (most significant bit) */
483 in_size = strtoul(cp, &cp, 10);
485 /* generator (hex) */
486 generator_known = strtoul(cp, &cp, 16);
488 /* Skip white space */
489 cp += strspn(cp, " ");
493 case QTYPE_SOPHIE_GERMAINE:
494 debug2("%10u: (%u) Sophie-Germaine", count_in, in_type);
503 case QTYPE_UNSTRUCTURED:
508 debug2("%10u: (%u)", count_in, in_type);
515 debug2("Unknown prime type");
520 * due to earlier inconsistencies in interpretation, check
521 * the proposed bit size.
523 if (BN_num_bits(p) != (in_size + 1)) {
524 debug2("%10u: bit size %u mismatch", count_in, in_size);
527 if (in_size < QSIZE_MINIMUM) {
528 debug2("%10u: bit size %u too short", count_in, in_size);
532 if (in_tests & QTEST_MILLER_RABIN)
538 * guess unknown generator
540 if (generator_known == 0) {
541 if (BN_mod_word(p, 24) == 11)
543 else if (BN_mod_word(p, 12) == 5)
546 u_int32_t r = BN_mod_word(p, 10);
548 if (r == 3 || r == 7)
553 * skip tests when desired generator doesn't match
555 if (generator_wanted > 0 &&
556 generator_wanted != generator_known) {
557 debug2("%10u: generator %d != %d",
558 count_in, generator_known, generator_wanted);
563 * Primes with no known generator are useless for DH, so
566 if (generator_known == 0) {
567 debug2("%10u: no known generator", count_in);
574 * The (1/4)^N performance bound on Miller-Rabin is
575 * extremely pessimistic, so don't spend a lot of time
576 * really verifying that q is prime until after we know
577 * that p is also prime. A single pass will weed out the
578 * vast majority of composite q's.
580 if (BN_is_prime(q, 1, NULL, ctx, NULL) <= 0) {
581 debug("%10u: q failed first possible prime test",
587 * q is possibly prime, so go ahead and really make sure
588 * that p is prime. If it is, then we can go back and do
589 * the same for q. If p is composite, chances are that
590 * will show up on the first Rabin-Miller iteration so it
591 * doesn't hurt to specify a high iteration count.
593 if (!BN_is_prime(p, trials, NULL, ctx, NULL)) {
594 debug("%10u: p is not prime", count_in);
597 debug("%10u: p is almost certainly prime", count_in);
599 /* recheck q more rigorously */
600 if (!BN_is_prime(q, trials - 1, NULL, ctx, NULL)) {
601 debug("%10u: q is not prime", count_in);
604 debug("%10u: q is almost certainly prime", count_in);
606 if (qfileout(out, QTYPE_SAFE, (in_tests | QTEST_MILLER_RABIN),
607 in_tries, in_size, generator_known, p)) {
621 logit("%.24s Found %u safe primes of %u candidates in %ld seconds",
622 ctime(&time_stop), count_out, count_possible,
623 (long) (time_stop - time_start));