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