No empty .Rs/.Re
[netbsd-mini2440.git] / usr.bin / moduli / qsieve / qsieve.c
blob62f1349673ba8765b38d4e78c72bdc519acfe70a
1 /* $NetBSD: qsieve.c,v 1.1 2006/01/24 18:59:23 elad Exp $ */
3 /*-
4 * Copyright 1994 Phil Karn <karn@qualcomm.com>
5 * Copyright 1996-1998, 2003 William Allen Simpson <wsimpson@greendragon.com>
6 * Copyright 2000 Niels Provos <provos@citi.umich.edu>
7 * All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 * Sieve candidates for "safe" primes,
32 * suitable for use as Diffie-Hellman moduli;
33 * that is, where q = (p-1)/2 is also prime.
35 * This is the first of two steps.
36 * This step is memory intensive.
38 * 1996 May William Allen Simpson
39 * extracted from earlier code by Phil Karn, April 1994.
40 * save large primes list for later processing.
41 * 1998 May William Allen Simpson
42 * parameterized.
43 * 2000 Dec Niels Provos
44 * convert from GMP to openssl BN.
45 * 2003 Jun William Allen Simpson
46 * change outfile definition slightly to match openssh mistake.
47 * move common file i/o to own file for better documentation.
48 * redo memory again.
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <time.h>
54 #include <openssl/bn.h>
55 #include <string.h>
56 #include <err.h>
57 #include "qfile.h"
59 /* define DEBUG_LARGE 1 */
60 /* define DEBUG_SMALL 1 */
63 * Using virtual memory can cause thrashing. This should be the largest
64 * number that is supported without a large amount of disk activity --
65 * that would increase the run time from hours to days or weeks!
67 #define LARGE_MINIMUM (8UL) /* megabytes */
70 * Do not increase this number beyond the unsigned integer bit size.
71 * Due to a multiple of 4, it must be LESS than 128 (yielding 2**30 bits).
73 #define LARGE_MAXIMUM (127UL) /* megabytes */
76 * Constant: assuming 8 bit bytes and 32 bit words
78 #define SHIFT_BIT (3)
79 #define SHIFT_BYTE (2)
80 #define SHIFT_WORD (SHIFT_BIT+SHIFT_BYTE)
81 #define SHIFT_MEGABYTE (20)
82 #define SHIFT_MEGAWORD (SHIFT_MEGABYTE-SHIFT_BYTE)
85 * Constant: when used with 32-bit integers, the largest sieve prime
86 * has to be less than 2**32.
88 #define SMALL_MAXIMUM (0xffffffffUL)
91 * Constant: can sieve all primes less than 2**32, as 65537**2 > 2**32-1.
93 #define TINY_NUMBER (1UL<<16)
96 * Ensure enough bit space for testing 2*q.
98 #define TEST_MAXIMUM (1UL<<16)
99 #define TEST_MINIMUM (QSIZE_MINIMUM + 1)
100 /* real TEST_MINIMUM (1UL << (SHIFT_WORD - TEST_POWER)) */
101 #define TEST_POWER (3) /* 2**n, n < SHIFT_WORD */
104 * bit operations on 32-bit words
106 #define BIT_CLEAR(a,n) ((a)[(n)>>SHIFT_WORD] &= ~(1U << ((n) & 31)))
107 #define BIT_SET(a,n) ((a)[(n)>>SHIFT_WORD] |= (1U << ((n) & 31)))
108 #define BIT_TEST(a,n) ((a)[(n)>>SHIFT_WORD] & (1U << ((n) & 31)))
111 * sieve relative to the initial value
113 uint32_t *LargeSieve;
114 uint32_t largewords;
115 uint32_t largetries;
116 uint32_t largenumbers;
117 uint32_t largememory; /* megabytes */
118 uint32_t largebits;
119 BIGNUM *largebase;
122 * sieve 2**30 in 2**16 parts
124 uint32_t *SmallSieve;
125 uint32_t smallbits;
126 uint32_t smallbase;
129 * sieve 2**16
131 uint32_t *TinySieve;
132 uint32_t tinybits;
134 static void usage(void);
135 void sieve_large(uint32_t);
138 * Sieve p's and q's with small factors
140 void
141 sieve_large(uint32_t s)
143 BN_ULONG r;
144 BN_ULONG u;
146 #ifdef DEBUG_SMALL
147 (void)fprintf(stderr, "%lu\n", s);
148 #endif
149 largetries++;
150 /* r = largebase mod s */
151 r = BN_mod_word(largebase, (BN_ULONG) s);
152 if (r == 0) {
153 /* s divides into largebase exactly */
154 u = 0;
155 } else {
156 /* largebase+u is first entry divisible by s */
157 u = s - r;
160 if (u < largebits * 2) {
162 * The sieve omits p's and q's divisible by 2, so ensure that
163 * largebase+u is odd. Then, step through the sieve in
164 * increments of 2*s
166 if (u & 0x1) {
167 /* Make largebase+u odd, and u even */
168 u += s;
171 /* Mark all multiples of 2*s */
172 for (u /= 2; u < largebits; u += s) {
173 BIT_SET(LargeSieve, (uint32_t)u);
177 /* r = p mod s */
178 r = (2 * r + 1) % s;
180 if (r == 0) {
181 /* s divides p exactly */
182 u = 0;
183 } else {
184 /* p+u is first entry divisible by s */
185 u = s - r;
188 if (u < largebits * 4) {
190 * The sieve omits p's divisible by 4, so ensure that
191 * largebase+u is not. Then, step through the sieve in
192 * increments of 4*s
194 while (u & 0x3) {
195 if (SMALL_MAXIMUM - u < s) {
196 return;
199 u += s;
202 /* Mark all multiples of 4*s */
203 for (u /= 4; u < largebits; u += s) {
204 BIT_SET(LargeSieve, (uint32_t)u);
210 * list candidates for Sophie-Germaine primes
211 * (where q = (p-1)/2)
212 * to standard output.
213 * The list is checked against small known primes
214 * (less than 2**30).
217 main(int argc, char *argv[])
219 BIGNUM *q;
220 uint32_t j;
221 int power;
222 uint32_t r;
223 uint32_t s;
224 uint32_t smallwords = TINY_NUMBER >> 6;
225 uint32_t t;
226 time_t time_start;
227 time_t time_stop;
228 uint32_t tinywords = TINY_NUMBER >> 6;
229 unsigned int i;
231 setprogname(argv[0]);
233 if (argc < 3) {
234 usage();
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 power = (int) strtoul(argv[2], NULL, 10);
242 if ((unsigned)power > TEST_MAXIMUM) {
243 errx(1, "Too many bits: %d > %lu.", power,
244 (unsigned long)TEST_MAXIMUM);
245 } else if (power < TEST_MINIMUM) {
246 errx(1, "Too few bits: %d < %lu.", power,
247 (unsigned long)TEST_MINIMUM);
250 power--; /* decrement before squaring */
253 * The density of ordinary primes is on the order of 1/bits, so the
254 * density of safe primes should be about (1/bits)**2. Set test range
255 * to something well above bits**2 to be reasonably sure (but not
256 * guaranteed) of catching at least one safe prime.
258 largewords = (uint32_t)((unsigned long)
259 (power * power) >> (SHIFT_WORD - TEST_POWER));
262 * Need idea of how much memory is available. We don't have to use all
263 * of it.
265 largememory = (uint32_t)strtoul(argv[1], NULL, 10);
266 if (largememory > LARGE_MAXIMUM) {
267 warnx("Limited memory: %u MB; limit %lu MB.", largememory,
268 LARGE_MAXIMUM);
269 largememory = LARGE_MAXIMUM;
272 if (largewords <= (largememory << SHIFT_MEGAWORD)) {
273 warnx("Increased memory: %u MB; need %u bytes.",
274 largememory, (largewords << SHIFT_BYTE));
275 largewords = (largememory << SHIFT_MEGAWORD);
276 } else if (largememory > 0) {
277 warnx("Decreased memory: %u MB; want %u bytes.",
278 largememory, (largewords << SHIFT_BYTE));
279 largewords = (largememory << SHIFT_MEGAWORD);
282 if ((TinySieve = (uint32_t *) calloc((size_t) tinywords, sizeof(uint32_t))) == NULL) {
283 errx(1, "Insufficient memory for tiny sieve: need %u byts.",
284 tinywords << SHIFT_BYTE);
286 tinybits = tinywords << SHIFT_WORD;
288 if ((SmallSieve = (uint32_t *) calloc((size_t) smallwords, sizeof(uint32_t))) == NULL) {
289 errx(1, "Insufficient memory for small sieve: need %u bytes.",
290 smallwords << SHIFT_BYTE);
292 smallbits = smallwords << SHIFT_WORD;
295 * dynamically determine available memory
297 while ((LargeSieve = (uint32_t *)calloc((size_t)largewords,
298 sizeof(uint32_t))) == NULL) {
299 /* 1/4 MB chunks */
300 largewords -= (1L << (SHIFT_MEGAWORD - 2));
302 largebits = largewords << SHIFT_WORD;
303 largenumbers = largebits * 2; /* even numbers excluded */
305 /* validation check: count the number of primes tried */
306 largetries = 0;
308 q = BN_new();
309 largebase = BN_new();
312 * Generate random starting point for subprime search, or use
313 * specified parameter.
315 if (argc < 4) {
316 BN_rand(largebase, power, 1, 1);
317 } else {
318 BIGNUM *a;
320 a = largebase;
321 BN_hex2bn(&a, argv[2]);
324 /* ensure odd */
325 if (!BN_is_odd(largebase)) {
326 BN_set_bit(largebase, 0);
329 time(&time_start);
330 (void)fprintf(stderr,
331 "%.24s Sieve next %u plus %d-bit start point:\n# ",
332 ctime(&time_start), largenumbers, power);
333 BN_print_fp(stderr, largebase);
334 (void)fprintf(stderr, "\n");
337 * TinySieve
339 for (i = 0; i < tinybits; i++) {
340 if (BIT_TEST(TinySieve, i)) {
341 /* 2*i+3 is composite */
342 continue;
345 /* The next tiny prime */
346 t = 2 * i + 3;
348 /* Mark all multiples of t */
349 for (j = i + t; j < tinybits; j += t) {
350 BIT_SET(TinySieve, j);
353 sieve_large(t);
357 * Start the small block search at the next possible prime. To avoid
358 * fencepost errors, the last pass is skipped.
360 for (smallbase = TINY_NUMBER + 3;
361 smallbase < (SMALL_MAXIMUM - TINY_NUMBER);
362 smallbase += TINY_NUMBER) {
363 for (i = 0; i < tinybits; i++) {
364 if (BIT_TEST(TinySieve, i)) {
365 /* 2*i+3 is composite */
366 continue;
369 /* The next tiny prime */
370 t = 2 * i + 3;
371 r = smallbase % t;
373 if (r == 0) {
374 /* t divides into smallbase exactly */
375 s = 0;
376 } else {
377 /* smallbase+s is first entry divisible by t */
378 s = t - r;
382 * The sieve omits even numbers, so ensure that
383 * smallbase+s is odd. Then, step through the sieve in
384 * increments of 2*t
386 if (s & 1) {
387 /* Make smallbase+s odd, and s even */
388 s += t;
391 /* Mark all multiples of 2*t */
392 for (s /= 2; s < smallbits; s += t) {
393 BIT_SET(SmallSieve, s);
398 * SmallSieve
400 for (i = 0; i < smallbits; i++) {
401 if (BIT_TEST(SmallSieve, i)) {
402 /* 2*i+smallbase is composite */
403 continue;
406 /* The next small prime */
407 sieve_large((2 * i) + smallbase);
410 memset(SmallSieve, 0, (size_t)(smallwords << SHIFT_BYTE));
413 time(&time_stop);
414 (void)fprintf(stderr,
415 "%.24s Sieved with %u small primes in %lu seconds\n",
416 ctime(&time_stop), largetries,
417 (long) (time_stop - time_start));
419 for (j = r = 0; j < largebits; j++) {
420 if (BIT_TEST(LargeSieve, j)) {
421 /* Definitely composite, skip */
422 continue;
425 #ifdef DEBUG_LARGE
426 (void)fprintf(stderr, "test q = largebase+%lu\n", 2 * j);
427 #endif
429 BN_set_word(q, (unsigned long)(2 * j));
430 BN_add(q, q, largebase);
432 if (0 > qfileout(stdout,
433 (uint32_t) QTYPE_SOPHIE_GERMAINE,
434 (uint32_t) QTEST_SIEVE,
435 largetries,
436 (uint32_t) (power - 1), /* MSB */
437 (uint32_t) (0), /* generator unknown */
438 q)) {
439 break;
442 r++; /* count q */
445 time(&time_stop);
447 free(LargeSieve);
448 free(SmallSieve);
449 free(TinySieve);
451 fflush(stdout);
452 /* fclose(stdout); */
454 (void) fprintf(stderr, "%.24s Found %u candidates\n",
455 ctime(&time_stop), r);
457 return (0);
460 static void
461 usage(void)
463 (void)fprintf(stderr, "Usage: %s <megabytes> <bits> [initial]\n"
464 "Possible values for <megabytes>: 0, %lu to %lu\n"
465 "Possible values for <bits>: %lu to %lu\n",
466 getprogname(),
467 LARGE_MINIMUM,
468 LARGE_MAXIMUM,
469 (unsigned long) TEST_MINIMUM,
470 (unsigned long) TEST_MAXIMUM);
472 exit(1);