primegen.c 55 KB

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