Home | History | Annotate | Line # | Download | only in dist
      1 /*	$NetBSD: moduli.c,v 1.19 2026/04/08 18:58:40 christos Exp $	*/
      2 /* $OpenBSD: moduli.c,v 1.41 2026/03/03 09:57:25 dtucker Exp $ */
      3 
      4 /*
      5  * Copyright 1994 Phil Karn <karn (at) qualcomm.com>
      6  * Copyright 1996-1998, 2003 William Allen Simpson <wsimpson (at) greendragon.com>
      7  * Copyright 2000 Niels Provos <provos (at) citi.umich.edu>
      8  * All rights reserved.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 /*
     32  * Two-step process to generate safe primes for DHGEX
     33  *
     34  *  Sieve candidates for "safe" primes,
     35  *  suitable for use as Diffie-Hellman moduli;
     36  *  that is, where q = (p-1)/2 is also prime.
     37  *
     38  * First step: generate candidate primes (memory intensive)
     39  * Second step: test primes' safety (processor intensive)
     40  */
     41 #include "includes.h"
     42 __RCSID("$NetBSD: moduli.c,v 1.19 2026/04/08 18:58:40 christos Exp $");
     43 
     44 #include <sys/types.h>
     45 
     46 #include <openssl/bn.h>
     47 #include <openssl/dh.h>
     48 
     49 #include <errno.h>
     50 #include <stdio.h>
     51 #include <stdlib.h>
     52 #include <string.h>
     53 #include <stdarg.h>
     54 #include <time.h>
     55 #include <unistd.h>
     56 #include <limits.h>
     57 
     58 #include "xmalloc.h"
     59 #include "dh.h"
     60 #include "log.h"
     61 #include "misc.h"
     62 
     63 /*
     64  * File output defines
     65  */
     66 
     67 /* need line long enough for largest moduli plus headers */
     68 #define QLINESIZE		(100+8192)
     69 
     70 /*
     71  * Size: decimal.
     72  * Specifies the number of the most significant bit (0 to M).
     73  * WARNING: internally, usually 1 to N.
     74  */
     75 #define QSIZE_MINIMUM		(511)
     76 
     77 /*
     78  * Prime sieving defines
     79  */
     80 
     81 /* Constant: assuming 8 bit bytes and 32 bit words */
     82 #define SHIFT_BIT	(3)
     83 #define SHIFT_BYTE	(2)
     84 #define SHIFT_WORD	(SHIFT_BIT+SHIFT_BYTE)
     85 #define SHIFT_MEGABYTE	(20)
     86 #define SHIFT_MEGAWORD	(SHIFT_MEGABYTE-SHIFT_BYTE)
     87 
     88 /*
     89  * Do not increase this number beyond the unsigned integer bit size.
     90  * Due to a multiple of 4, it must be LESS than 128 (yielding 2**30 bits).
     91  */
     92 #define LARGE_MAXIMUM	(127UL)	/* megabytes */
     93 
     94 /*
     95  * Constant: when used with 32-bit integers, the largest sieve prime
     96  * has to be less than 2**32.
     97  */
     98 #define SMALL_MAXIMUM	(0xffffffffUL)
     99 
    100 /* Constant: can sieve all primes less than 2**32, as 65537**2 > 2**32-1. */
    101 #define TINY_NUMBER	(1UL<<16)
    102 
    103 /* Ensure enough bit space for testing 2*q. */
    104 #define TEST_MAXIMUM	(1UL<<16)
    105 #define TEST_MINIMUM	(QSIZE_MINIMUM + 1)
    106 /* real TEST_MINIMUM	(1UL << (SHIFT_WORD - TEST_POWER)) */
    107 #define TEST_POWER	(3)	/* 2**n, n < SHIFT_WORD */
    108 
    109 /* bit operations on 32-bit words */
    110 #define BIT_CLEAR(a,n)	((a)[(n)>>SHIFT_WORD] &= ~(1L << ((n) & 31)))
    111 #define BIT_SET(a,n)	((a)[(n)>>SHIFT_WORD] |= (1L << ((n) & 31)))
    112 #define BIT_TEST(a,n)	((a)[(n)>>SHIFT_WORD] & (1L << ((n) & 31)))
    113 
    114 /*
    115  * Prime testing defines
    116  */
    117 
    118 /* Minimum number of primality tests to perform */
    119 #define TRIAL_MINIMUM	(4)
    120 
    121 /*
    122  * Sieving data (XXX - move to struct)
    123  */
    124 
    125 /* sieve 2**16 */
    126 static uint32_t *TinySieve, tinybits;
    127 
    128 /* sieve 2**30 in 2**16 parts */
    129 static uint32_t *SmallSieve, smallbits, smallbase;
    130 
    131 /* sieve relative to the initial value */
    132 static uint32_t *LargeSieve, largewords, largetries, largenumbers;
    133 static uint32_t largebits, largememory;	/* megabytes */
    134 static BIGNUM *largebase;
    135 
    136 int gen_candidates(FILE *, uint32_t, BIGNUM *);
    137 int prime_test(FILE *, FILE *, uint32_t, uint32_t, char *, unsigned long,
    138     unsigned long);
    139 
    140 /*
    141  * print moduli out in consistent form,
    142  */
    143 static int
    144 qfileout(FILE * ofile, uint32_t otype, uint32_t otests, uint32_t otries,
    145     uint32_t osize, uint32_t ogenerator, BIGNUM * omodulus)
    146 {
    147 	struct tm *gtm;
    148 	time_t time_now;
    149 	int res;
    150 
    151 	time(&time_now);
    152 	gtm = gmtime(&time_now);
    153 	if (gtm == NULL)
    154 		return -1;
    155 
    156 	res = fprintf(ofile, "%04d%02d%02d%02d%02d%02d %u %u %u %u %x ",
    157 	    gtm->tm_year + 1900, gtm->tm_mon + 1, gtm->tm_mday,
    158 	    gtm->tm_hour, gtm->tm_min, gtm->tm_sec,
    159 	    otype, otests, otries, osize, ogenerator);
    160 
    161 	if (res < 0)
    162 		return (-1);
    163 
    164 	if (BN_print_fp(ofile, omodulus) < 1)
    165 		return (-1);
    166 
    167 	res = fprintf(ofile, "\n");
    168 	fflush(ofile);
    169 
    170 	return (res > 0 ? 0 : -1);
    171 }
    172 
    173 
    174 /*
    175  ** Sieve p's and q's with small factors
    176  */
    177 static void
    178 sieve_large(uint32_t s32)
    179 {
    180 	uint64_t r, u, s = s32;
    181 
    182 	debug3("sieve_large %u", s32);
    183 	largetries++;
    184 	/* r = largebase mod s */
    185 	r = BN_mod_word(largebase, s32);
    186 	if (r == 0)
    187 		u = 0; /* s divides into largebase exactly */
    188 	else
    189 		u = s - r; /* largebase+u is first entry divisible by s */
    190 
    191 	if (u < largebits * 2ULL) {
    192 		/*
    193 		 * The sieve omits p's and q's divisible by 2, so ensure that
    194 		 * largebase+u is odd. Then, step through the sieve in
    195 		 * increments of 2*s
    196 		 */
    197 		if (u & 0x1)
    198 			u += s; /* Make largebase+u odd, and u even */
    199 
    200 		/* Mark all multiples of 2*s */
    201 		for (u /= 2; u < largebits; u += s)
    202 			BIT_SET(LargeSieve, u);
    203 	}
    204 
    205 	/* r = p mod s */
    206 	r = (2 * r + 1) % s;
    207 	if (r == 0)
    208 		u = 0; /* s divides p exactly */
    209 	else
    210 		u = s - r; /* p+u is first entry divisible by s */
    211 
    212 	if (u < largebits * 4ULL) {
    213 		/*
    214 		 * The sieve omits p's divisible by 4, so ensure that
    215 		 * largebase+u is not. Then, step through the sieve in
    216 		 * increments of 4*s
    217 		 */
    218 		while (u & 0x3) {
    219 			if (SMALL_MAXIMUM - u < s)
    220 				return;
    221 			u += s;
    222 		}
    223 
    224 		/* Mark all multiples of 4*s */
    225 		for (u /= 4; u < largebits; u += s)
    226 			BIT_SET(LargeSieve, u);
    227 	}
    228 }
    229 
    230 /*
    231  * list candidates for Sophie-Germain primes (where q = (p-1)/2)
    232  * to standard output.
    233  * The list is checked against small known primes (less than 2**30).
    234  */
    235 int
    236 gen_candidates(FILE *out, uint32_t power, BIGNUM *start)
    237 {
    238 	BIGNUM *q;
    239 	uint32_t j, r, s, t;
    240 	uint32_t smallwords = TINY_NUMBER >> 6;
    241 	uint32_t tinywords = TINY_NUMBER >> 6;
    242 	time_t time_start, time_stop;
    243 	uint32_t i;
    244 	int ret = 0;
    245 
    246 	/*
    247 	 * Set power to the length in bits of the prime to be generated.
    248 	 * This is changed to 1 less than the desired safe prime moduli p.
    249 	 */
    250 	if (power > TEST_MAXIMUM) {
    251 		error("Too many bits: %u > %lu", power, TEST_MAXIMUM);
    252 		return (-1);
    253 	} else if (power < TEST_MINIMUM) {
    254 		error("Too few bits: %u < %u", power, TEST_MINIMUM);
    255 		return (-1);
    256 	}
    257 	power--; /* decrement before squaring */
    258 
    259 	/* Always use the maximum amount of memory supported by the algorithm. */
    260 	largememory = LARGE_MAXIMUM;
    261 	largewords = (largememory << SHIFT_MEGAWORD);
    262 
    263 	TinySieve = xcalloc(tinywords, sizeof(uint32_t));
    264 	tinybits = tinywords << SHIFT_WORD;
    265 
    266 	SmallSieve = xcalloc(smallwords, sizeof(uint32_t));
    267 	smallbits = smallwords << SHIFT_WORD;
    268 
    269 	LargeSieve = xcalloc(largewords, sizeof(uint32_t));
    270 	largebits = largewords << SHIFT_WORD;
    271 	largenumbers = largebits * 2;	/* even numbers excluded */
    272 
    273 	/* validation check: count the number of primes tried */
    274 	largetries = 0;
    275 	if ((q = BN_new()) == NULL)
    276 		fatal("BN_new failed");
    277 
    278 	/*
    279 	 * Generate random starting point for subprime search, or use
    280 	 * specified parameter.
    281 	 */
    282 	if ((largebase = BN_new()) == NULL)
    283 		fatal("BN_new failed");
    284 	if (start == NULL) {
    285 		if (BN_rand(largebase, power, 1, 1) == 0)
    286 			fatal("BN_rand failed");
    287 	} else {
    288 		if (BN_copy(largebase, start) == NULL)
    289 			fatal("BN_copy: failed");
    290 	}
    291 
    292 	/* ensure odd */
    293 	if (BN_set_bit(largebase, 0) == 0)
    294 		fatal("BN_set_bit: failed");
    295 
    296 	time(&time_start);
    297 
    298 	logit("%.24s Sieve next %u plus %u-bit", ctime(&time_start),
    299 	    largenumbers, power);
    300 	debug2("start point: 0x%s", BN_bn2hex(largebase));
    301 
    302 	/*
    303 	 * TinySieve
    304 	 */
    305 	for (i = 0; i < tinybits; i++) {
    306 		if (BIT_TEST(TinySieve, i))
    307 			continue; /* 2*i+3 is composite */
    308 
    309 		/* The next tiny prime */
    310 		t = 2 * i + 3;
    311 
    312 		/* Mark all multiples of t */
    313 		for (j = i + t; j < tinybits; j += t)
    314 			BIT_SET(TinySieve, j);
    315 
    316 		sieve_large(t);
    317 	}
    318 
    319 	/*
    320 	 * Start the small block search at the next possible prime. To avoid
    321 	 * fencepost errors, the last pass is skipped.
    322 	 */
    323 	for (smallbase = TINY_NUMBER + 3;
    324 	    smallbase < (SMALL_MAXIMUM - TINY_NUMBER);
    325 	    smallbase += TINY_NUMBER) {
    326 		for (i = 0; i < tinybits; i++) {
    327 			if (BIT_TEST(TinySieve, i))
    328 				continue; /* 2*i+3 is composite */
    329 
    330 			/* The next tiny prime */
    331 			t = 2 * i + 3;
    332 			r = smallbase % t;
    333 
    334 			if (r == 0) {
    335 				s = 0; /* t divides into smallbase exactly */
    336 			} else {
    337 				/* smallbase+s is first entry divisible by t */
    338 				s = t - r;
    339 			}
    340 
    341 			/*
    342 			 * The sieve omits even numbers, so ensure that
    343 			 * smallbase+s is odd. Then, step through the sieve
    344 			 * in increments of 2*t
    345 			 */
    346 			if (s & 1)
    347 				s += t; /* Make smallbase+s odd, and s even */
    348 
    349 			/* Mark all multiples of 2*t */
    350 			for (s /= 2; s < smallbits; s += t)
    351 				BIT_SET(SmallSieve, s);
    352 		}
    353 
    354 		/*
    355 		 * SmallSieve
    356 		 */
    357 		for (i = 0; i < smallbits; i++) {
    358 			if (BIT_TEST(SmallSieve, i))
    359 				continue; /* 2*i+smallbase is composite */
    360 
    361 			/* The next small prime */
    362 			sieve_large((2 * i) + smallbase);
    363 		}
    364 
    365 		memset(SmallSieve, 0, smallwords << SHIFT_BYTE);
    366 	}
    367 
    368 	time(&time_stop);
    369 
    370 	logit("%.24s Sieved with %u small primes in %lld seconds",
    371 	    ctime(&time_stop), largetries, (long long)(time_stop - time_start));
    372 
    373 	for (j = r = 0; j < largebits; j++) {
    374 		if (BIT_TEST(LargeSieve, j))
    375 			continue; /* Definitely composite, skip */
    376 
    377 		debug2("test q = largebase+%u", 2 * j);
    378 		if (BN_set_word(q, 2 * j) == 0)
    379 			fatal("BN_set_word failed");
    380 		if (BN_add(q, q, largebase) == 0)
    381 			fatal("BN_add failed");
    382 		if (qfileout(out, MODULI_TYPE_SOPHIE_GERMAIN,
    383 		    MODULI_TESTS_SIEVE, largetries,
    384 		    (power - 1) /* MSB */, (0), q) == -1) {
    385 			ret = -1;
    386 			break;
    387 		}
    388 
    389 		r++; /* count q */
    390 	}
    391 
    392 	time(&time_stop);
    393 
    394 	free(LargeSieve);
    395 	free(SmallSieve);
    396 	free(TinySieve);
    397 
    398 	logit("%.24s Found %u candidates", ctime(&time_stop), r);
    399 
    400 	return (ret);
    401 }
    402 
    403 static void
    404 write_checkpoint(char *cpfile, uint32_t lineno)
    405 {
    406 	FILE *fp;
    407 	char tmp[PATH_MAX];
    408 	int r, writeok, closeok;
    409 
    410 	r = snprintf(tmp, sizeof(tmp), "%s.XXXXXXXXXX", cpfile);
    411 	if (r < 0 || r >= PATH_MAX) {
    412 		logit("write_checkpoint: temp pathname too long");
    413 		return;
    414 	}
    415 	if ((r = mkstemp(tmp)) == -1) {
    416 		logit("mkstemp(%s): %s", tmp, strerror(errno));
    417 		return;
    418 	}
    419 	if ((fp = fdopen(r, "w")) == NULL) {
    420 		logit("write_checkpoint: fdopen: %s", strerror(errno));
    421 		unlink(tmp);
    422 		close(r);
    423 		return;
    424 	}
    425 	writeok = (fprintf(fp, "%lu\n", (unsigned long)lineno) > 0);
    426 	closeok = (fclose(fp) == 0);
    427 	if (writeok && closeok && rename(tmp, cpfile) == 0) {
    428 		debug3("wrote checkpoint line %lu to '%s'",
    429 		    (unsigned long)lineno, cpfile);
    430 	} else {
    431 		logit("failed to write to checkpoint file '%s': %s", cpfile,
    432 		    strerror(errno));
    433 		(void)unlink(tmp);
    434 	}
    435 }
    436 
    437 static unsigned long
    438 read_checkpoint(char *cpfile)
    439 {
    440 	FILE *fp;
    441 	unsigned long lineno = 0;
    442 
    443 	if ((fp = fopen(cpfile, "r")) == NULL)
    444 		return 0;
    445 	if (fscanf(fp, "%lu\n", &lineno) < 1)
    446 		logit("Failed to load checkpoint from '%s'", cpfile);
    447 	else
    448 		logit("Loaded checkpoint from '%s' line %lu", cpfile, lineno);
    449 	fclose(fp);
    450 	return lineno;
    451 }
    452 
    453 static unsigned long
    454 count_lines(FILE *f)
    455 {
    456 	unsigned long count = 0;
    457 	char lp[QLINESIZE + 1];
    458 
    459 	if (fseek(f, 0, SEEK_SET) != 0) {
    460 		debug("input file is not seekable");
    461 		return ULONG_MAX;
    462 	}
    463 	while (fgets(lp, QLINESIZE + 1, f) != NULL)
    464 		count++;
    465 	rewind(f);
    466 	debug("input file has %lu lines", count);
    467 	return count;
    468 }
    469 
    470 static char *
    471 fmt_time(time_t seconds)
    472 {
    473 	int day, hr, min;
    474 	static char buf[128];
    475 
    476 	min = (seconds / 60) % 60;
    477 	hr = (seconds / 60 / 60) % 24;
    478 	day = seconds / 60 / 60 / 24;
    479 	if (day > 0)
    480 		snprintf(buf, sizeof buf, "%dd %d:%02d", day, hr, min);
    481 	else
    482 		snprintf(buf, sizeof buf, "%d:%02d", hr, min);
    483 	return buf;
    484 }
    485 
    486 static void
    487 print_progress(unsigned long start_lineno, unsigned long current_lineno,
    488     unsigned long end_lineno)
    489 {
    490 	static time_t time_start, time_prev;
    491 	time_t time_now, elapsed;
    492 	unsigned long num_to_process, processed, remaining, percent, eta;
    493 	double time_per_line;
    494 	char *eta_str;
    495 
    496 	time_now = monotime();
    497 	if (time_start == 0) {
    498 		time_start = time_prev = time_now;
    499 		return;
    500 	}
    501 	/* print progress after 1m then once per 5m */
    502 	if (time_now - time_prev < 5 * 60)
    503 		return;
    504 	time_prev = time_now;
    505 	elapsed = time_now - time_start;
    506 	processed = current_lineno - start_lineno;
    507 	remaining = end_lineno - current_lineno;
    508 	num_to_process = end_lineno - start_lineno;
    509 	time_per_line = (double)elapsed / processed;
    510 	/* if we don't know how many we're processing just report count+time */
    511 	time(&time_now);
    512 	if (end_lineno == ULONG_MAX) {
    513 		logit("%.24s processed %lu in %s", ctime(&time_now),
    514 		    processed, fmt_time(elapsed));
    515 		return;
    516 	}
    517 	percent = 100 * processed / num_to_process;
    518 	eta = time_per_line * remaining;
    519 	eta_str = xstrdup(fmt_time(eta));
    520 	logit("%.24s processed %lu of %lu (%lu%%) in %s, ETA %s",
    521 	    ctime(&time_now), processed, num_to_process, percent,
    522 	    fmt_time(elapsed), eta_str);
    523 	free(eta_str);
    524 }
    525 
    526 /*
    527  * perform a Miller-Rabin primality test
    528  * on the list of candidates
    529  * (checking both q and p)
    530  * The result is a list of so-call "safe" primes
    531  */
    532 int
    533 prime_test(FILE *in, FILE *out, uint32_t trials, uint32_t generator_wanted,
    534     char *checkpoint_file, unsigned long start_lineno, unsigned long num_lines)
    535 {
    536 	BIGNUM *q, *p, *a;
    537 	char *cp, *lp;
    538 	uint32_t count_in = 0, count_out = 0, count_possible = 0;
    539 	uint32_t generator_known, in_tests, in_tries, in_type, in_size;
    540 	unsigned long last_processed = 0, end_lineno;
    541 	time_t time_start, time_stop;
    542 	int res, is_prime;
    543 
    544 	if (trials < TRIAL_MINIMUM) {
    545 		error("Minimum primality trials is %d", TRIAL_MINIMUM);
    546 		return (-1);
    547 	}
    548 
    549 	if (num_lines == 0)
    550 		end_lineno = count_lines(in);
    551 	else
    552 		end_lineno = start_lineno + num_lines;
    553 
    554 	time(&time_start);
    555 
    556 	if ((p = BN_new()) == NULL)
    557 		fatal("BN_new failed");
    558 	if ((q = BN_new()) == NULL)
    559 		fatal("BN_new failed");
    560 
    561 	debug2("%.24s Final %u Miller-Rabin trials (%x generator)",
    562 	    ctime(&time_start), trials, generator_wanted);
    563 
    564 	if (checkpoint_file != NULL)
    565 		last_processed = read_checkpoint(checkpoint_file);
    566 	last_processed = start_lineno = MAXIMUM(last_processed, start_lineno);
    567 	if (end_lineno == ULONG_MAX)
    568 		debug("process from line %lu from pipe", last_processed);
    569 	else
    570 		debug("process from line %lu to line %lu", last_processed,
    571 		    end_lineno);
    572 
    573 	res = 0;
    574 	lp = xmalloc(QLINESIZE + 1);
    575 	while (fgets(lp, QLINESIZE + 1, in) != NULL && count_in < end_lineno) {
    576 		count_in++;
    577 		if (count_in <= last_processed) {
    578 			debug3("skipping line %u, before checkpoint or "
    579 			    "specified start line", count_in);
    580 			continue;
    581 		}
    582 		if (checkpoint_file != NULL)
    583 			write_checkpoint(checkpoint_file, count_in);
    584 		print_progress(start_lineno, count_in, end_lineno);
    585 		if (strlen(lp) < 14 || *lp == '!' || *lp == '#') {
    586 			debug2("%10u: comment or short line", count_in);
    587 			continue;
    588 		}
    589 
    590 		/* XXX - fragile parser */
    591 		/* time */
    592 		cp = &lp[14];	/* (skip) */
    593 
    594 		/* type */
    595 		in_type = strtoul(cp, &cp, 10);
    596 
    597 		/* tests */
    598 		in_tests = strtoul(cp, &cp, 10);
    599 
    600 		if (in_tests & MODULI_TESTS_COMPOSITE) {
    601 			debug2("%10u: known composite", count_in);
    602 			continue;
    603 		}
    604 
    605 		/* tries */
    606 		in_tries = strtoul(cp, &cp, 10);
    607 
    608 		/* size (most significant bit) */
    609 		in_size = strtoul(cp, &cp, 10);
    610 
    611 		/* generator (hex) */
    612 		generator_known = strtoul(cp, &cp, 16);
    613 
    614 		/* Skip white space */
    615 		cp += strspn(cp, " ");
    616 
    617 		/* modulus (hex) */
    618 		switch (in_type) {
    619 		case MODULI_TYPE_SOPHIE_GERMAIN:
    620 			debug2("%10u: (%u) Sophie-Germain", count_in, in_type);
    621 			a = q;
    622 			if (BN_hex2bn(&a, cp) == 0)
    623 				fatal("BN_hex2bn failed");
    624 			/* p = 2*q + 1 */
    625 			if (BN_lshift(p, q, 1) == 0)
    626 				fatal("BN_lshift failed");
    627 			if (BN_add_word(p, 1) == 0)
    628 				fatal("BN_add_word failed");
    629 			in_size += 1;
    630 			generator_known = 0;
    631 			break;
    632 		case MODULI_TYPE_UNSTRUCTURED:
    633 		case MODULI_TYPE_SAFE:
    634 		case MODULI_TYPE_SCHNORR:
    635 		case MODULI_TYPE_STRONG:
    636 		case MODULI_TYPE_UNKNOWN:
    637 			debug2("%10u: (%u)", count_in, in_type);
    638 			a = p;
    639 			if (BN_hex2bn(&a, cp) == 0)
    640 				fatal("BN_hex2bn failed");
    641 			/* q = (p-1) / 2 */
    642 			if (BN_rshift(q, p, 1) == 0)
    643 				fatal("BN_rshift failed");
    644 			break;
    645 		default:
    646 			debug2("Unknown prime type");
    647 			break;
    648 		}
    649 
    650 		/*
    651 		 * due to earlier inconsistencies in interpretation, check
    652 		 * the proposed bit size.
    653 		 */
    654 		if ((uint32_t)BN_num_bits(p) != (in_size + 1)) {
    655 			debug2("%10u: bit size %u mismatch", count_in, in_size);
    656 			continue;
    657 		}
    658 		if (in_size < QSIZE_MINIMUM) {
    659 			debug2("%10u: bit size %u too short", count_in, in_size);
    660 			continue;
    661 		}
    662 
    663 		if (in_tests & MODULI_TESTS_MILLER_RABIN)
    664 			in_tries += trials;
    665 		else
    666 			in_tries = trials;
    667 
    668 		/*
    669 		 * guess unknown generator
    670 		 */
    671 		if (generator_known == 0) {
    672 			if (BN_mod_word(p, 24) == 11)
    673 				generator_known = 2;
    674 			else {
    675 				uint32_t r = BN_mod_word(p, 10);
    676 
    677 				if (r == 3 || r == 7)
    678 					generator_known = 5;
    679 			}
    680 		}
    681 		/*
    682 		 * skip tests when desired generator doesn't match
    683 		 */
    684 		if (generator_wanted > 0 &&
    685 		    generator_wanted != generator_known) {
    686 			debug2("%10u: generator %d != %d",
    687 			    count_in, generator_known, generator_wanted);
    688 			continue;
    689 		}
    690 
    691 		/*
    692 		 * Primes with no known generator are useless for DH, so
    693 		 * skip those.
    694 		 */
    695 		if (generator_known == 0) {
    696 			debug2("%10u: no known generator", count_in);
    697 			continue;
    698 		}
    699 
    700 		count_possible++;
    701 
    702 		/*
    703 		 * The (1/4)^N performance bound on Miller-Rabin is
    704 		 * extremely pessimistic, so don't spend a lot of time
    705 		 * really verifying that q is prime until after we know
    706 		 * that p is also prime. A single pass will weed out the
    707 		 * vast majority of composite q's.
    708 		 */
    709 		is_prime = BN_is_prime_ex(q, 1, NULL, NULL);
    710 		if (is_prime < 0)
    711 			fatal("BN_is_prime_ex failed");
    712 		if (is_prime == 0) {
    713 			debug("%10u: q failed first possible prime test",
    714 			    count_in);
    715 			continue;
    716 		}
    717 
    718 		/*
    719 		 * q is possibly prime, so go ahead and really make sure
    720 		 * that p is prime. If it is, then we can go back and do
    721 		 * the same for q. If p is composite, chances are that
    722 		 * will show up on the first Rabin-Miller iteration so it
    723 		 * doesn't hurt to specify a high iteration count.
    724 		 */
    725 		is_prime = BN_is_prime_ex(p, trials, NULL, NULL);
    726 		if (is_prime < 0)
    727 			fatal("BN_is_prime_ex failed");
    728 		if (is_prime == 0) {
    729 			debug("%10u: p is not prime", count_in);
    730 			continue;
    731 		}
    732 		debug("%10u: p is almost certainly prime", count_in);
    733 
    734 		/* recheck q more rigorously */
    735 		is_prime = BN_is_prime_ex(q, trials - 1, NULL, NULL);
    736 		if (is_prime < 0)
    737 			fatal("BN_is_prime_ex failed");
    738 		if (is_prime == 0) {
    739 			debug("%10u: q is not prime", count_in);
    740 			continue;
    741 		}
    742 		debug("%10u: q is almost certainly prime", count_in);
    743 
    744 		if (qfileout(out, MODULI_TYPE_SAFE,
    745 		    in_tests | MODULI_TESTS_MILLER_RABIN,
    746 		    in_tries, in_size, generator_known, p)) {
    747 			res = -1;
    748 			break;
    749 		}
    750 
    751 		count_out++;
    752 	}
    753 
    754 	time(&time_stop);
    755 	free(lp);
    756 	BN_free(p);
    757 	BN_free(q);
    758 
    759 	if (checkpoint_file != NULL)
    760 		unlink(checkpoint_file);
    761 
    762 	logit("%.24s Found %u safe primes of %u candidates in %ld seconds",
    763 	    ctime(&time_stop), count_out, count_possible,
    764 	    (long) (time_stop - time_start));
    765 
    766 	return (res);
    767 }
    768