~ubuntu-branches/ubuntu/oneiric/gnupg2/oneiric-updates

« back to all changes in this revision

Viewing changes to cipher/primegen.c

  • Committer: Bazaar Package Importer
  • Author(s): Thomas Viehmann
  • Date: 2008-10-04 10:25:53 UTC
  • mfrom: (5.1.15 intrepid)
  • Revision ID: james.westby@ubuntu.com-20081004102553-fv62pp8dsitxli47
Tags: 2.0.9-3.1
* Non-maintainer upload.
* agent/gpg-agent.c: Deinit the threading library before exec'ing
  the command to run in --daemon mode. And because that still doesn't
  restore the sigprocmask, do that manually. Closes: #499569

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* primegen.c - prime number generator
2
 
 *      Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3
 
 *
4
 
 * This file is part of GnuPG.
5
 
 *
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.
10
 
 *
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.
15
 
 *
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
19
 
 *
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)
23
 
 * page 260.
24
 
 */
25
 
 
26
 
#include <config.h>
27
 
#include <stdio.h>
28
 
#include <stdlib.h>
29
 
#include <string.h>
30
 
#include <assert.h>
31
 
#include "util.h"
32
 
#include "mpi.h"
33
 
#include "cipher.h"
34
 
 
35
 
static int no_of_small_prime_numbers;
36
 
static MPI gen_prime( unsigned  nbits, int mode, int randomlevel );
37
 
static int check_prime( MPI prime, MPI val_2 );
38
 
static int is_prime( MPI n, int steps, int *count );
39
 
static void m_out_of_n( char *array, int m, int n );
40
 
 
41
 
static void (*progress_cb) ( void *, int );
42
 
static void *progress_cb_data;
43
 
 
44
 
void
45
 
register_primegen_progress ( void (*cb)( void *, int), void *cb_data )
46
 
{
47
 
    progress_cb = cb;
48
 
    progress_cb_data = cb_data;
49
 
}
50
 
 
51
 
 
52
 
static void
53
 
progress( int c )
54
 
{
55
 
    if ( progress_cb )
56
 
        progress_cb ( progress_cb_data, c );
57
 
    else
58
 
        fputc( c, stderr );
59
 
}
60
 
 
61
 
 
62
 
/****************
63
 
 * Generate a prime number (stored in secure memory)
64
 
 */
65
 
MPI
66
 
generate_secret_prime( unsigned  nbits )
67
 
{
68
 
    MPI prime;
69
 
 
70
 
    prime = gen_prime( nbits, 1, 2 );
71
 
    progress('\n');
72
 
    return prime;
73
 
}
74
 
 
75
 
MPI
76
 
generate_public_prime( unsigned  nbits )
77
 
{
78
 
    MPI prime;
79
 
 
80
 
    prime = gen_prime( nbits, 0, 2 );
81
 
    progress('\n');
82
 
    return prime;
83
 
}
84
 
 
85
 
 
86
 
/****************
87
 
 * We do not need to use the strongest RNG because we gain no extra
88
 
 * security from it - The prime number is public and we could also
89
 
 * offer the factors for those who are willing to check that it is
90
 
 * indeed a strong prime.
91
 
 *
92
 
 * mode 0: Standard
93
 
 *      1: Make sure that at least one factor is of size qbits.
94
 
 */
95
 
MPI
96
 
generate_elg_prime( int mode, unsigned pbits, unsigned qbits,
97
 
                    MPI g, MPI **ret_factors )
98
 
{
99
 
    int n;  /* number of factors */
100
 
    int m;  /* number of primes in pool */
101
 
    unsigned fbits; /* length of prime factors */
102
 
    MPI *factors; /* current factors */
103
 
    MPI *pool;  /* pool of primes */
104
 
    MPI q;      /* first prime factor (variable)*/
105
 
    MPI prime;  /* prime test value */
106
 
    MPI q_factor; /* used for mode 1 */
107
 
    byte *perms = NULL;
108
 
    int i, j;
109
 
    int count1, count2;
110
 
    unsigned nprime;
111
 
    unsigned req_qbits = qbits; /* the requested q bits size */
112
 
    MPI val_2  = mpi_alloc_set_ui( 2 );
113
 
 
114
 
    /* find number of needed prime factors */
115
 
    for(n=1; (pbits - qbits - 1) / n  >= qbits; n++ )
116
 
        ;
117
 
    n--;
118
 
    if( !n || (mode==1 && n < 2) )
119
 
        log_fatal("can't gen prime with pbits=%u qbits=%u\n", pbits, qbits );
120
 
    if( mode == 1 ) {
121
 
        n--;
122
 
        fbits = (pbits - 2*req_qbits -1) / n;
123
 
        qbits =  pbits - req_qbits - n*fbits;
124
 
    }
125
 
    else {
126
 
        fbits = (pbits - req_qbits -1) / n;
127
 
        qbits = pbits - n*fbits;
128
 
    }
129
 
    if( DBG_CIPHER )
130
 
        log_debug("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n",
131
 
                    pbits, req_qbits, qbits, fbits, n  );
132
 
    prime = mpi_alloc( (pbits + BITS_PER_MPI_LIMB - 1) /  BITS_PER_MPI_LIMB );
133
 
    q = gen_prime( qbits, 0, 0 );
134
 
    q_factor = mode==1? gen_prime( req_qbits, 0, 0 ) : NULL;
135
 
 
136
 
    /* allocate an array to hold the factors + 2 for later usage */
137
 
    factors = m_alloc_clear( (n+2) * sizeof *factors );
138
 
 
139
 
    /* make a pool of 3n+5 primes (this is an arbitrary value) */
140
 
    m = n*3+5;
141
 
    if( mode == 1 )
142
 
        m += 5; /* need some more for DSA */
143
 
    if( m < 25 )
144
 
        m = 25;
145
 
    pool = m_alloc_clear( m * sizeof *pool );
146
 
 
147
 
    /* permutate over the pool of primes */
148
 
    count1=count2=0;
149
 
    do {
150
 
      next_try:
151
 
        if( !perms ) {
152
 
            /* allocate new primes */
153
 
            for(i=0; i < m; i++ ) {
154
 
                mpi_free(pool[i]);
155
 
                pool[i] = NULL;
156
 
            }
157
 
            /* init m_out_of_n() */
158
 
            perms = m_alloc_clear( m );
159
 
            for(i=0; i < n; i++ ) {
160
 
                perms[i] = 1;
161
 
                pool[i] = gen_prime( fbits, 0, 0 );
162
 
                factors[i] = pool[i];
163
 
            }
164
 
        }
165
 
        else {
166
 
            m_out_of_n( perms, n, m );
167
 
            for(i=j=0; i < m && j < n ; i++ )
168
 
                if( perms[i] ) {
169
 
                    if( !pool[i] )
170
 
                        pool[i] = gen_prime( fbits, 0, 0 );
171
 
                    factors[j++] = pool[i];
172
 
                }
173
 
            if( i == n ) {
174
 
                m_free(perms); perms = NULL;
175
 
                progress('!');
176
 
                goto next_try;  /* allocate new primes */
177
 
            }
178
 
        }
179
 
 
180
 
        mpi_set( prime, q );
181
 
        mpi_mul_ui( prime, prime, 2 );
182
 
        if( mode == 1 )
183
 
            mpi_mul( prime, prime, q_factor );
184
 
        for(i=0; i < n; i++ )
185
 
            mpi_mul( prime, prime, factors[i] );
186
 
        mpi_add_ui( prime, prime, 1 );
187
 
        nprime = mpi_get_nbits(prime);
188
 
        if( nprime < pbits ) {
189
 
            if( ++count1 > 20 ) {
190
 
                count1 = 0;
191
 
                qbits++;
192
 
                progress('>');
193
 
                mpi_free (q);
194
 
                q = gen_prime( qbits, 0, 0 );
195
 
                goto next_try;
196
 
            }
197
 
        }
198
 
        else
199
 
            count1 = 0;
200
 
        if( nprime > pbits ) {
201
 
            if( ++count2 > 20 ) {
202
 
                count2 = 0;
203
 
                qbits--;
204
 
                progress('<');
205
 
                mpi_free (q);
206
 
                q = gen_prime( qbits, 0, 0 );
207
 
                goto next_try;
208
 
            }
209
 
        }
210
 
        else
211
 
            count2 = 0;
212
 
    } while( !(nprime == pbits && check_prime( prime, val_2 )) );
213
 
 
214
 
    if( DBG_CIPHER ) {
215
 
        progress('\n');
216
 
        log_mpidump( "prime    : ", prime );
217
 
        log_mpidump( "factor  q: ", q );
218
 
        if( mode == 1 )
219
 
            log_mpidump( "factor q0: ", q_factor );
220
 
        for(i=0; i < n; i++ )
221
 
            log_mpidump( "factor pi: ", factors[i] );
222
 
        log_debug("bit sizes: prime=%u, q=%u", mpi_get_nbits(prime), mpi_get_nbits(q) );
223
 
        if( mode == 1 )
224
 
            fprintf(stderr, ", q0=%u", mpi_get_nbits(q_factor) );
225
 
        for(i=0; i < n; i++ )
226
 
            fprintf(stderr, ", p%d=%u", i, mpi_get_nbits(factors[i]) );
227
 
        progress('\n');
228
 
    }
229
 
 
230
 
    if( ret_factors ) { /* caller wants the factors */
231
 
        *ret_factors = m_alloc_clear( (n+2) * sizeof **ret_factors);
232
 
        i = 0;
233
 
        if( mode == 1 ) {
234
 
            (*ret_factors)[i++] = mpi_copy( q_factor );
235
 
            for(; i <= n; i++ )
236
 
                (*ret_factors)[i] = mpi_copy( factors[i-1] );
237
 
        }
238
 
        else {
239
 
            for(; i < n; i++ )
240
 
                (*ret_factors)[i] = mpi_copy( factors[i] );
241
 
        }
242
 
    }
243
 
 
244
 
    if( g ) { /* create a generator (start with 3)*/
245
 
        MPI tmp   = mpi_alloc( mpi_get_nlimbs(prime) );
246
 
        MPI b     = mpi_alloc( mpi_get_nlimbs(prime) );
247
 
        MPI pmin1 = mpi_alloc( mpi_get_nlimbs(prime) );
248
 
 
249
 
        if( mode == 1 )
250
 
            BUG(); /* not yet implemented */
251
 
        factors[n] = q;
252
 
        factors[n+1] = mpi_alloc_set_ui(2);
253
 
        mpi_sub_ui( pmin1, prime, 1 );
254
 
        mpi_set_ui(g,2);
255
 
        do {
256
 
            mpi_add_ui(g, g, 1);
257
 
            if( DBG_CIPHER ) {
258
 
                log_debug("checking g: ");
259
 
                mpi_print( stderr, g, 1 );
260
 
            }
261
 
            else
262
 
                progress('^');
263
 
            for(i=0; i < n+2; i++ ) {
264
 
                /*fputc('~', stderr);*/
265
 
                mpi_fdiv_q(tmp, pmin1, factors[i] );
266
 
                /* (no mpi_pow(), but it is okay to use this with mod prime) */
267
 
                mpi_powm(b, g, tmp, prime );
268
 
                if( !mpi_cmp_ui(b, 1) )
269
 
                    break;
270
 
            }
271
 
            if( DBG_CIPHER )
272
 
                progress('\n');
273
 
        } while( i < n+2 );
274
 
        mpi_free(factors[n+1]);
275
 
        mpi_free(tmp);
276
 
        mpi_free(b);
277
 
        mpi_free(pmin1);
278
 
    }
279
 
    if( !DBG_CIPHER )
280
 
        progress('\n');
281
 
 
282
 
    m_free( factors );  /* (factors are shallow copies) */
283
 
    for(i=0; i < m; i++ )
284
 
        mpi_free( pool[i] );
285
 
    m_free( pool );
286
 
    m_free(perms);
287
 
    mpi_free(val_2);
288
 
    mpi_free(q);
289
 
    return prime;
290
 
}
291
 
 
292
 
 
293
 
 
294
 
static MPI
295
 
gen_prime( unsigned  nbits, int secret, int randomlevel )
296
 
{
297
 
    unsigned  nlimbs;
298
 
    MPI prime, ptest, pminus1, val_2, val_3, result;
299
 
    int i;
300
 
    unsigned x, step;
301
 
    int count1, count2;
302
 
    int *mods;
303
 
 
304
 
    if( 0 && DBG_CIPHER )
305
 
        log_debug("generate a prime of %u bits ", nbits );
306
 
 
307
 
    if( !no_of_small_prime_numbers ) {
308
 
        for(i=0; small_prime_numbers[i]; i++ )
309
 
            no_of_small_prime_numbers++;
310
 
    }
311
 
    mods = m_alloc( no_of_small_prime_numbers * sizeof *mods );
312
 
    /* make nbits fit into MPI implementation */
313
 
    nlimbs = (nbits + BITS_PER_MPI_LIMB - 1) /  BITS_PER_MPI_LIMB;
314
 
    val_2  = mpi_alloc_set_ui( 2 );
315
 
    val_3 = mpi_alloc_set_ui( 3);
316
 
    prime  = secret? mpi_alloc_secure( nlimbs ): mpi_alloc( nlimbs );
317
 
    result = mpi_alloc_like( prime );
318
 
    pminus1= mpi_alloc_like( prime );
319
 
    ptest  = mpi_alloc_like( prime );
320
 
    count1 = count2 = 0;
321
 
    for(;;) {  /* try forvever */
322
 
        int dotcount=0;
323
 
 
324
 
        /* generate a random number */
325
 
        {   char *p = get_random_bits( nbits, randomlevel, secret );
326
 
            mpi_set_buffer( prime, p, (nbits+7)/8, 0 );
327
 
            m_free(p);
328
 
        }
329
 
 
330
 
        /* Set high order bit to 1, set low order bit to 0.
331
 
           If we are generating a secret prime we are most probably
332
 
           doing that for RSA, to make sure that the modulus does have
333
 
           the requested keysize we set the 2 high order bits */
334
 
        mpi_set_highbit( prime, nbits-1 );
335
 
        if (secret)
336
 
          mpi_set_bit (prime, nbits-2);
337
 
        mpi_set_bit( prime, 0 );
338
 
 
339
 
        /* calculate all remainders */
340
 
        for(i=0; (x = small_prime_numbers[i]); i++ )
341
 
            mods[i] = mpi_fdiv_r_ui(NULL, prime, x);
342
 
 
343
 
        /* now try some primes starting with prime */
344
 
        for(step=0; step < 20000; step += 2 ) {
345
 
            /* check against all the small primes we have in mods */
346
 
            count1++;
347
 
            for(i=0; (x = small_prime_numbers[i]); i++ ) {
348
 
                while( mods[i] + step >= x )
349
 
                    mods[i] -= x;
350
 
                if( !(mods[i] + step) )
351
 
                    break;
352
 
            }
353
 
            if( x )
354
 
                continue;   /* found a multiple of an already known prime */
355
 
 
356
 
            mpi_add_ui( ptest, prime, step );
357
 
 
358
 
            /* do a faster Fermat test */
359
 
            count2++;
360
 
            mpi_sub_ui( pminus1, ptest, 1);
361
 
            mpi_powm( result, val_2, pminus1, ptest );
362
 
            if( !mpi_cmp_ui( result, 1 ) ) { /* not composite */
363
 
                /* perform stronger tests */
364
 
                if( is_prime(ptest, 5, &count2 ) ) {
365
 
                    if( !mpi_test_bit( ptest, nbits-1 ) ) {
366
 
                        progress('\n');
367
 
                        log_debug("overflow in prime generation\n");
368
 
                        break; /* step loop, continue with a new prime */
369
 
                    }
370
 
 
371
 
                    mpi_free(val_2);
372
 
                    mpi_free(val_3);
373
 
                    mpi_free(result);
374
 
                    mpi_free(pminus1);
375
 
                    mpi_free(prime);
376
 
                    m_free(mods);
377
 
                    return ptest;
378
 
                }
379
 
            }
380
 
            if( ++dotcount == 10 ) {
381
 
                progress('.');
382
 
                dotcount = 0;
383
 
            }
384
 
        }
385
 
        progress(':'); /* restart with a new random value */
386
 
    }
387
 
}
388
 
 
389
 
/****************
390
 
 * Returns: true if this may be a prime
391
 
 */
392
 
static int
393
 
check_prime( MPI prime, MPI val_2 )
394
 
{
395
 
    int i;
396
 
    unsigned x;
397
 
    int count=0;
398
 
 
399
 
    /* check against small primes */
400
 
    for(i=0; (x = small_prime_numbers[i]); i++ ) {
401
 
        if( mpi_divisible_ui( prime, x ) )
402
 
            return 0;
403
 
    }
404
 
 
405
 
    /* a quick fermat test */
406
 
    {
407
 
        MPI result = mpi_alloc_like( prime );
408
 
        MPI pminus1 = mpi_alloc_like( prime );
409
 
        mpi_sub_ui( pminus1, prime, 1);
410
 
        mpi_powm( result, val_2, pminus1, prime );
411
 
        mpi_free( pminus1 );
412
 
        if( mpi_cmp_ui( result, 1 ) ) { /* if composite */
413
 
            mpi_free( result );
414
 
            progress('.');
415
 
            return 0;
416
 
        }
417
 
        mpi_free( result );
418
 
    }
419
 
 
420
 
    /* perform stronger tests */
421
 
    if( is_prime(prime, 5, &count ) )
422
 
        return 1; /* is probably a prime */
423
 
    progress('.');
424
 
    return 0;
425
 
}
426
 
 
427
 
 
428
 
/****************
429
 
 * Return true if n is probably a prime
430
 
 */
431
 
static int
432
 
is_prime( MPI n, int steps, int *count )
433
 
{
434
 
    MPI x = mpi_alloc( mpi_get_nlimbs( n ) );
435
 
    MPI y = mpi_alloc( mpi_get_nlimbs( n ) );
436
 
    MPI z = mpi_alloc( mpi_get_nlimbs( n ) );
437
 
    MPI nminus1 = mpi_alloc( mpi_get_nlimbs( n ) );
438
 
    MPI a2 = mpi_alloc_set_ui( 2 );
439
 
    MPI q;
440
 
    unsigned i, j, k;
441
 
    int rc = 0;
442
 
    unsigned nbits = mpi_get_nbits( n );
443
 
 
444
 
    mpi_sub_ui( nminus1, n, 1 );
445
 
 
446
 
    /* find q and k, so that n = 1 + 2^k * q */
447
 
    q = mpi_copy( nminus1 );
448
 
    k = mpi_trailing_zeros( q );
449
 
    mpi_tdiv_q_2exp(q, q, k);
450
 
 
451
 
    for(i=0 ; i < steps; i++ ) {
452
 
        ++*count;
453
 
        if( !i ) {
454
 
            mpi_set_ui( x, 2 );
455
 
        }
456
 
        else {
457
 
            /*mpi_set_bytes( x, nbits-1, get_random_byte, 0 );*/
458
 
            {   char *p = get_random_bits( nbits, 0, 0 );
459
 
                mpi_set_buffer( x, p, (nbits+7)/8, 0 );
460
 
                m_free(p);
461
 
            }
462
 
            /* make sure that the number is smaller than the prime
463
 
             * and keep the randomness of the high bit */
464
 
            if( mpi_test_bit( x, nbits-2 ) ) {
465
 
                mpi_set_highbit( x, nbits-2 ); /* clear all higher bits */
466
 
            }
467
 
            else {
468
 
                mpi_set_highbit( x, nbits-2 );
469
 
                mpi_clear_bit( x, nbits-2 );
470
 
            }
471
 
            assert( mpi_cmp( x, nminus1 ) < 0 && mpi_cmp_ui( x, 1 ) > 0 );
472
 
        }
473
 
        mpi_powm( y, x, q, n);
474
 
        if( mpi_cmp_ui(y, 1) && mpi_cmp( y, nminus1 ) ) {
475
 
            for( j=1; j < k && mpi_cmp( y, nminus1 ); j++ ) {
476
 
                mpi_powm(y, y, a2, n);
477
 
                if( !mpi_cmp_ui( y, 1 ) )
478
 
                    goto leave; /* not a prime */
479
 
            }
480
 
            if( mpi_cmp( y, nminus1 ) )
481
 
                goto leave; /* not a prime */
482
 
        }
483
 
        progress('+');
484
 
    }
485
 
    rc = 1; /* may be a prime */
486
 
 
487
 
  leave:
488
 
    mpi_free( x );
489
 
    mpi_free( y );
490
 
    mpi_free( z );
491
 
    mpi_free( nminus1 );
492
 
    mpi_free( q );
493
 
 
494
 
    return rc;
495
 
}
496
 
 
497
 
 
498
 
static void
499
 
m_out_of_n( char *array, int m, int n )
500
 
{
501
 
    int i=0, i1=0, j=0, jp=0,  j1=0, k1=0, k2=0;
502
 
 
503
 
    if( !m || m >= n )
504
 
        return;
505
 
 
506
 
    if( m == 1 ) { /* special case */
507
 
        for(i=0; i < n; i++ )
508
 
            if( array[i] ) {
509
 
                array[i++] = 0;
510
 
                if( i >= n )
511
 
                    i = 0;
512
 
                array[i] = 1;
513
 
                return;
514
 
            }
515
 
        BUG();
516
 
    }
517
 
 
518
 
    for(j=1; j < n; j++ ) {
519
 
        if( array[n-1] == array[n-j-1] )
520
 
            continue;
521
 
        j1 = j;
522
 
        break;
523
 
    }
524
 
 
525
 
    if( m & 1 ) { /* m is odd */
526
 
        if( array[n-1] ) {
527
 
            if( j1 & 1 ) {
528
 
                k1 = n - j1;
529
 
                k2 = k1+2;
530
 
                if( k2 > n )
531
 
                    k2 = n;
532
 
                goto leave;
533
 
            }
534
 
            goto scan;
535
 
        }
536
 
        k2 = n - j1 - 1;
537
 
        if( k2 == 0 ) {
538
 
            k1 = i;
539
 
            k2 = n - j1;
540
 
        }
541
 
        else if( array[k2] && array[k2-1] )
542
 
            k1 = n;
543
 
        else
544
 
            k1 = k2 + 1;
545
 
    }
546
 
    else { /* m is even */
547
 
        if( !array[n-1] ) {
548
 
            k1 = n - j1;
549
 
            k2 = k1 + 1;
550
 
            goto leave;
551
 
        }
552
 
 
553
 
        if( !(j1 & 1) ) {
554
 
            k1 = n - j1;
555
 
            k2 = k1+2;
556
 
            if( k2 > n )
557
 
                k2 = n;
558
 
            goto leave;
559
 
        }
560
 
      scan:
561
 
        jp = n - j1 - 1;
562
 
        for(i=1; i <= jp; i++ ) {
563
 
            i1 = jp + 2 - i;
564
 
            if( array[i1-1]  ) {
565
 
                if( array[i1-2] ) {
566
 
                    k1 = i1 - 1;
567
 
                    k2 = n - j1;
568
 
                }
569
 
                else {
570
 
                    k1 = i1 - 1;
571
 
                    k2 = n + 1 - j1;
572
 
                }
573
 
                goto leave;
574
 
            }
575
 
        }
576
 
        k1 = 1;
577
 
        k2 = n + 1 - m;
578
 
    }
579
 
  leave:
580
 
    array[k1-1] = !array[k1-1];
581
 
    array[k2-1] = !array[k2-1];
582
 
}
583