1 /* primegen.c - prime number generator
2 * Copyright (C) 1998, 2000, 2001, 2002, 2003
3 * 2004, 2008 Free Software Foundation, Inc.
5 * This file is part of Libgcrypt.
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.
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.
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
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 );
42 static void (*progress_cb) (void *,const char*,int,int, int );
43 static void *progress_cb_data;
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,
129 static int no_of_small_prime_numbers = DIM (small_prime_numbers) - 1;
133 /* An object and a list to build up a global pool of primes. See
134 save_pool_prime and get_pool_prime. */
137 struct primepool_s *next;
138 gcry_mpi_t prime; /* If this is NULL the entry is not used. */
140 gcry_random_level_t randomlevel;
142 struct primepool_s *primepool;
143 /* Mutex used to protect access to the primepool. */
144 static ath_mutex_t primepool_lock;
148 _gcry_primegen_init (void)
152 ec = ath_mutex_init (&primepool_lock);
154 return gpg_err_code_from_errno (ec);
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
164 save_pool_prime (gcry_mpi_t prime, gcry_random_level_t randomlevel)
166 struct primepool_s *item, *item2;
169 for (n=0, item = primepool; item; item = item->next, n++)
172 if (!item && n > 100)
174 /* Remove some of the entries. Our strategy is removing
175 the last third from the list. */
178 for (i=0, item2 = primepool; item2; item2 = item2->next)
182 _gcry_mpi_release (item2->prime);
191 item = xtrycalloc (1, sizeof *item);
194 /* Out of memory. Silently giving up. */
195 _gcry_mpi_release (prime);
198 item->next = primepool;
202 item->nbits = mpi_get_nbits (prime);
203 item->randomlevel = randomlevel;
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. */
211 get_pool_prime (unsigned int nbits, gcry_random_level_t randomlevel)
213 struct primepool_s *item;
215 for (item = primepool; item; item = item->next)
217 && item->nbits == nbits && item->randomlevel == randomlevel)
219 gcry_mpi_t prime = item->prime;
221 gcry_assert (nbits == mpi_get_nbits (prime));
233 _gcry_register_primegen_progress ( void (*cb)(void *,const char*,int,int,int),
237 progress_cb_data = cb_data;
245 progress_cb ( progress_cb_data, "primegen", c, 0, 0 );
250 * Generate a prime number (stored in secure memory)
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)
260 prime = gen_prime (nbits, 1, random_level, extra_check, extra_check_arg);
266 /* Generate a prime number which may be public, i.e. not allocated in
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)
276 prime = gen_prime (nbits, 0, random_level, extra_check, extra_check_arg);
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.
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
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.
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,
311 gcry_prime_check_func_t cb_func, void *cb_arg)
313 gcry_err_code_t err = 0;
314 gcry_mpi_t *factors_new = NULL; /* Factors to return to the
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;
336 return GPG_ERR_INV_ARG;
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);
343 /* If QBITS is not given, assume a reasonable value. */
349 /* Find number of needed prime factors N. */
350 for (n = 1; (pbits - qbits - 1) / n >= qbits; n++)
354 val_2 = mpi_alloc_set_ui (2);
356 if ((! n) || ((need_q_factor) && (n < 2)))
358 err = GPG_ERR_INV_ARG;
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;
370 fbits = (pbits - req_qbits -1) / n;
371 qbits = pbits - n * fbits;
375 log_debug ("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n",
376 pbits, req_qbits, qbits, fbits, n);
378 /* Allocate an integer to old the new prime. */
379 prime = mpi_new (pbits);
381 /* Generate first prime factor. */
382 q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL);
384 /* Generate a specific Q-Factor if requested. */
386 q_factor = gen_prime (req_qbits, is_secret, randomlevel, NULL, NULL);
388 /* Allocate an array to hold all factors + 2 for later usage. */
389 factors = xtrycalloc (n + 2, sizeof (*factors));
392 err = gpg_err_code_from_errno (errno);
396 /* Allocate an array to track pool usage. */
397 pool_in_use = xtrymalloc (n * sizeof *pool_in_use);
400 err = gpg_err_code_from_errno (errno);
403 for (i=0; i < n; i++)
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.
409 Fixme: We need to research the best formula for sizing the pool.
412 if (need_q_factor) /* Need some more in this case. */
416 pool = xtrycalloc (m , sizeof (*pool));
419 err = gpg_err_code_from_errno (errno);
423 /* Permutate over the pool of primes until we find a prime of the
428 for (i=0; i < n; i++)
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++)
441 /* Init m_out_of_n(). */
442 perms = xtrycalloc (1, m);
445 err = gpg_err_code_from_errno (errno);
449 if (ath_mutex_lock (&primepool_lock))
451 err = GPG_ERR_INTERNAL;
455 for (i = 0; i < n; i++)
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. */
470 pool[i] = get_pool_prime (fbits, poolrandomlevel);
473 if (ath_mutex_unlock (&primepool_lock))
475 err = GPG_ERR_INTERNAL;
482 pool[i] = gen_prime (fbits, 0, poolrandomlevel, NULL, NULL);
484 factors[i] = pool[i];
486 if (is_locked && ath_mutex_unlock (&primepool_lock))
488 err = GPG_ERR_INTERNAL;
495 /* Get next permutation. */
496 m_out_of_n ( (char*)perms, n, m);
497 if (ath_mutex_lock (&primepool_lock))
499 err = GPG_ERR_INTERNAL;
503 for (i = j = 0; (i < m) && (j < n); i++)
506 /* If the subprime has not yet beed generated do it now. */
507 if (!pool[i] && is_locked)
509 pool[i] = get_pool_prime (fbits, poolrandomlevel);
512 if (ath_mutex_unlock (&primepool_lock))
514 err = GPG_ERR_INTERNAL;
521 pool[i] = gen_prime (fbits, 0, poolrandomlevel, NULL, NULL);
523 factors[j++] = pool[i];
525 if (is_locked && ath_mutex_unlock (&primepool_lock))
527 err = GPG_ERR_INTERNAL;
533 /* Ran out of permutations: Allocate new primes. */
541 /* Generate next prime candidate:
542 p = 2 * q [ * q_factor] * factor_0 * factor_1 * ... * factor_n + 1.
545 mpi_mul_ui (prime, prime, 2);
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);
561 q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL);
576 q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL);
583 while (! ((nprime == pbits) && check_prime (prime, val_2, 5,
589 log_mpidump ("prime ", prime);
590 log_mpidump ("factor q", q);
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));
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]));
606 /* Caller wants the factors. */
607 factors_new = xtrycalloc (n + 4, sizeof (*factors_new));
610 err = gpg_err_code_from_errno (errno);
617 factors_new[i++] = mpi_set_ui (NULL, 2);
618 factors_new[i++] = mpi_copy (q);
620 factors_new[i++] = mpi_copy (q_factor);
622 factors_new[i++] = mpi_copy (factors[j]);
629 factors_new[i++] = mpi_copy (q_factor);
631 factors_new[i] = mpi_copy (factors[i]);
635 factors_new[i] = mpi_copy (factors[i]);
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));
647 err = GPG_ERR_NOT_IMPLEMENTED;
651 factors[n + 1] = mpi_alloc_set_ui (2);
652 mpi_sub_ui (pmin1, prime, 1);
656 mpi_add_ui (g, g, 1);
658 log_printmpi ("checking g", g);
661 for (i = 0; i < n + 2; i++)
663 mpi_fdiv_q (tmp, pmin1, factors[i]);
664 /* No mpi_pow(), but it is okay to use this with mod
666 mpi_powm (b, g, tmp, prime);
667 if (! mpi_cmp_ui (b, 1))
675 mpi_free (factors[n+1]);
689 is_locked = !ath_mutex_lock (&primepool_lock);
690 for(i = 0; i < m; i++)
694 for (j=0; j < n; j++)
695 if (pool_in_use[j] == i)
697 if (j == n && is_locked)
699 /* This pooled subprime has not been used. */
700 save_pool_prime (pool[i], poolrandomlevel);
706 if (is_locked && ath_mutex_unlock (&primepool_lock))
707 err = GPG_ERR_INTERNAL;
713 xfree (factors); /* Factors are shallow copies. */
723 *prime_generated = prime;
725 *ret_factors = factors_new;
731 for (i = 0; factors_new[i]; i++)
732 mpi_free (factors_new[i]);
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
749 _gcry_generate_elg_prime (int mode, unsigned pbits, unsigned qbits,
751 gcry_mpi_t *r_prime, gcry_mpi_t **ret_factors)
756 return prime_generate_internal ((mode == 1), r_prime, pbits, qbits, g,
757 ret_factors, GCRY_WEAK_RANDOM, 0, 0,
763 gen_prime (unsigned int nbits, int secret, int randomlevel,
764 int (*extra_check)(void *, gcry_mpi_t), void *extra_check_arg)
766 gcry_mpi_t prime, ptest, pminus1, val_2, val_3, result;
768 unsigned int x, step;
769 unsigned int count1, count2;
772 /* if ( DBG_CIPHER ) */
773 /* log_debug ("generate a prime of %u bits ", nbits ); */
776 log_fatal ("can't generate a prime with less than %d bits\n", 16);
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 );
791 /* generate a random number */
792 _gcry_mpi_randomize( prime, nbits, randomlevel );
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);
800 mpi_set_bit (prime, nbits-2);
801 mpi_set_bit(prime, 0);
803 /* Calculate all remainders. */
804 for (i=0; (x = small_prime_numbers[i]); i++ )
805 mods[i] = mpi_fdiv_r_ui(NULL, prime, x);
807 /* Now try some primes starting with prime. */
808 for(step=0; step < 20000; step += 2 )
810 /* Check against all the small primes we have in mods. */
812 for (i=0; (x = small_prime_numbers[i]); i++ )
814 while ( mods[i] + step >= x )
816 if ( !(mods[i] + step) )
820 continue; /* Found a multiple of an already known prime. */
822 mpi_add_ui( ptest, prime, step );
824 /* Do a fast Fermat test now. */
826 mpi_sub_ui( pminus1, ptest, 1);
827 mpi_powm( result, val_2, pminus1, ptest );
828 if ( !mpi_cmp_ui( result, 1 ) )
830 /* Not composite, perform stronger tests */
831 if (is_prime(ptest, 5, &count2 ))
833 if (!mpi_test_bit( ptest, nbits-1-secret ))
836 log_debug ("overflow in prime generation\n");
837 break; /* Stop loop, continue with a new prime. */
840 if (extra_check && extra_check (extra_check_arg, ptest))
842 /* The extra check told us that this prime is
843 not of the caller's taste. */
859 if (++dotcount == 10 )
865 progress(':'); /* restart with a new random value */
870 * Returns: true if this may be a prime
871 * RM_ROUNDS gives the number of Rabin-Miller tests to run.
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)
879 unsigned int count=0;
881 /* Check against small primes. */
882 for (i=0; (x = small_prime_numbers[i]); i++ )
884 if ( mpi_divisible_ui( prime, x ) )
888 /* A quick Fermat test. */
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 );
895 if ( mpi_cmp_ui( result, 1 ) )
905 if (!cb_func || cb_func (cb_arg, GCRY_PRIME_CHECK_AT_MAYBE_PRIME, prime))
907 /* Perform stronger tests. */
908 if ( is_prime( prime, rm_rounds, &count ) )
911 || cb_func (cb_arg, GCRY_PRIME_CHECK_AT_GOT_PRIME, prime))
912 return 1; /* Probably a prime. */
921 * Return true if n is probably a prime
924 is_prime (gcry_mpi_t n, int steps, unsigned int *count)
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 );
934 unsigned nbits = mpi_get_nbits( n );
936 if (steps < 5) /* Make sure that we do at least 5 rounds. */
939 mpi_sub_ui( nminus1, n, 1 );
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);
946 for (i=0 ; i < steps; i++ )
955 _gcry_mpi_randomize( x, nbits, GCRY_WEAK_RANDOM );
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) )
961 mpi_set_highbit ( x, nbits-2); /* Clear all higher bits. */
965 mpi_set_highbit( x, nbits-2 );
966 mpi_clear_bit( x, nbits-2 );
968 gcry_assert (mpi_cmp (x, nminus1) < 0 && mpi_cmp_ui (x, 1) > 0);
970 mpi_powm ( y, x, q, n);
971 if ( mpi_cmp_ui(y, 1) && mpi_cmp( y, nminus1 ) )
973 for ( j=1; j < k && mpi_cmp( y, nminus1 ); j++ )
975 mpi_powm(y, y, a2, n);
976 if( !mpi_cmp_ui( y, 1 ) )
977 goto leave; /* Not a prime. */
979 if (mpi_cmp( y, nminus1 ) )
980 goto leave; /* Not a prime. */
984 rc = 1; /* May be a prime. */
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++)
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.
1014 m_out_of_n ( char *array, int m, int n )
1016 int i=0, i1=0, j=0, jp=0, j1=0, k1=0, k2=0;
1021 /* Need to handle this simple case separately. */
1024 for (i=0; i < n; i++ )
1039 for (j=1; j < n; j++ )
1041 if ( array[n-1] == array[n-j-1])
1068 else if( array[k2] && array[k2-1] )
1093 for (i=1; i <= jp; i++ )
1115 /* Now complement the two selected bits. */
1116 array[k1-1] = !array[k1-1];
1117 array[k2-1] = !array[k2-1];
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. */
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,
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;
1140 return GPG_ERR_INV_ARG;
1143 if (flags & GCRY_PRIME_FLAG_SPECIAL_FACTOR)
1147 rc = prime_generate_internal ((mode==1), &prime_generated, prime_bits,
1149 factors? &factors_generated : NULL,
1150 random_level, flags, 1,
1155 /* Additional check. */
1156 if ( !cb_func (cb_arg, GCRY_PRIME_CHECK_AT_FINISH, prime_generated))
1158 /* Failed, deallocate resources. */
1161 mpi_free (prime_generated);
1164 for (i = 0; factors_generated[i]; i++)
1165 mpi_free (factors_generated[i]);
1166 xfree (factors_generated);
1168 rc = GPG_ERR_GENERAL;
1175 *factors = factors_generated;
1176 *prime = prime_generated;
1182 /* Check whether the number X is prime. */
1184 _gcry_prime_check (gcry_mpi_t x, unsigned int flags)
1186 gcry_err_code_t rc = 0;
1187 gcry_mpi_t val_2 = mpi_alloc_set_ui (2); /* Used by the Fermat test. */
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;
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.*/
1206 _gcry_prime_group_generator (gcry_mpi_t *r_g,
1207 gcry_mpi_t prime, gcry_mpi_t *factors,
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);
1217 if (!factors || !r_g || !prime)
1218 return GPG_ERR_INV_ARG;
1221 for (n=0; factors[n]; n++)
1224 return GPG_ERR_INV_ARG;
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); */
1234 mpi_sub_ui (pmin1, prime, 1);
1240 mpi_add_ui (g, g, 1);
1243 log_printmpi ("checking g", g);
1247 for (i = 0; i < n; i++)
1249 mpi_fdiv_q (tmp, pmin1, factors[i]);
1250 mpi_powm (b, g, tmp, prime);
1251 if (! mpi_cmp_ui (b, 1))
1259 _gcry_mpi_release (tmp);
1260 _gcry_mpi_release (b);
1261 _gcry_mpi_release (pmin1);
1267 /* Convenience function to release the factors array. */
1269 _gcry_prime_release_factors (gcry_mpi_t *factors)
1275 for (i=0; factors[i]; i++)
1276 mpi_free (factors[i]);
1283 /* Helper for _gcry_derive_x931_prime. */
1285 find_x931_prime (const gcry_mpi_t pfirst)
1287 gcry_mpi_t val_2 = mpi_alloc_set_ui (2);
1290 prime = mpi_copy (pfirst);
1291 /* If P is even add 1. */
1292 mpi_set_bit (prime, 0);
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);
1307 /* Generate a prime using the algorithm from X9.31 appendix B.4.
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.
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. */
1316 _gcry_derive_x931_prime (const gcry_mpi_t xp,
1317 const gcry_mpi_t xp1, const gcry_mpi_t xp2,
1319 gcry_mpi_t *r_p1, gcry_mpi_t *r_p2)
1321 gcry_mpi_t p1, p2, p1p2, yp0;
1323 if (!xp || !xp1 || !xp2)
1325 if (!e || !mpi_test_bit (e, 0))
1326 return NULL; /* We support only odd values for E. */
1328 p1 = find_x931_prime (xp1);
1329 p2 = find_x931_prime (xp2);
1330 p1p2 = mpi_alloc_like (xp);
1331 mpi_mul (p1p2, p1, p2);
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);
1342 tmp = mpi_alloc_like (p2);
1343 mpi_invm (tmp, p1, p2);
1344 mpi_mul (tmp, tmp, p1);
1345 mpi_sub (r1, r1, tmp);
1347 /* Fixup a negative value. */
1348 if (mpi_has_sign (r1))
1349 mpi_add (r1, r1, p1p2);
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);
1357 /* Fixup a negative value. */
1358 if (mpi_cmp (yp0, xp) < 0 )
1359 mpi_add (yp0, yp0, p1p2);
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. */
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
1373 #CC1092495D867E64065DEE3E7955F2EBC7D47A2D
1374 7C9953388F97DDDC3E1CA19C35CA659EDC2FC4E3
1375 BF20CB896EE37E098A906313271422162CB6C642
1378 #CC1092495D867E64065DEE3E7955F2EBC7D47A2D
1379 7C9953388F97DDDC3E1CA19C35CA659EDC2FC2E6
1380 C88FE299D52D78BE405A97E01FD71DD7819ECB91
1382 as stated in the standard. This seems to be a bug in X9.31.
1386 gcry_mpi_t val_2 = mpi_alloc_set_ui (2);
1387 gcry_mpi_t gcdtmp = mpi_alloc_like (yp0);
1390 mpi_sub_ui (p1p2, p1p2, 1); /* Adjust for loop body. */
1391 mpi_sub_ui (yp0, yp0, 1); /* Ditto. */
1394 gcdres = mpi_gcd (gcdtmp, e, yp0);
1395 mpi_add_ui (yp0, yp0, 1);
1397 progress ('/'); /* gcd (e, yp0-1) != 1 */
1398 else if (check_prime (yp0, val_2, 64, NULL, NULL))
1400 /* We add p1p2-1 because yp0 is incremented after the gcd test. */
1401 mpi_add (yp0, yp0, p1p2);
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. */
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,
1435 void **r_seed, size_t *r_seedlen)
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. */
1445 unsigned char value_u[160/8];
1446 int value_n, value_b, value_k;
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;
1453 /* FIPS 186-2 allows only for 1024/160 bit. */
1454 if (pbits != 1024 || qbits != 160)
1455 return GPG_ERR_INV_KEYLEN;
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;
1462 /* Allocate a buffer to later compute SEED+some_increment. */
1463 seed_plus = xtrymalloc (seedlen < 20? 20:seedlen);
1466 ec = gpg_err_code_from_syserror ();
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);
1480 /* Step 1: Generate a (new) seed unless one has been supplied. */
1483 seedlen = sizeof seed_help_buffer;
1484 _gcry_create_nonce (seed_help_buffer, seedlen);
1485 seed = seed_help_buffer;
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--)
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];
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);
1507 mpi_set_highbit (prime_q, qbits-1 );
1508 mpi_set_bit (prime_q, 0);
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. */
1515 seed = NULL; /* Force a new seed at Step 1. */
1518 /* Step 6. Note that we do no use an explicit offset but increment
1519 SEED_PLUS accordingly. SEED_PLUS is currently SEED+1. */
1523 prime_p = mpi_new (pbits);
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 +
1530 + V_{n-1}*2^{(n-1)*160}
1531 + (V_{n} mod 2^b)*2^{n*160}
1533 mpi_set_ui (value_w, 0);
1534 for (value_k=0; value_k <= value_n; value_k++)
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--)
1549 _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen);
1551 _gcry_mpi_release (tmpval); tmpval = NULL;
1552 ec = _gcry_mpi_scan (&tmpval, GCRYMPI_FMT_USG,
1553 digest, sizeof digest, NULL);
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);
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);
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);
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. */
1579 /* Step 13: counter = counter + 1, offset = offset + n + 1. */
1582 /* Step 14: If counter >= 2^12 goto Step 1. */
1583 if (counter >= 4096)
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); */
1604 *r_counter = counter;
1605 if (r_seed && r_seedlen)
1607 memcpy (seed_plus, seed, seedlen);
1608 *r_seed = seed_plus;
1610 *r_seedlen = seedlen;
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);
1621 _gcry_mpi_release (val_2);
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
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.
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.
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,
1649 void **r_seed, size_t *r_seedlen,
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. */
1661 unsigned char value_u[256/8];
1662 int value_n, value_b, value_j;
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;
1669 gcry_assert (sizeof seed_help_buffer == sizeof digest
1670 && sizeof seed_help_buffer == sizeof value_u);
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;
1683 return GPG_ERR_INV_KEYLEN;
1685 /* Also check that the hash algorithm is available. */
1686 ec = _gcry_md_test_algo (hashalgo);
1689 gcry_assert (qbits/8 <= sizeof digest);
1690 gcry_assert (_gcry_md_get_algo_dlen (hashalgo) == qbits/8);
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;
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);
1705 ec = gpg_err_code_from_syserror ();
1708 val_2 = mpi_alloc_set_ui (2);
1709 value_w = mpi_new (pbits);
1710 value_x = mpi_new (pbits);
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);
1721 /* Step 5: Generate a (new) seed unless one has been supplied. */
1725 gcry_assert (seedlen <= sizeof seed_help_buffer);
1726 _gcry_create_nonce (seed_help_buffer, seedlen);
1727 seed = seed_help_buffer;
1730 /* Step 6: U = hash(seed) */
1731 _gcry_md_hash_buffer (hashalgo, value_u, seed, seedlen);
1733 /* Step 7: q = 2^{N-1} + U + 1 - (U mod 2) */
1734 if ( !(value_u[qbits/8-1] & 0x01) )
1736 for (i=qbits/8-1; i >= 0; i--)
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);
1748 mpi_set_highbit (prime_q, qbits-1 );
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. */
1757 seed = NULL; /* Force a new seed at Step 5. */
1760 /* Step 11. Note that we do no use an explicit offset but increment
1761 SEED_PLUS accordingly. */
1762 memcpy (seed_plus, seed, seedlen);
1766 prime_p = mpi_new (pbits);
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 +
1773 + V_{n-1}*2^{(n-1)*outlen}
1774 + (V_{n} mod 2^b)*2^{n*outlen}
1776 mpi_set_ui (value_w, 0);
1777 for (value_j=0; value_j <= value_n; value_j++)
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
1784 for (i=seedlen-1; i >= 0; i--)
1790 _gcry_md_hash_buffer (GCRY_MD_SHA1, digest, seed_plus, seedlen);
1792 _gcry_mpi_release (tmpval); tmpval = NULL;
1793 ec = _gcry_mpi_scan (&tmpval, GCRYMPI_FMT_USG,
1794 digest, sizeof digest, NULL);
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);
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);
1808 /* Step 11.4: c = X mod 2q */
1809 mpi_mul_2exp (tmpval, prime_q, 1);
1810 mpi_mod (tmpval, value_x, tmpval);
1812 /* Step 11.5: p = X - (c - 1) */
1813 mpi_sub_ui (tmpval, tmpval, 1);
1814 mpi_sub (prime_p, value_x, tmpval);
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. */
1822 /* Step 11.9: counter = counter + 1, offset = offset + n + 1.
1823 If counter >= 4L goto Step 5. */
1825 if (counter >= 4*pbits)
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);
1846 *r_counter = counter;
1847 if (r_seed && r_seedlen)
1849 memcpy (seed_plus, seed, seedlen);
1850 *r_seed = seed_plus;
1852 *r_seedlen = seedlen;
1855 *r_hashalgo = hashalgo;
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);
1864 _gcry_mpi_release (val_2);