~darkmuggle-deactivatedaccount/ubuntu/quantal/grub2/fix-872244

« back to all changes in this revision

Viewing changes to grub-core/lib/libgcrypt-grub/cipher/primegen.c

  • Committer: Bazaar Package Importer
  • Author(s): Colin Watson, Colin Watson, Evan Broder, Mario Limonciello
  • Date: 2010-11-24 13:59:55 UTC
  • mfrom: (1.17.6 upstream) (17.6.15 experimental)
  • Revision ID: james.westby@ubuntu.com-20101124135955-r6ii5sepayr7jt53
Tags: 1.99~20101124-1ubuntu1
[ Colin Watson ]
* Resynchronise with Debian experimental.  Remaining changes:
  - Adjust for default Ubuntu boot options ("quiet splash").
  - Default to hiding the menu; holding down Shift at boot will show it.
  - Set a monochromatic theme for Ubuntu.
  - Apply Ubuntu GRUB Legacy changes to legacy update-grub script: title,
    recovery mode, quiet option, tweak how memtest86+ is displayed, and
    use UUIDs where appropriate.
  - Fix backslash-escaping in merge_debconf_into_conf.
  - Remove "GNU/Linux" from default distributor string.
  - Add crashkernel= options if kdump and makedumpfile are available.
  - If other operating systems are installed, then automatically unhide
    the menu.  Otherwise, if GRUB_HIDDEN_TIMEOUT is 0, then use keystatus
    if available to check whether Shift is pressed.  If it is, show the
    menu, otherwise boot immediately.  If keystatus is not available, then
    fall back to a short delay interruptible with Escape.
  - Allow Shift to interrupt 'sleep --interruptible'.
  - Don't display introductory message about line editing unless we're
    actually offering a shell prompt.  Don't clear the screen just before
    booting if we never drew the menu in the first place.
  - Remove some verbose messages printed before reading the configuration
    file.
  - Suppress progress messages as the kernel and initrd load for
    non-recovery kernel menu entries.
  - Change prepare_grub_to_access_device to handle filesystems
    loop-mounted on file images.
  - Ignore devices loop-mounted from files in 10_linux.
  - Show the boot menu if the previous boot failed, that is if it failed
    to get to the end of one of the normal runlevels.
  - Don't generate /boot/grub/device.map during grub-install or
    grub-mkconfig by default.
  - Adjust upgrade version checks for Ubuntu.
  - Don't display "GRUB loading" unless Shift is held down.
  - Adjust versions of grub-doc and grub-legacy-doc conflicts to tolerate
    our backport of the grub-doc split.
  - Fix LVM/RAID probing in the absence of /boot/grub/device.map.
  - Look for .mo files in /usr/share/locale-langpack as well, in
    preference.
  - Make sure GRUB_TIMEOUT isn't quoted unnecessarily.
  - Probe all devices in 'grub-probe --target=drive' if
    /boot/grub/device.map is missing.
  - Build-depend on qemu-kvm rather than qemu-system for grub-pc tests.
  - Use qemu rather than qemu-system-i386.
  - Program vesafb on BIOS systems rather than efifb.
  - Add a grub-rescue-efi-amd64 package containing a rescue CD-ROM image
    for EFI-AMD64.
  - On Wubi, don't ask for an install device, but just update wubildr
    using the diverted grub-install.
  - When embedding the core image in a post-MBR gap, check for and avoid
    sectors matching any of a list of known signatures.
  - Disable video_bochs and video_cirrus on PC BIOS systems, as probing
    PCI space seems to break on some systems.
* Downgrade "ACPI shutdown failed" error to a debug message, since it can
  cause spurious test failures.

[ Evan Broder ]
* Enable lua from grub-extras.
* Incorporate the bitop library into lua.
* Add enum_pci function to grub module in lua.
* Switch back to gfxpayload=keep by default, unless the video hardware
  is known to not support it.

[ Mario Limonciello ]
* Built part_msdos and vfat into bootx64.efi (LP: #677758)

Show diffs side-by-side

added added

removed removed

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