Coverage Report

Created: 2022-12-08 06:09

/src/libgcrypt/cipher/primegen.c
Line
Count
Source (jump to first uncovered line)
1
/* primegen.c - prime number generator
2
 * Copyright (C) 1998, 2000, 2001, 2002, 2003
3
 *               2004, 2008 Free Software Foundation, Inc.
4
 *
5
 * This file is part of Libgcrypt.
6
 *
7
 * Libgcrypt is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU Lesser general Public License as
9
 * published by the Free Software Foundation; either version 2.1 of
10
 * the License, or (at your option) any later version.
11
 *
12
 * Libgcrypt is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
20
 */
21
22
#include <config.h>
23
24
#include <stdio.h>
25
#include <stdlib.h>
26
#include <string.h>
27
#include <errno.h>
28
29
#include "g10lib.h"
30
#include "mpi.h"
31
#include "cipher.h"
32
33
static gcry_mpi_t gen_prime (unsigned int nbits, int secret, int randomlevel,
34
                             int (*extra_check)(void *, gcry_mpi_t),
35
                             void *extra_check_arg);
36
static int check_prime( gcry_mpi_t prime, gcry_mpi_t val_2, int rm_rounds,
37
                        gcry_prime_check_func_t cb_func, void *cb_arg );
38
static int is_prime (gcry_mpi_t n, int steps, unsigned int *count);
39
static void m_out_of_n( char *array, int m, int n );
40
41
static void (*progress_cb) (void *,const char*,int,int, int );
42
static void *progress_cb_data;
43
44
/* Note: 2 is not included because it can be tested more easily by
45
   looking at bit 0. The last entry in this list is marked by a zero */
46
static ushort small_prime_numbers[] = {
47
    3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
48
    47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
49
    103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
50
    157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
51
    211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
52
    269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
53
    331, 337, 347, 349, 353, 359, 367, 373, 379, 383,
54
    389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
55
    449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
56
    509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
57
    587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
58
    643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
59
    709, 719, 727, 733, 739, 743, 751, 757, 761, 769,
60
    773, 787, 797, 809, 811, 821, 823, 827, 829, 839,
61
    853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
62
    919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
63
    991, 997, 1009, 1013, 1019, 1021, 1031, 1033,
64
    1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091,
65
    1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
66
    1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213,
67
    1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277,
68
    1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307,
69
    1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399,
70
    1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
71
    1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493,
72
    1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559,
73
    1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609,
74
    1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667,
75
    1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
76
    1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789,
77
    1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871,
78
    1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931,
79
    1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997,
80
    1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
81
    2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111,
82
    2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161,
83
    2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243,
84
    2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297,
85
    2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
86
    2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411,
87
    2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473,
88
    2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
89
    2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633,
90
    2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
91
    2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729,
92
    2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791,
93
    2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851,
94
    2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917,
95
    2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
96
    3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061,
97
    3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137,
98
    3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209,
99
    3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271,
100
    3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
101
    3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,
102
    3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467,
103
    3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,
104
    3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583,
105
    3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
106
    3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709,
107
    3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779,
108
    3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851,
109
    3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917,
110
    3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
111
    4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049,
112
    4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111,
113
    4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177,
114
    4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243,
115
    4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
116
    4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391,
117
    4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457,
118
    4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519,
119
    4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597,
120
    4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
121
    4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729,
122
    4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799,
123
    4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889,
124
    4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951,
125
    4957, 4967, 4969, 4973, 4987, 4993, 4999,
126
    0
127
};
128
static int no_of_small_prime_numbers = DIM (small_prime_numbers) - 1;
129
130
131

132
/* An object and a list to build up a global pool of primes.  See
133
   save_pool_prime and get_pool_prime. */
134
struct primepool_s
135
{
136
  struct primepool_s *next;
137
  gcry_mpi_t prime;      /* If this is NULL the entry is not used. */
138
  unsigned int nbits;
139
  gcry_random_level_t randomlevel;
140
};
141
struct primepool_s *primepool;
142
/* Mutex used to protect access to the primepool.  */
143
GPGRT_LOCK_DEFINE (primepool_lock);
144
145
146
gcry_err_code_t
147
_gcry_primegen_init (void)
148
1
{
149
  /* This function was formerly used to initialize the primepool
150
     Mutex. This has been replace by a static initialization.  */
151
1
  return 0;
152
1
}
153
154
155
/* Save PRIME which has been generated at RANDOMLEVEL for later
156
   use. Needs to be called while primepool_lock is being hold.  Note
157
   that PRIME should be considered released after calling this
158
   function. */
159
static void
160
save_pool_prime (gcry_mpi_t prime, gcry_random_level_t randomlevel)
161
0
{
162
0
  struct primepool_s *item, *item2;
163
0
  size_t n;
164
165
0
  for (n=0, item = primepool; item; item = item->next, n++)
166
0
    if (!item->prime)
167
0
      break;
168
0
  if (!item && n > 100)
169
0
    {
170
      /* Remove some of the entries.  Our strategy is removing
171
         the last third from the list. */
172
0
      int i;
173
174
0
      for (i=0, item2 = primepool; item2; item2 = item2->next)
175
0
        {
176
0
          if (i >= n/3*2)
177
0
            {
178
0
              _gcry_mpi_release (item2->prime);
179
0
              item2->prime = NULL;
180
0
              if (!item)
181
0
                item = item2;
182
0
            }
183
0
        }
184
0
    }
185
0
  if (!item)
186
0
    {
187
0
      item = xtrycalloc (1, sizeof *item);
188
0
      if (!item)
189
0
        {
190
          /* Out of memory.  Silently giving up. */
191
0
          _gcry_mpi_release (prime);
192
0
          return;
193
0
        }
194
0
      item->next = primepool;
195
0
      primepool = item;
196
0
    }
197
0
  item->prime = prime;
198
0
  item->nbits = mpi_get_nbits (prime);
199
0
  item->randomlevel = randomlevel;
200
0
}
201
202
203
/* Return a prime for the prime pool or NULL if none has been found.
204
   The prime needs to match NBITS and randomlevel. This function needs
205
   to be called with the primepool_look is being hold. */
206
static gcry_mpi_t
207
get_pool_prime (unsigned int nbits, gcry_random_level_t randomlevel)
208
0
{
209
0
  struct primepool_s *item;
210
211
0
  for (item = primepool; item; item = item->next)
212
0
    if (item->prime
213
0
        && item->nbits == nbits && item->randomlevel == randomlevel)
214
0
      {
215
0
        gcry_mpi_t prime = item->prime;
216
0
        item->prime = NULL;
217
0
        gcry_assert (nbits == mpi_get_nbits (prime));
218
0
        return prime;
219
0
      }
220
0
  return NULL;
221
0
}
222
223
224
225
226
227

228
void
229
_gcry_register_primegen_progress ( void (*cb)(void *,const char*,int,int,int),
230
                                   void *cb_data )
231
0
{
232
0
  progress_cb = cb;
233
0
  progress_cb_data = cb_data;
234
0
}
235
236
237
static void
238
progress( int c )
239
0
{
240
0
  if ( progress_cb )
241
0
    progress_cb ( progress_cb_data, "primegen", c, 0, 0 );
242
0
}
243
244
245
/****************
246
 * Generate a prime number (stored in secure memory)
247
 */
248
gcry_mpi_t
249
_gcry_generate_secret_prime (unsigned int nbits,
250
                             gcry_random_level_t random_level,
251
                             int (*extra_check)(void*, gcry_mpi_t),
252
                             void *extra_check_arg)
253
0
{
254
0
  gcry_mpi_t prime;
255
256
0
  prime = gen_prime (nbits, 1, random_level, extra_check, extra_check_arg);
257
0
  progress('\n');
258
0
  return prime;
259
0
}
260
261
262
/* Generate a prime number which may be public, i.e. not allocated in
263
   secure memory.  */
264
gcry_mpi_t
265
_gcry_generate_public_prime (unsigned int nbits,
266
                             gcry_random_level_t random_level,
267
                             int (*extra_check)(void*, gcry_mpi_t),
268
                             void *extra_check_arg)
269
0
{
270
0
  gcry_mpi_t prime;
271
272
0
  prime = gen_prime (nbits, 0, random_level, extra_check, extra_check_arg);
273
0
  progress('\n');
274
0
  return prime;
275
0
}
276
277
278
/* Core prime generation function.  The algorithm used to generate
279
   practically save primes is due to Lim and Lee as described in the
280
   CRYPTO '97 proceedings (ISBN3540633847) page 260.
281
282
   NEED_Q_FACTOR: If true make sure that at least one factor is of
283
                  size qbits.  This is for example required for DSA.
284
   PRIME_GENERATED: Adresss of a variable where the resulting prime
285
                    number will be stored.
286
   PBITS: Requested size of the prime number.  At least 48.
287
   QBITS: One factor of the prime needs to be of this size.  Maybe 0
288
          if this is not required.  See also MODE.
289
   G: If not NULL an MPI which will receive a generator for the prime
290
      for use with Elgamal.
291
   RET_FACTORS: if not NULL, an array with all factors are stored at
292
                that address.
293
   ALL_FACTORS: If set to true all factors of prime-1 are returned.
294
   RANDOMLEVEL:  How strong should the random numers be.
295
   FLAGS: Prime generation bit flags. Currently supported:
296
          GCRY_PRIME_FLAG_SECRET - The prime needs to be kept secret.
297
   CB_FUNC, CB_ARG:  Callback to be used for extra checks.
298
299
 */
300
static gcry_err_code_t
301
prime_generate_internal (int need_q_factor,
302
       gcry_mpi_t *prime_generated, unsigned int pbits,
303
       unsigned int qbits, gcry_mpi_t g,
304
       gcry_mpi_t **ret_factors,
305
       gcry_random_level_t randomlevel, unsigned int flags,
306
                         int all_factors,
307
                         gcry_prime_check_func_t cb_func, void *cb_arg)
308
0
{
309
0
  gcry_err_code_t err = 0;
310
0
  gcry_mpi_t *factors_new = NULL; /* Factors to return to the
311
             caller.  */
312
0
  gcry_mpi_t *factors = NULL; /* Current factors.  */
313
0
  gcry_random_level_t poolrandomlevel; /* Random level used for pool primes. */
314
0
  gcry_mpi_t *pool = NULL;  /* Pool of primes.  */
315
0
  int *pool_in_use = NULL;      /* Array with currently used POOL elements. */
316
0
  unsigned char *perms = NULL;  /* Permutations of POOL.  */
317
0
  gcry_mpi_t q_factor = NULL; /* Used if QBITS is non-zero.  */
318
0
  unsigned int fbits = 0; /* Length of prime factors.  */
319
0
  unsigned int n = 0;   /* Number of factors.  */
320
0
  unsigned int m = 0;   /* Number of primes in pool.  */
321
0
  gcry_mpi_t q = NULL;    /* First prime factor.  */
322
0
  gcry_mpi_t prime = NULL;  /* Prime candidate.  */
323
0
  unsigned int nprime = 0;  /* Bits of PRIME.  */
324
0
  unsigned int req_qbits;       /* The original QBITS value.  */
325
0
  gcry_mpi_t val_2;             /* For check_prime().  */
326
0
  int is_locked = 0;            /* Flag to help unlocking the primepool. */
327
0
  unsigned int is_secret = (flags & GCRY_PRIME_FLAG_SECRET);
328
0
  unsigned int count1 = 0, count2 = 0;
329
0
  unsigned int i = 0, j = 0;
330
331
0
  if (pbits < 48)
332
0
    return GPG_ERR_INV_ARG;
333
334
  /* We won't use a too strong random elvel for the pooled subprimes. */
335
0
  poolrandomlevel = (randomlevel > GCRY_STRONG_RANDOM?
336
0
                     GCRY_STRONG_RANDOM : randomlevel);
337
338
339
  /* If QBITS is not given, assume a reasonable value. */
340
0
  if (!qbits)
341
0
    qbits = pbits / 3;
342
343
0
  req_qbits = qbits;
344
345
  /* Find number of needed prime factors N.  */
346
0
  for (n = 1; (pbits - qbits - 1) / n  >= qbits; n++)
347
0
    ;
348
0
  n--;
349
350
0
  val_2 = mpi_alloc_set_ui (2);
351
352
0
  if ((! n) || ((need_q_factor) && (n < 2)))
353
0
    {
354
0
      err = GPG_ERR_INV_ARG;
355
0
      goto leave;
356
0
    }
357
358
0
  if (need_q_factor)
359
0
    {
360
0
      n--;  /* Need one factor less because we want a specific Q-FACTOR. */
361
0
      fbits = (pbits - 2 * req_qbits -1) / n;
362
0
      qbits =  pbits - req_qbits - n * fbits;
363
0
    }
364
0
  else
365
0
    {
366
0
      fbits = (pbits - req_qbits -1) / n;
367
0
      qbits = pbits - n * fbits;
368
0
    }
369
370
0
  if (DBG_CIPHER)
371
0
    log_debug ("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n",
372
0
               pbits, req_qbits, qbits, fbits, n);
373
374
  /* Allocate an integer to old the new prime. */
375
0
  prime = mpi_new (pbits);
376
377
  /* Generate first prime factor.  */
378
0
  q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL);
379
380
  /* Generate a specific Q-Factor if requested. */
381
0
  if (need_q_factor)
382
0
    q_factor = gen_prime (req_qbits, is_secret, randomlevel, NULL, NULL);
383
384
  /* Allocate an array to hold all factors + 2 for later usage.  */
385
0
  factors = xtrycalloc (n + 2, sizeof (*factors));
386
0
  if (!factors)
387
0
    {
388
0
      err = gpg_err_code_from_errno (errno);
389
0
      goto leave;
390
0
    }
391
392
  /* Allocate an array to track pool usage. */
393
0
  pool_in_use = xtrymalloc (n * sizeof *pool_in_use);
394
0
  if (!pool_in_use)
395
0
    {
396
0
      err = gpg_err_code_from_errno (errno);
397
0
      goto leave;
398
0
    }
399
0
  for (i=0; i < n; i++)
400
0
    pool_in_use[i] = -1;
401
402
  /* Make a pool of 3n+5 primes (this is an arbitrary value).  We
403
     require at least 30 primes for are useful selection process.
404
405
     Fixme: We need to research the best formula for sizing the pool.
406
  */
407
0
  m = n * 3 + 5;
408
0
  if (need_q_factor) /* Need some more in this case. */
409
0
    m += 5;
410
0
  if (m < 30)
411
0
    m = 30;
412
0
  pool = xtrycalloc (m , sizeof (*pool));
413
0
  if (! pool)
414
0
    {
415
0
      err = gpg_err_code_from_errno (errno);
416
0
      goto leave;
417
0
    }
418
419
  /* Permutate over the pool of primes until we find a prime of the
420
     requested length.  */
421
0
  do
422
0
    {
423
0
    next_try:
424
0
      for (i=0; i < n; i++)
425
0
        pool_in_use[i] = -1;
426
427
0
      if (!perms)
428
0
        {
429
          /* Allocate new primes.  This is done right at the beginning
430
             of the loop and if we have later run out of primes. */
431
0
          for (i = 0; i < m; i++)
432
0
            {
433
0
              mpi_free (pool[i]);
434
0
              pool[i] = NULL;
435
0
            }
436
437
          /* Init m_out_of_n().  */
438
0
          perms = xtrycalloc (1, m);
439
0
          if (!perms)
440
0
            {
441
0
              err = gpg_err_code_from_errno (errno);
442
0
              goto leave;
443
0
            }
444
445
0
          err = gpgrt_lock_lock (&primepool_lock);
446
0
          if (err)
447
0
            goto leave;
448
0
          is_locked = 1;
449
450
0
          for (i = 0; i < n; i++)
451
0
            {
452
0
              perms[i] = 1;
453
              /* At a maximum we use strong random for the factors.
454
                 This saves us a lot of entropy. Given that Q and
455
                 possible Q-factor are also used in the final prime
456
                 this should be acceptable.  We also don't allocate in
457
                 secure memory to save on that scare resource too.  If
458
                 Q has been allocated in secure memory, the final
459
                 prime will be saved there anyway.  This is because
460
                 our MPI routines take care of that.  GnuPG has worked
461
                 this way ever since.  */
462
0
              pool[i] = NULL;
463
0
              if (is_locked)
464
0
                {
465
0
                  pool[i] = get_pool_prime (fbits, poolrandomlevel);
466
0
                  if (!pool[i])
467
0
                    {
468
0
                      err = gpgrt_lock_unlock (&primepool_lock);
469
0
                      if (err)
470
0
                        goto leave;
471
0
                      is_locked = 0;
472
0
                    }
473
0
                }
474
0
              if (!pool[i])
475
0
                pool[i] = gen_prime (fbits, 0, poolrandomlevel, NULL, NULL);
476
0
              pool_in_use[i] = i;
477
0
              factors[i] = pool[i];
478
0
            }
479
480
0
          if (is_locked && (err = gpgrt_lock_unlock (&primepool_lock)))
481
0
            goto leave;
482
0
          is_locked = 0;
483
0
        }
484
0
      else
485
0
        {
486
          /* Get next permutation. */
487
0
          m_out_of_n ( (char*)perms, n, m);
488
489
0
          if ((err = gpgrt_lock_lock (&primepool_lock)))
490
0
            goto leave;
491
0
          is_locked = 1;
492
493
0
          for (i = j = 0; (i < m) && (j < n); i++)
494
0
            if (perms[i])
495
0
              {
496
                /* If the subprime has not yet beed generated do it now. */
497
0
                if (!pool[i] && is_locked)
498
0
                  {
499
0
                    pool[i] = get_pool_prime (fbits, poolrandomlevel);
500
0
                    if (!pool[i])
501
0
                      {
502
0
                        if ((err = gpgrt_lock_unlock (&primepool_lock)))
503
0
                          goto leave;
504
0
                        is_locked = 0;
505
0
                      }
506
0
                  }
507
0
                if (!pool[i])
508
0
                  pool[i] = gen_prime (fbits, 0, poolrandomlevel, NULL, NULL);
509
0
                pool_in_use[j] = i;
510
0
                factors[j++] = pool[i];
511
0
              }
512
513
0
          if (is_locked && (err = gpgrt_lock_unlock (&primepool_lock)))
514
0
            goto leave;
515
0
          is_locked = 0;
516
517
0
          if (i == n)
518
0
            {
519
              /* Ran out of permutations: Allocate new primes.  */
520
0
              xfree (perms);
521
0
              perms = NULL;
522
0
              progress ('!');
523
0
              goto next_try;
524
0
            }
525
0
        }
526
527
  /* Generate next prime candidate:
528
     p = 2 * q [ * q_factor] * factor_0 * factor_1 * ... * factor_n + 1.
529
         */
530
0
  mpi_set (prime, q);
531
0
  mpi_mul_ui (prime, prime, 2);
532
0
  if (need_q_factor)
533
0
    mpi_mul (prime, prime, q_factor);
534
0
  for(i = 0; i < n; i++)
535
0
    mpi_mul (prime, prime, factors[i]);
536
0
  mpi_add_ui (prime, prime, 1);
537
0
  nprime = mpi_get_nbits (prime);
538
539
0
  if (nprime < pbits)
540
0
    {
541
0
      if (++count1 > 20)
542
0
        {
543
0
    count1 = 0;
544
0
    qbits++;
545
0
    progress('>');
546
0
    mpi_free (q);
547
0
    q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL);
548
0
    goto next_try;
549
0
        }
550
0
    }
551
0
  else
552
0
    count1 = 0;
553
554
0
  if (nprime > pbits)
555
0
    {
556
0
      if (++count2 > 20)
557
0
        {
558
0
    count2 = 0;
559
0
    qbits--;
560
0
    progress('<');
561
0
    mpi_free (q);
562
0
    q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL);
563
0
    goto next_try;
564
0
        }
565
0
    }
566
0
  else
567
0
    count2 = 0;
568
0
    }
569
0
  while (! ((nprime == pbits) && check_prime (prime, val_2, 5,
570
0
                                              cb_func, cb_arg)));
571
572
0
  if (DBG_CIPHER)
573
0
    {
574
0
      progress ('\n');
575
0
      log_mpidump ("prime    ", prime);
576
0
      log_mpidump ("factor  q", q);
577
0
      if (need_q_factor)
578
0
        log_mpidump ("factor q0", q_factor);
579
0
      for (i = 0; i < n; i++)
580
0
        log_mpidump ("factor pi", factors[i]);
581
0
      log_debug ("bit sizes: prime=%u, q=%u",
582
0
                 mpi_get_nbits (prime), mpi_get_nbits (q));
583
0
      if (need_q_factor)
584
0
        log_printf (", q0=%u", mpi_get_nbits (q_factor));
585
0
      for (i = 0; i < n; i++)
586
0
        log_printf (", p%d=%u", i, mpi_get_nbits (factors[i]));
587
0
      log_printf ("\n");
588
0
    }
589
590
0
  if (ret_factors)
591
0
    {
592
      /* Caller wants the factors.  */
593
0
      factors_new = xtrycalloc (n + 4, sizeof (*factors_new));
594
0
      if (! factors_new)
595
0
        {
596
0
          err = gpg_err_code_from_errno (errno);
597
0
          goto leave;
598
0
        }
599
600
0
      if (all_factors)
601
0
        {
602
0
          i = 0;
603
0
          factors_new[i++] = mpi_set_ui (NULL, 2);
604
0
          factors_new[i++] = mpi_copy (q);
605
0
          if (need_q_factor)
606
0
            factors_new[i++] = mpi_copy (q_factor);
607
0
          for(j=0; j < n; j++)
608
0
            factors_new[i++] = mpi_copy (factors[j]);
609
0
        }
610
0
      else
611
0
        {
612
0
          i = 0;
613
0
          if (need_q_factor)
614
0
            {
615
0
              factors_new[i++] = mpi_copy (q_factor);
616
0
              for (; i <= n; i++)
617
0
                factors_new[i] = mpi_copy (factors[i]);
618
0
            }
619
0
          else
620
0
            for (; i < n; i++ )
621
0
              factors_new[i] = mpi_copy (factors[i]);
622
0
        }
623
0
    }
624
625
0
  if (g && need_q_factor)
626
0
    err = GPG_ERR_NOT_IMPLEMENTED;
627
0
  else if (g)
628
0
    {
629
      /* Create a generator (start with 3).  */
630
0
      gcry_mpi_t tmp = mpi_alloc (mpi_get_nlimbs (prime));
631
0
      gcry_mpi_t b = mpi_alloc (mpi_get_nlimbs (prime));
632
0
      gcry_mpi_t pmin1 = mpi_alloc (mpi_get_nlimbs (prime));
633
634
0
      factors[n] = q;
635
0
      factors[n + 1] = mpi_alloc_set_ui (2);
636
0
      mpi_sub_ui (pmin1, prime, 1);
637
0
      mpi_set_ui (g, 2);
638
0
      do
639
0
        {
640
0
          mpi_add_ui (g, g, 1);
641
0
          if (DBG_CIPHER)
642
0
            log_printmpi ("checking g", g);
643
0
          else
644
0
            progress('^');
645
0
          for (i = 0; i < n + 2; i++)
646
0
            {
647
0
              mpi_fdiv_q (tmp, pmin1, factors[i]);
648
              /* No mpi_pow(), but it is okay to use this with mod
649
                 prime.  */
650
0
              mpi_powm (b, g, tmp, prime);
651
0
              if (! mpi_cmp_ui (b, 1))
652
0
                break;
653
0
            }
654
0
          if (DBG_CIPHER)
655
0
            progress('\n');
656
0
        }
657
0
      while (i < n + 2);
658
659
0
      mpi_free (factors[n+1]);
660
0
      mpi_free (tmp);
661
0
      mpi_free (b);
662
0
      mpi_free (pmin1);
663
0
    }
664
665
0
  if (! DBG_CIPHER)
666
0
    progress ('\n');
667
668
669
0
 leave:
670
0
  if (pool)
671
0
    {
672
0
      is_locked = !gpgrt_lock_lock (&primepool_lock);
673
0
      for(i = 0; i < m; i++)
674
0
        {
675
0
          if (pool[i])
676
0
            {
677
0
              for (j=0; j < n; j++)
678
0
                if (pool_in_use[j] == i)
679
0
                  break;
680
0
              if (j == n && is_locked)
681
0
                {
682
                  /* This pooled subprime has not been used. */
683
0
                  save_pool_prime (pool[i], poolrandomlevel);
684
0
                }
685
0
              else
686
0
                mpi_free (pool[i]);
687
0
            }
688
0
        }
689
0
      if (is_locked)
690
0
        err = gpgrt_lock_unlock (&primepool_lock);
691
0
      is_locked = 0;
692
0
      xfree (pool);
693
0
    }
694
0
  xfree (pool_in_use);
695
0
  if (factors)
696
0
    xfree (factors);  /* Factors are shallow copies.  */
697
0
  if (perms)
698
0
    xfree (perms);
699
700
0
  mpi_free (val_2);
701
0
  mpi_free (q);
702
0
  mpi_free (q_factor);
703
704
0
  if (! err)
705
0
    {
706
0
      *prime_generated = prime;
707
0
      if (ret_factors)
708
0
  *ret_factors = factors_new;
709
0
    }
710
0
  else
711
0
    {
712
0
      if (factors_new)
713
0
  {
714
0
    for (i = 0; factors_new[i]; i++)
715
0
      mpi_free (factors_new[i]);
716
0
    xfree (factors_new);
717
0
  }
718
0
      mpi_free (prime);
719
0
    }
720
721
0
  return err;
722
0
}
723
724
725
/* Generate a prime used for discrete logarithm algorithms; i.e. this
726
   prime will be public and no strong random is required.  On success
727
   R_PRIME receives a new MPI with the prime.  On error R_PRIME is set
728
   to NULL and an error code is returned.  If RET_FACTORS is not NULL
729
   it is set to an allocated array of factors on success or to NULL on
730
   error.  */
731
gcry_err_code_t
732
_gcry_generate_elg_prime (int mode, unsigned pbits, unsigned qbits,
733
        gcry_mpi_t g,
734
                          gcry_mpi_t *r_prime, gcry_mpi_t **ret_factors)
735
0
{
736
0
  *r_prime = NULL;
737
0
  if (ret_factors)
738
0
    *ret_factors = NULL;
739
0
  return prime_generate_internal ((mode == 1), r_prime, pbits, qbits, g,
740
0
                                  ret_factors, GCRY_WEAK_RANDOM, 0, 0,
741
0
                                  NULL, NULL);
742
0
}
743
744
745
static gcry_mpi_t
746
gen_prime (unsigned int nbits, int secret, int randomlevel,
747
           int (*extra_check)(void *, gcry_mpi_t), void *extra_check_arg)
748
0
{
749
0
  gcry_mpi_t prime, ptest, pminus1, val_2, val_3, result;
750
0
  int i;
751
0
  unsigned int x, step;
752
0
  unsigned int count1, count2;
753
0
  int *mods;
754
755
0
  (void)count1; /* The value is not used, actually.  */
756
757
/*   if (  DBG_CIPHER ) */
758
/*     log_debug ("generate a prime of %u bits ", nbits ); */
759
760
0
  if (nbits < 16)
761
0
    log_fatal ("can't generate a prime with less than %d bits\n", 16);
762
763
0
  mods = (secret? xmalloc_secure (no_of_small_prime_numbers * sizeof *mods)
764
0
          /* */ : xmalloc (no_of_small_prime_numbers * sizeof *mods));
765
  /* Make nbits fit into gcry_mpi_t implementation. */
766
0
  val_2  = mpi_alloc_set_ui( 2 );
767
0
  val_3 = mpi_alloc_set_ui( 3);
768
0
  prime  = secret? mpi_snew (nbits): mpi_new (nbits);
769
0
  result = mpi_alloc_like( prime );
770
0
  pminus1= mpi_alloc_like( prime );
771
0
  ptest  = mpi_alloc_like( prime );
772
0
  count1 = count2 = 0;
773
0
  for (;;)
774
0
    {  /* try forvever */
775
0
      int dotcount=0;
776
777
      /* generate a random number */
778
0
      _gcry_mpi_randomize( prime, nbits, randomlevel );
779
780
      /* Set high order bit to 1, set low order bit to 1.  If we are
781
         generating a secret prime we are most probably doing that
782
         for RSA, to make sure that the modulus does have the
783
         requested key size we set the 2 high order bits. */
784
0
      mpi_set_highbit (prime, nbits-1);
785
0
      if (secret)
786
0
        mpi_set_bit (prime, nbits-2);
787
0
      mpi_set_bit(prime, 0);
788
789
      /* Calculate all remainders. */
790
0
      for (i=0; (x = small_prime_numbers[i]); i++ )
791
0
        mods[i] = mpi_fdiv_r_ui(NULL, prime, x);
792
793
      /* Now try some primes starting with prime. */
794
0
      for(step=0; step < 20000; step += 2 )
795
0
        {
796
          /* Check against all the small primes we have in mods. */
797
0
          count1++;
798
0
          for (i=0; (x = small_prime_numbers[i]); i++ )
799
0
            {
800
0
              while ( mods[i] + step >= x )
801
0
                mods[i] -= x;
802
0
              if ( !(mods[i] + step) )
803
0
                break;
804
0
      }
805
0
          if ( x )
806
0
            continue;   /* Found a multiple of an already known prime. */
807
808
0
          mpi_add_ui( ptest, prime, step );
809
810
          /* Do a fast Fermat test now. */
811
0
          count2++;
812
0
          mpi_sub_ui( pminus1, ptest, 1);
813
0
          mpi_powm( result, val_2, pminus1, ptest );
814
0
          if ( !mpi_cmp_ui( result, 1 ) )
815
0
            {
816
              /* Not composite, perform stronger tests */
817
0
              if (is_prime(ptest, 5, &count2 ))
818
0
                {
819
0
                  if (!mpi_test_bit( ptest, nbits-1-secret ))
820
0
                    {
821
0
                      progress('\n');
822
0
                      log_debug ("overflow in prime generation\n");
823
0
                      break; /* Stop loop, continue with a new prime. */
824
0
                    }
825
826
0
                  if (extra_check && extra_check (extra_check_arg, ptest))
827
0
                    {
828
                      /* The extra check told us that this prime is
829
                         not of the caller's taste. */
830
0
                      progress ('/');
831
0
                    }
832
0
                  else
833
0
                    {
834
                      /* Got it. */
835
0
                      mpi_free(val_2);
836
0
                      mpi_free(val_3);
837
0
                      mpi_free(result);
838
0
                      mpi_free(pminus1);
839
0
                      mpi_free(prime);
840
0
                      xfree(mods);
841
0
                      return ptest;
842
0
                    }
843
0
                }
844
0
      }
845
0
          if (++dotcount == 10 )
846
0
            {
847
0
              progress('.');
848
0
              dotcount = 0;
849
0
      }
850
0
  }
851
0
      progress(':'); /* restart with a new random value */
852
0
    }
853
0
}
854
855
/****************
856
 * Returns: true if this may be a prime
857
 * RM_ROUNDS gives the number of Rabin-Miller tests to run.
858
 */
859
static int
860
check_prime( gcry_mpi_t prime, gcry_mpi_t val_2, int rm_rounds,
861
             gcry_prime_check_func_t cb_func, void *cb_arg)
862
0
{
863
0
  int i;
864
0
  unsigned int x;
865
0
  unsigned int count=0;
866
867
  /* Check against small primes. */
868
0
  for (i=0; (x = small_prime_numbers[i]); i++ )
869
0
    {
870
0
      if ( mpi_divisible_ui( prime, x ) )
871
0
        return !mpi_cmp_ui (prime, x);
872
0
    }
873
874
  /* A quick Fermat test. */
875
0
  {
876
0
    gcry_mpi_t result = mpi_alloc_like( prime );
877
0
    gcry_mpi_t pminus1 = mpi_alloc_like( prime );
878
0
    mpi_sub_ui( pminus1, prime, 1);
879
0
    mpi_powm( result, val_2, pminus1, prime );
880
0
    mpi_free( pminus1 );
881
0
    if ( mpi_cmp_ui( result, 1 ) )
882
0
      {
883
        /* Is composite. */
884
0
        mpi_free( result );
885
0
        progress('.');
886
0
        return 0;
887
0
      }
888
0
    mpi_free( result );
889
0
  }
890
891
0
  if (!cb_func || cb_func (cb_arg, GCRY_PRIME_CHECK_AT_MAYBE_PRIME, prime))
892
0
    {
893
      /* Perform stronger tests. */
894
0
      if ( is_prime( prime, rm_rounds, &count ) )
895
0
        {
896
0
          if (!cb_func
897
0
              || cb_func (cb_arg, GCRY_PRIME_CHECK_AT_GOT_PRIME, prime))
898
0
            return 1; /* Probably a prime. */
899
0
        }
900
0
    }
901
0
  progress('.');
902
0
  return 0;
903
0
}
904
905
906
/*
907
 * Return true if n is probably a prime
908
 */
909
static int
910
is_prime (gcry_mpi_t n, int steps, unsigned int *count)
911
0
{
912
0
  gcry_mpi_t x = mpi_alloc( mpi_get_nlimbs( n ) );
913
0
  gcry_mpi_t y = mpi_alloc( mpi_get_nlimbs( n ) );
914
0
  gcry_mpi_t z = mpi_alloc( mpi_get_nlimbs( n ) );
915
0
  gcry_mpi_t nminus1 = mpi_alloc( mpi_get_nlimbs( n ) );
916
0
  gcry_mpi_t a2 = mpi_alloc_set_ui( 2 );
917
0
  gcry_mpi_t q;
918
0
  unsigned i, j, k;
919
0
  int rc = 0;
920
0
  unsigned nbits = mpi_get_nbits( n );
921
922
0
  if (steps < 5) /* Make sure that we do at least 5 rounds. */
923
0
    steps = 5;
924
925
0
  mpi_sub_ui( nminus1, n, 1 );
926
927
  /* Find q and k, so that n = 1 + 2^k * q . */
928
0
  q = mpi_copy ( nminus1 );
929
0
  k = mpi_trailing_zeros ( q );
930
0
  mpi_tdiv_q_2exp (q, q, k);
931
932
0
  for (i=0 ; i < steps; i++ )
933
0
    {
934
0
      ++*count;
935
0
      if( !i )
936
0
        {
937
0
          mpi_set_ui( x, 2 );
938
0
        }
939
0
      else
940
0
        {
941
          /* We need to loop to avoid an X with value 0 or 1.  */
942
0
          do
943
0
            {
944
0
              _gcry_mpi_randomize (x, nbits, GCRY_WEAK_RANDOM);
945
946
              /* Make sure that the number is smaller than the prime
947
               * and keep the randomness of the high bit. */
948
0
              if (mpi_test_bit (x, nbits-2))
949
0
                {
950
0
                  mpi_set_highbit (x, nbits-2); /* Clear all higher bits. */
951
0
                }
952
0
              else
953
0
                {
954
0
                  mpi_set_highbit (x, nbits-2);
955
0
                  mpi_clear_bit (x, nbits-2);
956
0
                }
957
0
            }
958
0
          while (mpi_cmp_ui (x, 1) <= 0);
959
0
          gcry_assert (mpi_cmp (x, nminus1) < 0);
960
0
  }
961
0
      mpi_powm ( y, x, q, n);
962
0
      if ( mpi_cmp_ui(y, 1) && mpi_cmp( y, nminus1 ) )
963
0
        {
964
0
          for ( j=1; j < k && mpi_cmp( y, nminus1 ); j++ )
965
0
            {
966
0
              mpi_powm(y, y, a2, n);
967
0
              if( !mpi_cmp_ui( y, 1 ) )
968
0
                goto leave; /* Not a prime. */
969
0
            }
970
0
          if (mpi_cmp( y, nminus1 ) )
971
0
            goto leave; /* Not a prime. */
972
0
  }
973
0
      progress('+');
974
0
    }
975
0
  rc = 1; /* May be a prime. */
976
977
0
 leave:
978
0
  mpi_free( x );
979
0
  mpi_free( y );
980
0
  mpi_free( z );
981
0
  mpi_free( nminus1 );
982
0
  mpi_free( q );
983
0
  mpi_free( a2 );
984
985
0
  return rc;
986
0
}
987
988
989
/* Given ARRAY of size N with M elements set to true produce a
990
   modified array with the next permutation of M elements.  Note, that
991
   ARRAY is used in a one-bit-per-byte approach.  To detected the last
992
   permutation it is useful to initialize the array with the first M
993
   element set to true and use this test:
994
       m_out_of_n (array, m, n);
995
       for (i = j = 0; i < n && j < m; i++)
996
         if (array[i])
997
           j++;
998
       if (j == m)
999
         goto ready;
1000
1001
   This code is based on the algorithm 452 from the "Collected
1002
   Algorithms From ACM, Volume II" by C. N. Liu and D. T. Tang.
1003
*/
1004
static void
1005
m_out_of_n ( char *array, int m, int n )
1006
0
{
1007
0
  int i=0, i1=0, j=0, jp=0,  j1=0, k1=0, k2=0;
1008
1009
0
  if( !m || m >= n )
1010
0
    return;
1011
1012
  /* Need to handle this simple case separately. */
1013
0
  if( m == 1 )
1014
0
    {
1015
0
      for (i=0; i < n; i++ )
1016
0
        {
1017
0
          if ( array[i] )
1018
0
            {
1019
0
              array[i++] = 0;
1020
0
              if( i >= n )
1021
0
                i = 0;
1022
0
              array[i] = 1;
1023
0
              return;
1024
0
            }
1025
0
        }
1026
0
      BUG();
1027
0
    }
1028
1029
1030
0
  for (j=1; j < n; j++ )
1031
0
    {
1032
0
      if ( array[n-1] == array[n-j-1])
1033
0
        continue;
1034
0
      j1 = j;
1035
0
      break;
1036
0
    }
1037
1038
0
  if ( (m & 1) )
1039
0
    {
1040
      /* M is odd. */
1041
0
      if( array[n-1] )
1042
0
        {
1043
0
          if( j1 & 1 )
1044
0
            {
1045
0
              k1 = n - j1;
1046
0
              k2 = k1+2;
1047
0
              if( k2 > n )
1048
0
                k2 = n;
1049
0
              goto leave;
1050
0
            }
1051
0
          goto scan;
1052
0
        }
1053
0
      k2 = n - j1 - 1;
1054
0
      if( k2 == 0 )
1055
0
        {
1056
0
          k1 = i;
1057
0
          k2 = n - j1;
1058
0
        }
1059
0
      else if( array[k2] && array[k2-1] )
1060
0
        k1 = n;
1061
0
      else
1062
0
        k1 = k2 + 1;
1063
0
    }
1064
0
  else
1065
0
    {
1066
      /* M is even. */
1067
0
      if( !array[n-1] )
1068
0
        {
1069
0
          k1 = n - j1;
1070
0
          k2 = k1 + 1;
1071
0
          goto leave;
1072
0
        }
1073
1074
0
      if( !(j1 & 1) )
1075
0
        {
1076
0
          k1 = n - j1;
1077
0
          k2 = k1+2;
1078
0
          if( k2 > n )
1079
0
            k2 = n;
1080
0
          goto leave;
1081
0
        }
1082
0
    scan:
1083
0
      jp = n - j1 - 1;
1084
0
      for (i=1; i <= jp; i++ )
1085
0
        {
1086
0
          i1 = jp + 2 - i;
1087
0
          if( array[i1-1]  )
1088
0
            {
1089
0
              if( array[i1-2] )
1090
0
                {
1091
0
                  k1 = i1 - 1;
1092
0
                  k2 = n - j1;
1093
0
    }
1094
0
              else
1095
0
                {
1096
0
                  k1 = i1 - 1;
1097
0
                  k2 = n + 1 - j1;
1098
0
                }
1099
0
              goto leave;
1100
0
            }
1101
0
        }
1102
0
      k1 = 1;
1103
0
      k2 = n + 1 - m;
1104
0
    }
1105
0
 leave:
1106
  /* Now complement the two selected bits. */
1107
0
  array[k1-1] = !array[k1-1];
1108
0
  array[k2-1] = !array[k2-1];
1109
0
}
1110
1111
1112
/* Generate a new prime number of PRIME_BITS bits and store it in
1113
   PRIME.  If FACTOR_BITS is non-zero, one of the prime factors of
1114
   (prime - 1) / 2 must be FACTOR_BITS bits long.  If FACTORS is
1115
   non-zero, allocate a new, NULL-terminated array holding the prime
1116
   factors and store it in FACTORS.  FLAGS might be used to influence
1117
   the prime number generation process.  */
1118
gcry_err_code_t
1119
_gcry_prime_generate (gcry_mpi_t *prime, unsigned int prime_bits,
1120
                      unsigned int factor_bits, gcry_mpi_t **factors,
1121
                      gcry_prime_check_func_t cb_func, void *cb_arg,
1122
                      gcry_random_level_t random_level,
1123
                      unsigned int flags)
1124
0
{
1125
0
  gcry_err_code_t rc = 0;
1126
0
  gcry_mpi_t *factors_generated = NULL;
1127
0
  gcry_mpi_t prime_generated = NULL;
1128
0
  unsigned int mode = 0;
1129
1130
0
  if (!prime)
1131
0
    return GPG_ERR_INV_ARG;
1132
0
  *prime = NULL;
1133
1134
0
  if (flags & GCRY_PRIME_FLAG_SPECIAL_FACTOR)
1135
0
    mode = 1;
1136
1137
  /* Generate.  */
1138
0
  rc = prime_generate_internal ((mode==1), &prime_generated, prime_bits,
1139
0
                                factor_bits, NULL,
1140
0
                                factors? &factors_generated : NULL,
1141
0
                                random_level, flags, 1,
1142
0
                                cb_func, cb_arg);
1143
1144
0
  if (!rc && cb_func)
1145
0
    {
1146
      /* Additional check. */
1147
0
      if ( !cb_func (cb_arg, GCRY_PRIME_CHECK_AT_FINISH, prime_generated))
1148
0
        {
1149
          /* Failed, deallocate resources.  */
1150
0
          unsigned int i;
1151
1152
0
          mpi_free (prime_generated);
1153
0
          if (factors)
1154
0
            {
1155
0
              for (i = 0; factors_generated[i]; i++)
1156
0
                mpi_free (factors_generated[i]);
1157
0
              xfree (factors_generated);
1158
0
            }
1159
0
          rc = GPG_ERR_GENERAL;
1160
0
        }
1161
0
    }
1162
1163
0
  if (!rc)
1164
0
    {
1165
0
      if (factors)
1166
0
        *factors = factors_generated;
1167
0
      *prime = prime_generated;
1168
0
    }
1169
1170
0
  return rc;
1171
0
}
1172
1173
/* Check whether the number X is prime.  */
1174
gcry_err_code_t
1175
_gcry_prime_check (gcry_mpi_t x, unsigned int flags)
1176
0
{
1177
0
  (void)flags;
1178
1179
0
  switch (mpi_cmp_ui (x, 2))
1180
0
    {
1181
0
    case 0:  return 0;                /* 2 is a prime */
1182
0
    case -1: return GPG_ERR_NO_PRIME; /* Only numbers > 1 are primes.  */
1183
0
    }
1184
1185
  /* We use 64 rounds because the prime we are going to test is not
1186
     guaranteed to be a random one. */
1187
0
  if (check_prime (x, mpi_const (MPI_C_TWO), 64, NULL, NULL))
1188
0
    return 0;
1189
1190
0
  return GPG_ERR_NO_PRIME;
1191
0
}
1192
1193
1194
/* Check whether the number X is prime according to FIPS 186-4 table C.2.  */
1195
gcry_err_code_t
1196
_gcry_fips186_4_prime_check (gcry_mpi_t x, unsigned int bits)
1197
0
{
1198
0
  gcry_err_code_t ec = GPG_ERR_NO_ERROR;
1199
1200
0
  switch (mpi_cmp_ui (x, 2))
1201
0
    {
1202
0
    case 0:  return ec;               /* 2 is a prime */
1203
0
    case -1: return GPG_ERR_NO_PRIME; /* Only numbers > 1 are primes.  */
1204
0
    }
1205
1206
  /* We use 5 or 4 rounds as specified in table C.2 */
1207
0
  if (! check_prime (x, mpi_const (MPI_C_TWO), bits > 1024 ? 4 : 5, NULL, NULL))
1208
0
    ec = GPG_ERR_NO_PRIME;
1209
1210
0
  return ec;
1211
0
}
1212
1213
1214
/* Find a generator for PRIME where the factorization of (prime-1) is
1215
   in the NULL terminated array FACTORS. Return the generator as a
1216
   newly allocated MPI in R_G.  If START_G is not NULL, use this as s
1217
   atart for the search. Returns 0 on success.*/
1218
gcry_err_code_t
1219
_gcry_prime_group_generator (gcry_mpi_t *r_g,
1220
                             gcry_mpi_t prime, gcry_mpi_t *factors,
1221
                             gcry_mpi_t start_g)
1222
0
{
1223
0
  gcry_mpi_t tmp, b, pmin1, g;
1224
0
  int first, i, n;
1225
1226
0
  if (!r_g)
1227
0
    return GPG_ERR_INV_ARG;
1228
0
  *r_g = NULL;
1229
0
  if (!factors || !prime)
1230
0
    return GPG_ERR_INV_ARG;
1231
1232
0
  for (n=0; factors[n]; n++)
1233
0
    ;
1234
0
  if (n < 2)
1235
0
    return GPG_ERR_INV_ARG;
1236
1237
0
  tmp   = mpi_new (0);
1238
0
  b     = mpi_new (0);
1239
0
  pmin1 = mpi_new (0);
1240
0
  g     = start_g? mpi_copy (start_g) : mpi_set_ui (NULL, 3);
1241
1242
  /* Extra sanity check - usually disabled. */
1243
/*   mpi_set (tmp, factors[0]); */
1244
/*   for(i = 1; i < n; i++) */
1245
/*     mpi_mul (tmp, tmp, factors[i]); */
1246
/*   mpi_add_ui (tmp, tmp, 1); */
1247
/*   if (mpi_cmp (prime, tmp)) */
1248
/*     return gpg_error (GPG_ERR_INV_ARG); */
1249
1250
0
  mpi_sub_ui (pmin1, prime, 1);
1251
0
  first = 1;
1252
0
  do
1253
0
    {
1254
0
      if (first)
1255
0
        first = 0;
1256
0
      else
1257
0
        mpi_add_ui (g, g, 1);
1258
1259
0
      if (DBG_CIPHER)
1260
0
        log_printmpi ("checking g", g);
1261
0
      else
1262
0
        progress('^');
1263
1264
0
      for (i = 0; i < n; i++)
1265
0
        {
1266
0
          mpi_fdiv_q (tmp, pmin1, factors[i]);
1267
0
          mpi_powm (b, g, tmp, prime);
1268
0
          if (! mpi_cmp_ui (b, 1))
1269
0
            break;
1270
0
        }
1271
0
      if (DBG_CIPHER)
1272
0
        progress('\n');
1273
0
    }
1274
0
  while (i < n);
1275
1276
0
  _gcry_mpi_release (tmp);
1277
0
  _gcry_mpi_release (b);
1278
0
  _gcry_mpi_release (pmin1);
1279
0
  *r_g = g;
1280
1281
0
  return 0;
1282
0
}
1283
1284
/* Convenience function to release the factors array. */
1285
void
1286
_gcry_prime_release_factors (gcry_mpi_t *factors)
1287
0
{
1288
0
  if (factors)
1289
0
    {
1290
0
      int i;
1291
1292
0
      for (i=0; factors[i]; i++)
1293
0
        mpi_free (factors[i]);
1294
0
      xfree (factors);
1295
0
    }
1296
0
}
1297
1298
1299

1300
/* Helper for _gcry_derive_x931_prime.  */
1301
static gcry_mpi_t
1302
find_x931_prime (const gcry_mpi_t pfirst)
1303
0
{
1304
0
  gcry_mpi_t val_2 = mpi_alloc_set_ui (2);
1305
0
  gcry_mpi_t prime;
1306
1307
0
  prime = mpi_copy (pfirst);
1308
  /* If P is even add 1.  */
1309
0
  mpi_set_bit (prime, 0);
1310
1311
  /* We use 64 Rabin-Miller rounds which is better and thus
1312
     sufficient.  We do not have a Lucas test implementation thus we
1313
     can't do it in the X9.31 preferred way of running a few
1314
     Rabin-Miller followed by one Lucas test.  */
1315
0
  while ( !check_prime (prime, val_2, 64, NULL, NULL) )
1316
0
    mpi_add_ui (prime, prime, 2);
1317
1318
0
  mpi_free (val_2);
1319
1320
0
  return prime;
1321
0
}
1322
1323
1324
/* Generate a prime using the algorithm from X9.31 appendix B.4.
1325
1326
   This function requires that the provided public exponent E is odd.
1327
   XP, XP1 and XP2 are the seed values.  All values are mandatory.
1328
1329
   On success the prime is returned.  If R_P1 or R_P2 are given the
1330
   internal values P1 and P2 are saved at these addresses.  On error
1331
   NULL is returned.  */
1332
gcry_mpi_t
1333
_gcry_derive_x931_prime (const gcry_mpi_t xp,
1334
                         const gcry_mpi_t xp1, const gcry_mpi_t xp2,
1335
                         const gcry_mpi_t e,
1336
                         gcry_mpi_t *r_p1, gcry_mpi_t *r_p2)
1337
0
{
1338
0
  gcry_mpi_t p1, p2, p1p2, yp0;
1339
1340
0
  if (!xp || !xp1 || !xp2)
1341
0
    return NULL;
1342
0
  if (!e || !mpi_test_bit (e, 0))
1343
0
    return NULL;  /* We support only odd values for E.  */
1344
1345
0
  p1 = find_x931_prime (xp1);
1346
0
  p2 = find_x931_prime (xp2);
1347
0
  p1p2 = mpi_alloc_like (xp);
1348
0
  mpi_mul (p1p2, p1, p2);
1349
1350
0
  {
1351
0
    gcry_mpi_t r1, tmp;
1352
1353
    /* r1 = (p2^{-1} mod p1)p2 - (p1^{-1} mod p2) */
1354
0
    tmp = mpi_alloc_like (p1);
1355
0
    mpi_invm (tmp, p2, p1);
1356
0
    mpi_mul (tmp, tmp, p2);
1357
0
    r1 = tmp;
1358
1359
0
    tmp = mpi_alloc_like (p2);
1360
0
    mpi_invm (tmp, p1, p2);
1361
0
    mpi_mul (tmp, tmp, p1);
1362
0
    mpi_sub (r1, r1, tmp);
1363
1364
    /* Fixup a negative value.  */
1365
0
    if (mpi_has_sign (r1))
1366
0
      mpi_add (r1, r1, p1p2);
1367
1368
    /* yp0 = xp + (r1 - xp mod p1*p2)  */
1369
0
    yp0 = tmp; tmp = NULL;
1370
0
    mpi_subm (yp0, r1, xp, p1p2);
1371
0
    mpi_add (yp0, yp0, xp);
1372
0
    mpi_free (r1);
1373
1374
    /* Fixup a negative value.  */
1375
0
    if (mpi_cmp (yp0, xp) < 0 )
1376
0
      mpi_add (yp0, yp0, p1p2);
1377
0
  }
1378
1379
  /* yp0 is now the first integer greater than xp with p1 being a
1380
     large prime factor of yp0-1 and p2 a large prime factor of yp0+1.  */
1381
1382
  /* Note that the first example from X9.31 (D.1.1) which uses
1383
       (Xq1 #1A5CF72EE770DE50CB09ACCEA9#)
1384
       (Xq2 #134E4CAA16D2350A21D775C404#)
1385
       (Xq  #CC1092495D867E64065DEE3E7955F2EBC7D47A2D
1386
             7C9953388F97DDDC3E1CA19C35CA659EDC2FC325
1387
             6D29C2627479C086A699A49C4C9CEE7EF7BD1B34
1388
             321DE34A#))))
1389
     returns an yp0 of
1390
            #CC1092495D867E64065DEE3E7955F2EBC7D47A2D
1391
             7C9953388F97DDDC3E1CA19C35CA659EDC2FC4E3
1392
             BF20CB896EE37E098A906313271422162CB6C642
1393
             75C1201F#
1394
     and not
1395
            #CC1092495D867E64065DEE3E7955F2EBC7D47A2D
1396
             7C9953388F97DDDC3E1CA19C35CA659EDC2FC2E6
1397
             C88FE299D52D78BE405A97E01FD71DD7819ECB91
1398
             FA85A076#
1399
     as stated in the standard.  This seems to be a bug in X9.31.
1400
   */
1401
1402
0
  {
1403
0
    gcry_mpi_t val_2 = mpi_alloc_set_ui (2);
1404
0
    gcry_mpi_t gcdtmp = mpi_alloc_like (yp0);
1405
0
    int gcdres;
1406
1407
0
    mpi_sub_ui (p1p2, p1p2, 1); /* Adjust for loop body.  */
1408
0
    mpi_sub_ui (yp0, yp0, 1);   /* Ditto.  */
1409
0
    for (;;)
1410
0
      {
1411
0
        gcdres = mpi_gcd (gcdtmp, e, yp0);
1412
0
        mpi_add_ui (yp0, yp0, 1);
1413
0
        if (!gcdres)
1414
0
          progress ('/');  /* gcd (e, yp0-1) != 1  */
1415
0
        else if (check_prime (yp0, val_2, 64, NULL, NULL))
1416
0
          break; /* Found.  */
1417
        /* We add p1p2-1 because yp0 is incremented after the gcd test.  */
1418
0
        mpi_add (yp0, yp0, p1p2);
1419
0
      }
1420
0
    mpi_free (gcdtmp);
1421
0
    mpi_free (val_2);
1422
0
  }
1423
1424
0
  mpi_free (p1p2);
1425
1426
0
  progress('\n');
1427
0
  if (r_p1)
1428
0
    *r_p1 = p1;
1429
0
  else
1430
0
    mpi_free (p1);
1431
0
  if (r_p2)
1432
0
    *r_p2 = p2;
1433
0
  else
1434
0
    mpi_free (p2);
1435
0
  return yp0;
1436
0
}
1437
1438
1439

1440
/* Generate the two prime used for DSA using the algorithm specified
1441
   in FIPS 186-2.  PBITS is the desired length of the prime P and a
1442
   QBITS the length of the prime Q.  If SEED is not supplied and
1443
   SEEDLEN is 0 the function generates an appropriate SEED.  On
1444
   success the generated primes are stored at R_Q and R_P, the counter
1445
   value is stored at R_COUNTER and the seed actually used for
1446
   generation is stored at R_SEED and R_SEEDVALUE.  */
1447
gpg_err_code_t
1448
_gcry_generate_fips186_2_prime (unsigned int pbits, unsigned int qbits,
1449
                                const void *seed, size_t seedlen,
1450
                                gcry_mpi_t *r_q, gcry_mpi_t *r_p,
1451
                                int *r_counter,
1452
                                void **r_seed, size_t *r_seedlen)
1453
0
{
1454
0
  gpg_err_code_t ec;
1455
0
  unsigned char seed_help_buffer[160/8];  /* Used to hold a generated SEED. */
1456
0
  unsigned char *seed_plus;     /* Malloced buffer to hold SEED+x.  */
1457
0
  unsigned char digest[160/8];  /* Helper buffer for SHA-1 digest.  */
1458
0
  gcry_mpi_t val_2 = NULL;      /* Helper for the prime test.  */
1459
0
  gcry_mpi_t tmpval = NULL;     /* Helper variable.  */
1460
0
  int i;
1461
1462
0
  unsigned char value_u[160/8];
1463
0
  int value_n, value_b, value_k;
1464
0
  int counter;
1465
0
  gcry_mpi_t value_w = NULL;
1466
0
  gcry_mpi_t value_x = NULL;
1467
0
  gcry_mpi_t prime_q = NULL;
1468
0
  gcry_mpi_t prime_p = NULL;
1469
1470
  /* FIPS 186-2 allows only for 1024/160 bit.  */
1471
0
  if (pbits != 1024 || qbits != 160)
1472
0
    return GPG_ERR_INV_KEYLEN;
1473
1474
0
  if (!seed && !seedlen)
1475
0
    ; /* No seed value given:  We are asked to generate it.  */
1476
0
  else if (!seed || seedlen < qbits/8)
1477
0
    return GPG_ERR_INV_ARG;
1478
1479
  /* Allocate a buffer to later compute SEED+some_increment. */
1480
0
  seed_plus = xtrymalloc (seedlen < 20? 20:seedlen);
1481
0
  if (!seed_plus)
1482
0
    {
1483
0
      ec = gpg_err_code_from_syserror ();
1484
0
      goto leave;
1485
0
    }
1486
1487
0
  val_2   = mpi_alloc_set_ui (2);
1488
0
  value_n = (pbits - 1) / qbits;
1489
0
  value_b = (pbits - 1) - value_n * qbits;
1490
0
  value_w = mpi_new (pbits);
1491
0
  value_x = mpi_new (pbits);
1492
1493
0
 restart:
1494
  /* Generate Q.  */
1495
0
  for (;;)
1496
0
    {
1497
      /* Step 1: Generate a (new) seed unless one has been supplied.  */
1498
0
      if (!seed)
1499
0
        {
1500
0
          seedlen = sizeof seed_help_buffer;
1501
0
          _gcry_create_nonce (seed_help_buffer, seedlen);
1502
0
          seed = seed_help_buffer;
1503
0
        }
1504
1505
      /* Step 2: U = sha1(seed) ^ sha1((seed+1) mod 2^{qbits})  */
1506
0
      memcpy (seed_plus, seed, seedlen);
1507
0
      for (i=seedlen-1; i >= 0; i--)
1508
0
        {
1509
0
          seed_plus[i]++;
1510
0
          if (seed_plus[i])
1511
0
            break;
1512
0
        }
1513
0
      _gcry_md_hash_buffer (GCRY_MD_SHA1, value_u, seed, seedlen);
1514
0
      _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen);
1515
0
      for (i=0; i < sizeof value_u; i++)
1516
0
        value_u[i] ^= digest[i];
1517
1518
      /* Step 3:  Form q from U  */
1519
0
      _gcry_mpi_release (prime_q); prime_q = NULL;
1520
0
      ec = _gcry_mpi_scan (&prime_q, GCRYMPI_FMT_USG,
1521
0
                           value_u, sizeof value_u, NULL);
1522
0
      if (ec)
1523
0
        goto leave;
1524
0
      mpi_set_highbit (prime_q, qbits-1 );
1525
0
      mpi_set_bit (prime_q, 0);
1526
1527
      /* Step 4:  Test whether Q is prime using 64 round of Rabin-Miller.  */
1528
0
      if (check_prime (prime_q, val_2, 64, NULL, NULL))
1529
0
        break; /* Yes, Q is prime.  */
1530
1531
      /* Step 5.  */
1532
0
      seed = NULL;  /* Force a new seed at Step 1.  */
1533
0
    }
1534
1535
  /* Step 6.  Note that we do no use an explicit offset but increment
1536
     SEED_PLUS accordingly.  SEED_PLUS is currently SEED+1.  */
1537
0
  counter = 0;
1538
1539
  /* Generate P. */
1540
0
  prime_p = mpi_new (pbits);
1541
0
  for (;;)
1542
0
    {
1543
      /* Step 7: For k = 0,...n let
1544
                   V_k = sha1(seed+offset+k) mod 2^{qbits}
1545
         Step 8: W = V_0 + V_1*2^160 +
1546
                         ...
1547
                         + V_{n-1}*2^{(n-1)*160}
1548
                         + (V_{n} mod 2^b)*2^{n*160}
1549
       */
1550
0
      mpi_set_ui (value_w, 0);
1551
0
      for (value_k=0; value_k <= value_n; value_k++)
1552
0
        {
1553
          /* There is no need to have an explicit offset variable:  In
1554
             the first round we shall have an offset of 2, this is
1555
             achieved by using SEED_PLUS which is already at SEED+1,
1556
             thus we just need to increment it once again.  The
1557
             requirement for the next round is to update offset by N,
1558
             which we implictly did at the end of this loop, and then
1559
             to add one; this one is the same as in the first round.  */
1560
0
          for (i=seedlen-1; i >= 0; i--)
1561
0
            {
1562
0
              seed_plus[i]++;
1563
0
              if (seed_plus[i])
1564
0
                break;
1565
0
            }
1566
0
          _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen);
1567
1568
0
          _gcry_mpi_release (tmpval); tmpval = NULL;
1569
0
          ec = _gcry_mpi_scan (&tmpval, GCRYMPI_FMT_USG,
1570
0
                               digest, sizeof digest, NULL);
1571
0
          if (ec)
1572
0
            goto leave;
1573
0
          if (value_k == value_n)
1574
0
            mpi_clear_highbit (tmpval, value_b); /* (V_n mod 2^b) */
1575
0
          mpi_lshift (tmpval, tmpval, value_k*qbits);
1576
0
          mpi_add (value_w, value_w, tmpval);
1577
0
        }
1578
1579
      /* Step 8 continued: X = W + 2^{L-1}  */
1580
0
      mpi_set_ui (value_x, 0);
1581
0
      mpi_set_highbit (value_x, pbits-1);
1582
0
      mpi_add (value_x, value_x, value_w);
1583
1584
      /* Step 9:  c = X mod 2q,  p = X - (c - 1)  */
1585
0
      mpi_mul_2exp (tmpval, prime_q, 1);
1586
0
      mpi_mod (tmpval, value_x, tmpval);
1587
0
      mpi_sub_ui (tmpval, tmpval, 1);
1588
0
      mpi_sub (prime_p, value_x, tmpval);
1589
1590
      /* Step 10: If  p < 2^{L-1}  skip the primality test.  */
1591
      /* Step 11 and 12: Primality test.  */
1592
0
      if (mpi_get_nbits (prime_p) >= pbits-1
1593
0
          && check_prime (prime_p, val_2, 64, NULL, NULL) )
1594
0
        break; /* Yes, P is prime, continue with Step 15.  */
1595
1596
      /* Step 13: counter = counter + 1, offset = offset + n + 1. */
1597
0
      counter++;
1598
1599
      /* Step 14: If counter >= 2^12  goto Step 1.  */
1600
0
      if (counter >= 4096)
1601
0
        goto restart;
1602
0
    }
1603
1604
  /* Step 15:  Save p, q, counter and seed.  */
1605
/*   log_debug ("fips186-2 pbits p=%u q=%u counter=%d\n", */
1606
/*              mpi_get_nbits (prime_p), mpi_get_nbits (prime_q), counter); */
1607
/*   log_printhex("fips186-2 seed:", seed, seedlen); */
1608
/*   log_mpidump ("fips186-2 prime p", prime_p); */
1609
/*   log_mpidump ("fips186-2 prime q", prime_q); */
1610
0
  if (r_q)
1611
0
    {
1612
0
      *r_q = prime_q;
1613
0
      prime_q = NULL;
1614
0
    }
1615
0
  if (r_p)
1616
0
    {
1617
0
      *r_p = prime_p;
1618
0
      prime_p = NULL;
1619
0
    }
1620
0
  if (r_counter)
1621
0
    *r_counter = counter;
1622
0
  if (r_seed && r_seedlen)
1623
0
    {
1624
0
      memcpy (seed_plus, seed, seedlen);
1625
0
      *r_seed = seed_plus;
1626
0
      seed_plus = NULL;
1627
0
      *r_seedlen = seedlen;
1628
0
    }
1629
1630
1631
0
 leave:
1632
0
  _gcry_mpi_release (tmpval);
1633
0
  _gcry_mpi_release (value_x);
1634
0
  _gcry_mpi_release (value_w);
1635
0
  _gcry_mpi_release (prime_p);
1636
0
  _gcry_mpi_release (prime_q);
1637
0
  xfree (seed_plus);
1638
0
  _gcry_mpi_release (val_2);
1639
0
  return ec;
1640
0
}
1641
1642
1643

1644
/* WARNING: The code below has not yet been tested!
1645
 *
1646
 * Generate the two prime used for DSA using the algorithm specified
1647
 * in FIPS 186-3, A.1.1.2.  PBITS is the desired length of the prime P
1648
 * and a QBITS the length of the prime Q.  If SEED is not supplied and
1649
 * SEEDLEN is 0 the function generates an appropriate SEED.  On
1650
 * success the generated primes are stored at R_Q and R_P, the counter
1651
 * value is stored at R_COUNTER and the seed actually used for
1652
 * generation is stored at R_SEED and R_SEEDVALUE.  The hash algorithm
1653
 * used is stored at R_HASHALGO.
1654
 *
1655
 * Note that this function is very similar to the fips186_2 code.  Due
1656
 * to the minor differences, other buffer sizes and for documentarion,
1657
 * we use a separate function.
1658
 */
1659
gpg_err_code_t
1660
_gcry_generate_fips186_3_prime (unsigned int pbits, unsigned int qbits,
1661
                                const void *seed, size_t seedlen,
1662
                                gcry_mpi_t *r_q, gcry_mpi_t *r_p,
1663
                                int *r_counter,
1664
                                void **r_seed, size_t *r_seedlen,
1665
                                int *r_hashalgo)
1666
0
{
1667
0
  gpg_err_code_t ec;
1668
0
  unsigned char seed_help_buffer[256/8];  /* Used to hold a generated SEED. */
1669
0
  unsigned char *seed_plus;     /* Malloced buffer to hold SEED+x.  */
1670
0
  unsigned char digest[256/8];  /* Helper buffer for SHA-2 digest.  */
1671
0
  gcry_mpi_t val_2 = NULL;      /* Helper for the prime test.  */
1672
0
  gcry_mpi_t tmpval = NULL;     /* Helper variable.  */
1673
0
  int hashalgo;                 /* The id of the Approved Hash Function.  */
1674
0
  int i;
1675
1676
0
  unsigned char value_u[256/8];
1677
0
  int value_n, value_b, value_j;
1678
0
  int counter;
1679
0
  gcry_mpi_t value_w = NULL;
1680
0
  gcry_mpi_t value_x = NULL;
1681
0
  gcry_mpi_t prime_q = NULL;
1682
0
  gcry_mpi_t prime_p = NULL;
1683
1684
0
  gcry_assert (sizeof seed_help_buffer == sizeof digest
1685
0
               && sizeof seed_help_buffer == sizeof value_u);
1686
1687
  /* Step 1:  Check the requested prime lengths.  */
1688
  /* Note that due to the size of our buffers QBITS is limited to 256.  */
1689
0
  if (pbits == 2048 && qbits == 224)
1690
0
    hashalgo = GCRY_MD_SHA224;
1691
0
  else if (pbits == 2048 && qbits == 256)
1692
0
    hashalgo = GCRY_MD_SHA256;
1693
0
  else if (pbits == 3072 && qbits == 256)
1694
0
    hashalgo = GCRY_MD_SHA256;
1695
0
  else
1696
0
    return GPG_ERR_INV_KEYLEN;
1697
1698
  /* Also check that the hash algorithm is available.  */
1699
0
  ec = _gcry_md_test_algo (hashalgo);
1700
0
  if (ec)
1701
0
    return ec;
1702
0
  gcry_assert (qbits/8 <= sizeof digest);
1703
0
  gcry_assert (_gcry_md_get_algo_dlen (hashalgo) == qbits/8);
1704
1705
1706
  /* Step 2:  Check seedlen.  */
1707
0
  if (!seed && !seedlen)
1708
0
    ; /* No seed value given:  We are asked to generate it.  */
1709
0
  else if (!seed || seedlen < qbits/8)
1710
0
    return GPG_ERR_INV_ARG;
1711
1712
  /* Allocate a buffer to later compute SEED+some_increment and a few
1713
     helper variables.  */
1714
0
  seed_plus = xtrymalloc (seedlen < sizeof seed_help_buffer?
1715
0
                          sizeof seed_help_buffer : seedlen);
1716
0
  if (!seed_plus)
1717
0
    {
1718
0
      ec = gpg_err_code_from_syserror ();
1719
0
      goto leave;
1720
0
    }
1721
0
  val_2   = mpi_alloc_set_ui (2);
1722
0
  value_w = mpi_new (pbits);
1723
0
  value_x = mpi_new (pbits);
1724
1725
  /* Step 3: n = \lceil L / outlen \rceil - 1  */
1726
0
  value_n = (pbits + qbits - 1) / qbits - 1;
1727
  /* Step 4: b = L - 1 - (n * outlen)  */
1728
0
  value_b = pbits - 1 - (value_n * qbits);
1729
1730
0
 restart:
1731
  /* Generate Q.  */
1732
0
  for (;;)
1733
0
    {
1734
      /* Step 5:  Generate a (new) seed unless one has been supplied.  */
1735
0
      if (!seed)
1736
0
        {
1737
0
          seedlen = qbits/8;
1738
0
          gcry_assert (seedlen <= sizeof seed_help_buffer);
1739
0
          _gcry_create_nonce (seed_help_buffer, seedlen);
1740
0
          seed = seed_help_buffer;
1741
0
        }
1742
1743
      /* Step 6:  U = hash(seed)  */
1744
0
      _gcry_md_hash_buffer (hashalgo, value_u, seed, seedlen);
1745
1746
      /* Step 7:  q = 2^{N-1} + U + 1 - (U mod 2)  */
1747
0
      if ( !(value_u[qbits/8-1] & 0x01) )
1748
0
        {
1749
0
          for (i=qbits/8-1; i >= 0; i--)
1750
0
            {
1751
0
              value_u[i]++;
1752
0
              if (value_u[i])
1753
0
                break;
1754
0
            }
1755
0
        }
1756
0
      _gcry_mpi_release (prime_q); prime_q = NULL;
1757
0
      ec = _gcry_mpi_scan (&prime_q, GCRYMPI_FMT_USG,
1758
0
                           value_u, qbits/8, NULL);
1759
0
      if (ec)
1760
0
        goto leave;
1761
0
      mpi_set_highbit (prime_q, qbits-1 );
1762
1763
      /* Step 8:  Test whether Q is prime using 64 round of Rabin-Miller.
1764
                  According to table C.1 this is sufficient for all
1765
                  supported prime sizes (i.e. up 3072/256).  */
1766
0
      if (check_prime (prime_q, val_2, 64, NULL, NULL))
1767
0
        break; /* Yes, Q is prime.  */
1768
1769
      /* Step 8.  */
1770
0
      seed = NULL;  /* Force a new seed at Step 5.  */
1771
0
    }
1772
1773
  /* Step 11.  Note that we do no use an explicit offset but increment
1774
     SEED_PLUS accordingly.  */
1775
0
  memcpy (seed_plus, seed, seedlen);
1776
0
  counter = 0;
1777
1778
  /* Generate P. */
1779
0
  prime_p = mpi_new (pbits);
1780
0
  for (;;)
1781
0
    {
1782
      /* Step 11.1: For j = 0,...n let
1783
                      V_j = hash(seed+offset+j)
1784
         Step 11.2: W = V_0 + V_1*2^outlen +
1785
                            ...
1786
                            + V_{n-1}*2^{(n-1)*outlen}
1787
                            + (V_{n} mod 2^b)*2^{n*outlen}
1788
       */
1789
0
      mpi_set_ui (value_w, 0);
1790
0
      for (value_j=0; value_j <= value_n; value_j++)
1791
0
        {
1792
          /* There is no need to have an explicit offset variable: In
1793
             the first round we shall have an offset of 1 and a j of
1794
             0.  This is achieved by incrementing SEED_PLUS here.  For
1795
             the next round offset is implicitly updated by using
1796
             SEED_PLUS again.  */
1797
0
          for (i=seedlen-1; i >= 0; i--)
1798
0
            {
1799
0
              seed_plus[i]++;
1800
0
              if (seed_plus[i])
1801
0
                break;
1802
0
            }
1803
0
          _gcry_md_hash_buffer (hashalgo, digest, seed_plus, seedlen);
1804
1805
0
          _gcry_mpi_release (tmpval); tmpval = NULL;
1806
0
          ec = _gcry_mpi_scan (&tmpval, GCRYMPI_FMT_USG,
1807
0
                               digest, qbits/8, NULL);
1808
0
          if (ec)
1809
0
            goto leave;
1810
0
          if (value_j == value_n)
1811
0
            mpi_clear_highbit (tmpval, value_b); /* (V_n mod 2^b) */
1812
0
          mpi_lshift (tmpval, tmpval, value_j*qbits);
1813
0
          mpi_add (value_w, value_w, tmpval);
1814
0
        }
1815
1816
      /* Step 11.3: X = W + 2^{L-1}  */
1817
0
      mpi_set_ui (value_x, 0);
1818
0
      mpi_set_highbit (value_x, pbits-1);
1819
0
      mpi_add (value_x, value_x, value_w);
1820
1821
      /* Step 11.4:  c = X mod 2q  */
1822
0
      mpi_mul_2exp (tmpval, prime_q, 1);
1823
0
      mpi_mod (tmpval, value_x, tmpval);
1824
1825
      /* Step 11.5:  p = X - (c - 1)  */
1826
0
      mpi_sub_ui (tmpval, tmpval, 1);
1827
0
      mpi_sub (prime_p, value_x, tmpval);
1828
1829
      /* Step 11.6: If  p < 2^{L-1}  skip the primality test.  */
1830
      /* Step 11.7 and 11.8: Primality test.  */
1831
0
      if (mpi_get_nbits (prime_p) >= pbits-1
1832
0
          && check_prime (prime_p, val_2, 64, NULL, NULL) )
1833
0
        break; /* Yes, P is prime, continue with Step 15.  */
1834
1835
      /* Step 11.9: counter = counter + 1, offset = offset + n + 1.
1836
                    If counter >= 4L  goto Step 5.  */
1837
0
      counter++;
1838
0
      if (counter >= 4*pbits)
1839
0
        goto restart;
1840
0
    }
1841
1842
  /* Step 12:  Save p, q, counter and seed.  */
1843
  /* log_debug ("fips186-3 pbits p=%u q=%u counter=%d\n", */
1844
  /*            mpi_get_nbits (prime_p), mpi_get_nbits (prime_q), counter); */
1845
  /* log_printhex ("fips186-3 seed", seed, seedlen); */
1846
  /* log_printmpi ("fips186-3    p", prime_p); */
1847
  /* log_printmpi ("fips186-3    q", prime_q); */
1848
1849
0
  if (r_q)
1850
0
    {
1851
0
      *r_q = prime_q;
1852
0
      prime_q = NULL;
1853
0
    }
1854
0
  if (r_p)
1855
0
    {
1856
0
      *r_p = prime_p;
1857
0
      prime_p = NULL;
1858
0
    }
1859
0
  if (r_counter)
1860
0
    *r_counter = counter;
1861
0
  if (r_seed && r_seedlen)
1862
0
    {
1863
0
      memcpy (seed_plus, seed, seedlen);
1864
0
      *r_seed = seed_plus;
1865
0
      seed_plus = NULL;
1866
0
      *r_seedlen = seedlen;
1867
0
    }
1868
0
  if (r_hashalgo)
1869
0
    *r_hashalgo = hashalgo;
1870
1871
0
 leave:
1872
0
  _gcry_mpi_release (tmpval);
1873
0
  _gcry_mpi_release (value_x);
1874
0
  _gcry_mpi_release (value_w);
1875
0
  _gcry_mpi_release (prime_p);
1876
0
  _gcry_mpi_release (prime_q);
1877
0
  xfree (seed_plus);
1878
0
  _gcry_mpi_release (val_2);
1879
0
  return ec;
1880
0
}