1 /* primegen.c - prime number generator
2 * Copyright (C) 1998 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20 * ***********************************************************************
21 * The algorithm used to generate practically save primes is due to
22 * Lim and Lee as described in the CRYPTO '97 proceedings (ISBN3540633847)
33 #include "constants.h"
37 #include "gcryptfix.h"
39 /* #include <assert.h> */
40 /* #include <config.h> */
41 /* #include "util.h" */
42 /* #include "mpi.h" */
43 /* #include "cipher.h" */
46 static int no_of_small_prime_numbers;
47 static MPI gen_prime( unsigned nbits, int mode, int randomlevel );
48 static int check_prime( MPI prime, MPI val_2 );
49 static int is_prime( MPI n, unsigned steps, int *count );
50 static void m_out_of_n( char *array, int m, int n );
61 * Generate a prime number (stored in secure memory)
64 generate_secret_prime( unsigned nbits )
68 prime = gen_prime( nbits, 1, 2 );
74 generate_public_prime( unsigned nbits )
78 prime = gen_prime( nbits, 0, 2 );
85 * We do not need to use the strongest RNG because we gain no extra
86 * security from it - The prime number is public and we could also
87 * offer the factors for those who are willing to check that it is
88 * indeed a strong prime.
91 * 1: Make sure that at least one factor is of size qbits.
94 generate_elg_prime( int mode, unsigned pbits, unsigned qbits,
95 MPI g, MPI **ret_factors )
97 int n; /* number of factors */
98 int m; /* number of primes in pool */
99 unsigned fbits; /* length of prime factors */
100 MPI *factors; /* current factors */
101 MPI *pool; /* pool of primes */
102 MPI q; /* first prime factor (variable)*/
103 MPI prime; /* prime test value */
104 MPI q_factor; /* used for mode 1 */
109 unsigned req_qbits = qbits; /* the requested q bits size */
110 MPI val_2 = mpi_alloc_set_ui( 2 );
112 /* find number of needed prime factors */
113 for(n=1; (pbits - qbits - 1) / n >= qbits; n++ )
116 if( !n || (mode==1 && n < 2) )
117 log_fatal("can't gen prime with pbits=%u qbits=%u\n", pbits, qbits );
120 fbits = (pbits - 2*req_qbits -1) / n;
121 qbits = pbits - req_qbits - n*fbits;
124 fbits = (pbits - req_qbits -1) / n;
125 qbits = pbits - n*fbits;
128 log_debug("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n",
129 pbits, req_qbits, qbits, fbits, n );
130 prime = mpi_alloc( (pbits + BITS_PER_MPI_LIMB - 1) / BITS_PER_MPI_LIMB );
131 q = gen_prime( qbits, 0, 1 );
132 q_factor = mode==1? gen_prime( req_qbits, 0, 1 ) : NULL;
134 /* allocate an array to hold the factors + 2 for later usage */
136 m_alloc_ptrs_clear(factors, n+2);
138 factors = m_alloc_clear( (n+2) * sizeof *factors );
141 /* make a pool of 3n+5 primes (this is an arbitrary value) */
144 m += 5; /* need some more for DSA */
148 m_alloc_ptrs_clear(pool, m);
150 pool = m_alloc_clear( m * sizeof *pool );
153 /* permutate over the pool of primes */
158 /* allocate new primes */
159 for(i=0; i < m; i++ ) {
163 /* init m_out_of_n() */
165 perms = alloc_bytes( m, "perms" );
167 perms = m_alloc_clear( m );
169 for(i=0; i < n; i++ ) {
171 pool[i] = gen_prime( fbits, 0, 1 );
172 factors[i] = pool[i];
176 m_out_of_n( perms, n, m );
177 for(i=j=0; i < m && j < n ; i++ )
180 pool[i] = gen_prime( fbits, 0, 1 );
181 factors[j++] = pool[i];
184 m_free(perms); perms = NULL;
186 goto next_try; /* allocate new primes */
191 mpi_mul_ui( prime, prime, 2 );
193 mpi_mul( prime, prime, q_factor );
194 for(i=0; i < n; i++ )
195 mpi_mul( prime, prime, factors[i] );
196 mpi_add_ui( prime, prime, 1 );
197 nprime = mpi_get_nbits(prime);
198 if( nprime < pbits ) {
199 if( ++count1 > 20 ) {
203 q = gen_prime( qbits, 0, 1 );
209 if( nprime > pbits ) {
210 if( ++count2 > 20 ) {
214 q = gen_prime( qbits, 0, 1 );
220 } while( !(nprime == pbits && check_prime( prime, val_2 )) );
224 log_mpidump( "prime : ", prime );
225 log_mpidump( "factor q: ", q );
227 log_mpidump( "factor q0: ", q_factor );
228 for(i=0; i < n; i++ )
229 log_mpidump( "factor pi: ", factors[i] );
230 log_debug("bit sizes: prime=%u, q=%u", mpi_get_nbits(prime), mpi_get_nbits(q) );
232 fprintf(stderr, ", q0=%u", mpi_get_nbits(q_factor) );
233 for(i=0; i < n; i++ )
234 fprintf(stderr, ", p%d=%u", i, mpi_get_nbits(factors[i]) );
238 if( ret_factors ) { /* caller wants the factors */
240 m_alloc_ptrs_clear(*ret_factors, n+2);
242 *ret_factors = m_alloc_clear( (n+2) * sizeof **ret_factors);
246 (*ret_factors)[i++] = mpi_copy( q_factor );
248 (*ret_factors)[i] = mpi_copy( factors[i] );
252 (*ret_factors)[i] = mpi_copy( factors[i] );
256 if( g ) { /* create a generator (start with 3)*/
257 MPI tmp = mpi_alloc( mpi_get_nlimbs(prime) );
258 MPI b = mpi_alloc( mpi_get_nlimbs(prime) );
259 MPI pmin1 = mpi_alloc( mpi_get_nlimbs(prime) );
262 BUG(); /* not yet implemented */
264 factors[n+1] = mpi_alloc_set_ui(2);
265 mpi_sub_ui( pmin1, prime, 1 );
271 log_mpidump("checking g: ", g);
273 log_debug("checking g: ");
274 mpi_print( stderr, g, 1 );
279 for(i=0; i < n+2; i++ ) {
280 /*fputc('~', stderr);*/
281 mpi_fdiv_q(tmp, pmin1, factors[i] );
282 /* (no mpi_pow(), but it is okay to use this with mod prime) */
283 mpi_powm(b, g, tmp, prime );
284 if( !mpi_cmp_ui(b, 1) )
290 mpi_free(factors[n+1]);
298 m_free( factors ); /* (factors are shallow copies) */
299 for(i=0; i < m; i++ )
310 gen_prime( unsigned nbits, int secret, int randomlevel )
313 MPI prime, ptest, pminus1, val_2, val_3, result;
316 unsigned count1, count2;
319 if( 0 && DBG_CIPHER )
320 log_debug("generate a prime of %u bits ", nbits );
322 if( !no_of_small_prime_numbers ) {
323 for(i=0; small_prime_numbers[i]; i++ )
324 no_of_small_prime_numbers++;
326 mods = m_alloc( no_of_small_prime_numbers * sizeof *mods );
327 /* make nbits fit into MPI implementation */
328 nlimbs = (nbits + BITS_PER_MPI_LIMB - 1) / BITS_PER_MPI_LIMB;
329 val_2 = mpi_alloc_set_ui( 2 );
330 val_3 = mpi_alloc_set_ui( 3);
331 prime = secret? mpi_alloc_secure( nlimbs ): mpi_alloc( nlimbs );
332 result = mpi_alloc_like( prime );
333 pminus1= mpi_alloc_like( prime );
334 ptest = mpi_alloc_like( prime );
336 for(;;) { /* try forvever */
339 /* generate a random number */
340 { char *p = get_random_bits( nbits, randomlevel, secret );
341 mpi_set_buffer( prime, p, (nbits+7)/8, 0 );
345 /* set high order bit to 1, set low order bit to 1 */
346 mpi_set_highbit( prime, nbits-1 );
347 mpi_set_bit( prime, 0 );
349 /* calculate all remainders */
350 for(i=0; (x = small_prime_numbers[i]); i++ )
351 mods[i] = mpi_fdiv_r_ui(NULL, prime, x);
353 /* now try some primes starting with prime */
354 for(step=0; step < 20000; step += 2 ) {
355 /* check against all the small primes we have in mods */
357 for(i=0; (x = small_prime_numbers[i]); i++ ) {
358 while( mods[i] + step >= x )
360 if( !(mods[i] + step) )
364 continue; /* found a multiple of an already known prime */
366 mpi_add_ui( ptest, prime, step );
368 /* do a faster Fermat test */
370 mpi_sub_ui( pminus1, ptest, 1);
371 mpi_powm( result, val_2, pminus1, ptest );
372 if( !mpi_cmp_ui( result, 1 ) ) { /* not composite */
373 /* perform stronger tests */
374 if( is_prime(ptest, 5, &count2 ) ) {
375 if( !mpi_test_bit( ptest, nbits-1 ) ) {
377 log_debug("overflow in prime generation\n");
378 break; /* step loop, continue with a new prime */
390 if( ++dotcount == 10 ) {
395 progress(':'); /* restart with a new random value */
400 * Returns: true if this may be a prime
403 check_prime( MPI prime, MPI val_2 )
409 /* check against small primes */
410 for(i=0; (x = small_prime_numbers[i]); i++ ) {
411 if( mpi_divisible_ui( prime, x ) )
415 /* a quick fermat test */
417 MPI result = mpi_alloc_like( prime );
418 MPI pminus1 = mpi_alloc_like( prime );
419 mpi_sub_ui( pminus1, prime, 1);
420 mpi_powm( result, val_2, pminus1, prime );
422 if( mpi_cmp_ui( result, 1 ) ) { /* if composite */
430 /* perform stronger tests */
431 if( is_prime(prime, 5, &count ) )
432 return 1; /* is probably a prime */
439 * Return true if n is probably a prime
442 is_prime( MPI n, unsigned steps, int *count )
444 MPI x = mpi_alloc( mpi_get_nlimbs( n ) );
445 MPI y = mpi_alloc( mpi_get_nlimbs( n ) );
446 MPI z = mpi_alloc( mpi_get_nlimbs( n ) );
447 MPI nminus1 = mpi_alloc( mpi_get_nlimbs( n ) );
448 MPI a2 = mpi_alloc_set_ui( 2 );
452 unsigned nbits = mpi_get_nbits( n );
454 mpi_sub_ui( nminus1, n, 1 );
456 /* find q and k, so that n = 1 + 2^k * q */
457 q = mpi_copy( nminus1 );
458 k = mpi_trailing_zeros( q );
459 mpi_tdiv_q_2exp(q, q, k);
461 for(i=0 ; i < steps; i++ ) {
467 /*mpi_set_bytes( x, nbits-1, get_random_byte, 0 );*/
468 { char *p = get_random_bits( nbits, 0, 0 );
469 mpi_set_buffer( x, p, (nbits+7)/8, 0 );
472 /* make sure that the number is smaller than the prime
473 * and keep the randomness of the high bit */
474 if( mpi_test_bit( x, nbits-2 ) ) {
475 mpi_set_highbit( x, nbits-2 ); /* clear all higher bits */
478 mpi_set_highbit( x, nbits-2 );
479 mpi_clear_bit( x, nbits-2 );
481 assert( mpi_cmp( x, nminus1 ) < 0 && mpi_cmp_ui( x, 1 ) > 0 );
483 mpi_powm( y, x, q, n);
484 if( mpi_cmp_ui(y, 1) && mpi_cmp( y, nminus1 ) ) {
485 for( j=1; j < k && mpi_cmp( y, nminus1 ); j++ ) {
486 mpi_powm(y, y, a2, n);
487 if( !mpi_cmp_ui( y, 1 ) )
488 goto leave; /* not a prime */
490 if( mpi_cmp( y, nminus1 ) )
491 goto leave; /* not a prime */
495 rc = 1; /* may be a prime */
509 m_out_of_n( char *array, int m, int n )
511 int i=0, i1=0, j=0, jp=0, j1=0, k1=0, k2=0;
516 if( m == 1 ) { /* special case */
517 for(i=0; i < n; i++ )
528 for(j=1; j < n; j++ ) {
529 if( array[n-1] == array[n-j-1] )
535 if( m & 1 ) { /* m is odd */
551 else if( array[k2] && array[k2-1] )
556 else { /* m is even */
572 for(i=1; i <= jp; i++ ) {
590 array[k1-1] = !array[k1-1];
591 array[k2-1] = !array[k2-1];