prime.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /*
  2. * Prime generation.
  3. */
  4. #include <assert.h>
  5. #include <math.h>
  6. #include "ssh.h"
  7. #include "mpint.h"
  8. #include "mpunsafe.h"
  9. #include "sshkeygen.h"
  10. /* ----------------------------------------------------------------------
  11. * Standard probabilistic prime-generation algorithm:
  12. *
  13. * - get a number from our PrimeCandidateSource which will at least
  14. * avoid being divisible by any prime under 2^16
  15. *
  16. * - perform the Miller-Rabin primality test enough times to
  17. * ensure the probability of it being composite is 2^-80 or
  18. * less
  19. *
  20. * - go back to square one if any M-R test fails.
  21. */
  22. static PrimeGenerationContext *probprime_new_context(
  23. const PrimeGenerationPolicy *policy)
  24. {
  25. PrimeGenerationContext *ctx = snew(PrimeGenerationContext);
  26. ctx->vt = policy;
  27. return ctx;
  28. }
  29. static void probprime_free_context(PrimeGenerationContext *ctx)
  30. {
  31. sfree(ctx);
  32. }
  33. static ProgressPhase probprime_add_progress_phase(
  34. const PrimeGenerationPolicy *policy,
  35. ProgressReceiver *prog, unsigned bits)
  36. {
  37. /*
  38. * The density of primes near x is 1/(log x). When x is about 2^b,
  39. * that's 1/(b log 2).
  40. *
  41. * But we're only doing the expensive part of the process (the M-R
  42. * checks) for a number that passes the initial winnowing test of
  43. * having no factor less than 2^16 (at least, unless the prime is
  44. * so small that PrimeCandidateSource gives up on that winnowing).
  45. * The density of _those_ numbers is about 1/19.76. So the odds of
  46. * hitting a prime per expensive attempt are boosted by a factor
  47. * of 19.76.
  48. */
  49. const double log_2 = 0.693147180559945309417232121458;
  50. double winnow_factor = (bits < 32 ? 1.0 : 19.76);
  51. double prob = winnow_factor / (bits * log_2);
  52. /*
  53. * Estimate the cost of prime generation as the cost of the M-R
  54. * modexps.
  55. */
  56. double cost = (miller_rabin_checks_needed(bits) *
  57. estimate_modexp_cost(bits));
  58. return progress_add_probabilistic(prog, cost, prob);
  59. }
  60. static mp_int *probprime_generate(
  61. PrimeGenerationContext *ctx,
  62. PrimeCandidateSource *pcs, ProgressReceiver *prog)
  63. {
  64. pcs_ready(pcs);
  65. while (true) {
  66. progress_report_attempt(prog);
  67. mp_int *p = pcs_generate(pcs);
  68. if (!p) {
  69. pcs_free(pcs);
  70. return NULL;
  71. }
  72. MillerRabin *mr = miller_rabin_new(p);
  73. bool known_bad = false;
  74. unsigned nchecks = miller_rabin_checks_needed(mp_get_nbits(p));
  75. for (unsigned check = 0; check < nchecks; check++) {
  76. if (!miller_rabin_test_random(mr)) {
  77. known_bad = true;
  78. break;
  79. }
  80. }
  81. miller_rabin_free(mr);
  82. if (!known_bad) {
  83. /*
  84. * We have a prime!
  85. */
  86. pcs_free(pcs);
  87. return p;
  88. }
  89. mp_free(p);
  90. }
  91. }
  92. static strbuf *null_mpu_certificate(PrimeGenerationContext *ctx, mp_int *p)
  93. {
  94. return NULL;
  95. }
  96. const PrimeGenerationPolicy primegen_probabilistic = {
  97. probprime_add_progress_phase,
  98. probprime_new_context,
  99. probprime_free_context,
  100. probprime_generate,
  101. null_mpu_certificate,
  102. };
  103. /* ----------------------------------------------------------------------
  104. * Alternative provable-prime algorithm, based on the following paper:
  105. *
  106. * [MAURER] Maurer, U.M. Fast generation of prime numbers and secure
  107. * public-key cryptographic parameters. J. Cryptology 8, 123–155
  108. * (1995). https://doi.org/10.1007/BF00202269
  109. */
  110. typedef enum SubprimePolicy {
  111. SPP_FAST,
  112. SPP_MAURER_SIMPLE,
  113. SPP_MAURER_COMPLEX,
  114. } SubprimePolicy;
  115. typedef struct ProvablePrimePolicyExtra {
  116. SubprimePolicy spp;
  117. } ProvablePrimePolicyExtra;
  118. typedef struct ProvablePrimeContext ProvablePrimeContext;
  119. struct ProvablePrimeContext {
  120. Pockle *pockle;
  121. PrimeGenerationContext pgc;
  122. const ProvablePrimePolicyExtra *extra;
  123. };
  124. static PrimeGenerationContext *provableprime_new_context(
  125. const PrimeGenerationPolicy *policy)
  126. {
  127. ProvablePrimeContext *ppc = snew(ProvablePrimeContext);
  128. ppc->pgc.vt = policy;
  129. ppc->pockle = pockle_new();
  130. ppc->extra = policy->extra;
  131. return &ppc->pgc;
  132. }
  133. static void provableprime_free_context(PrimeGenerationContext *ctx)
  134. {
  135. ProvablePrimeContext *ppc = container_of(ctx, ProvablePrimeContext, pgc);
  136. pockle_free(ppc->pockle);
  137. sfree(ppc);
  138. }
  139. static ProgressPhase provableprime_add_progress_phase(
  140. const PrimeGenerationPolicy *policy,
  141. ProgressReceiver *prog, unsigned bits)
  142. {
  143. /*
  144. * Estimating the cost of making a _provable_ prime is difficult
  145. * because of all the recursions to smaller sizes.
  146. *
  147. * Once you have enough factors of p-1 to certify primality of p,
  148. * the remaining work in provable prime generation is not very
  149. * different from probabilistic: you generate a random candidate,
  150. * test its primality probabilistically, and use the witness value
  151. * generated as a byproduct of that test for the full Pocklington
  152. * verification. The expensive part, as usual, is made of modpows.
  153. *
  154. * The Pocklington test needs at least two modpows (one for the
  155. * Fermat check, and one per known factor of p-1).
  156. *
  157. * The prior M-R step needs an unknown number, because we iterate
  158. * until we find a value whose order is divisible by the largest
  159. * power of 2 that divides p-1, say 2^j. That excludes half the
  160. * possible witness values (specifically, the quadratic residues),
  161. * so we expect to need on average two M-R operations to find one.
  162. * But that's only if the number _is_ prime - as usual, it's also
  163. * possible that we hit a non-prime and have to try again.
  164. *
  165. * So, if we were only estimating the cost of that final step, it
  166. * would look a lot like the probabilistic version: we'd have to
  167. * estimate the expected total number of modexps by knowing
  168. * something about the density of primes among our candidate
  169. * integers, and then multiply that by estimate_modexp_cost(bits).
  170. * But the problem is that we also have to _find_ a smaller prime,
  171. * so we have to recurse.
  172. *
  173. * In the MAURER_SIMPLE version of the algorithm, you recurse to
  174. * any one of a range of possible smaller sizes i, each with
  175. * probability proportional to 1/i. So your expected time to
  176. * generate an n-bit prime is given by a horrible recurrence of
  177. * the form E_n = S_n + (sum E_i/i) / (sum 1/i), in which S_n is
  178. * the expected cost of the final step once you have your smaller
  179. * primes, and both sums are over ceil(n/2) <= i <= n-20.
  180. *
  181. * At this point I ran out of effort to actually do the maths
  182. * rigorously, so instead I did the empirical experiment of
  183. * generating that sequence in Python and plotting it on a graph.
  184. * My Python code is here, in case I need it again:
  185. from math import log
  186. alpha = log(3)/log(2) + 1 # exponent for modexp using Karatsuba mult
  187. E = [1] * 16 # assume generating tiny primes is trivial
  188. for n in range(len(E), 4096):
  189. # Expected time for sub-generations, as a weighted mean of prior
  190. # values of the same sequence.
  191. lo = (n+1)//2
  192. hi = n-20
  193. if lo <= hi:
  194. subrange = range(lo, hi+1)
  195. num = sum(E[i]/i for i in subrange)
  196. den = sum(1/i for i in subrange)
  197. else:
  198. num, den = 0, 1
  199. # Constant term (cost of final step).
  200. # Similar to probprime_add_progress_phase.
  201. winnow_factor = 1 if n < 32 else 19.76
  202. prob = winnow_factor / (n * log(2))
  203. cost = 4 * n**alpha / prob
  204. E.append(cost + num / den)
  205. for i, p in enumerate(E):
  206. try:
  207. print(log(i), log(p))
  208. except ValueError:
  209. continue
  210. * The output loop prints the logs of both i and E_i, so that when
  211. * I plot the resulting data file in gnuplot I get a log-log
  212. * diagram. That showed me some early noise and then a very
  213. * straight-looking line; feeding the straight part of the graph
  214. * to linear-regression analysis reported that it fits the line
  215. *
  216. * log E_n = -1.7901825337965498 + 3.6199197179662517 * log(n)
  217. * => E_n = 0.16692969657466802 * n^3.6199197179662517
  218. *
  219. * So my somewhat empirical estimate is that Maurer prime
  220. * generation costs about 0.167 * bits^3.62, in the same arbitrary
  221. * time units used by estimate_modexp_cost.
  222. */
  223. return progress_add_linear(prog, 0.167 * pow(bits, 3.62));
  224. }
  225. static mp_int *primegen_small(Pockle *pockle, PrimeCandidateSource *pcs)
  226. {
  227. assert(pcs_get_bits(pcs) <= 32);
  228. pcs_ready(pcs);
  229. while (true) {
  230. mp_int *p = pcs_generate(pcs);
  231. if (!p) {
  232. pcs_free(pcs);
  233. return NULL;
  234. }
  235. if (pockle_add_small_prime(pockle, p) == POCKLE_OK) {
  236. pcs_free(pcs);
  237. return p;
  238. }
  239. mp_free(p);
  240. }
  241. }
  242. #ifdef DEBUG_PRIMEGEN
  243. static void timestamp(FILE *fp)
  244. {
  245. struct timespec ts;
  246. clock_gettime(CLOCK_MONOTONIC, &ts);
  247. fprintf(fp, "%lu.%09lu: ", (unsigned long)ts.tv_sec,
  248. (unsigned long)ts.tv_nsec);
  249. }
  250. static PRINTF_LIKE(1, 2) void debug_f(const char *fmt, ...)
  251. {
  252. va_list ap;
  253. va_start(ap, fmt);
  254. timestamp(stderr);
  255. vfprintf(stderr, fmt, ap);
  256. fputc('\n', stderr);
  257. va_end(ap);
  258. }
  259. static void debug_f_mp(const char *fmt, mp_int *x, ...)
  260. {
  261. va_list ap;
  262. va_start(ap, x);
  263. timestamp(stderr);
  264. vfprintf(stderr, fmt, ap);
  265. mp_dump(stderr, "", x, "\n");
  266. va_end(ap);
  267. }
  268. #else
  269. #define debug_f(...) ((void)0)
  270. #define debug_f_mp(...) ((void)0)
  271. #endif
  272. static double uniform_random_double(void)
  273. {
  274. unsigned char randbuf[8];
  275. random_read(randbuf, 8);
  276. return GET_64BIT_MSB_FIRST(randbuf) * 0x1.0p-64;
  277. }
  278. static mp_int *mp_ceil_div(mp_int *n, mp_int *d)
  279. {
  280. mp_int *nplus = mp_add(n, d);
  281. mp_sub_integer_into(nplus, nplus, 1);
  282. mp_int *toret = mp_div(nplus, d);
  283. mp_free(nplus);
  284. return toret;
  285. }
  286. static mp_int *provableprime_generate_inner(
  287. ProvablePrimeContext *ppc, PrimeCandidateSource *pcs,
  288. ProgressReceiver *prog, double progress_origin, double progress_scale)
  289. {
  290. unsigned bits = pcs_get_bits(pcs);
  291. assert(bits > 1);
  292. if (bits <= 32) {
  293. debug_f("ppgi(%u) -> small", bits);
  294. return primegen_small(ppc->pockle, pcs);
  295. }
  296. unsigned min_bits_needed, max_bits_needed;
  297. {
  298. /*
  299. * Find the product of all the prime factors we already know
  300. * about.
  301. */
  302. mp_int *size_got = mp_from_integer(1);
  303. size_t nfactors;
  304. mp_int **factors = pcs_get_known_prime_factors(pcs, &nfactors);
  305. for (size_t i = 0; i < nfactors; i++) {
  306. mp_int *to_free = size_got;
  307. size_got = mp_unsafe_shrink(mp_mul(size_got, factors[i]));
  308. mp_free(to_free);
  309. }
  310. /*
  311. * Find the largest cofactor we might be able to use, and the
  312. * smallest one we can get away with.
  313. */
  314. mp_int *upperbound = pcs_get_upper_bound(pcs);
  315. mp_int *size_needed = mp_nthroot(upperbound, 3, NULL);
  316. debug_f_mp("upperbound = ", upperbound);
  317. {
  318. mp_int *to_free = upperbound;
  319. upperbound = mp_unsafe_shrink(mp_div(upperbound, size_got));
  320. mp_free(to_free);
  321. }
  322. debug_f_mp("size_needed = ", size_needed);
  323. {
  324. mp_int *to_free = size_needed;
  325. size_needed = mp_unsafe_shrink(mp_ceil_div(size_needed, size_got));
  326. mp_free(to_free);
  327. }
  328. max_bits_needed = pcs_get_bits_remaining(pcs);
  329. /*
  330. * We need a prime that is greater than or equal to
  331. * 'size_needed' in order for the product of all our known
  332. * factors of p-1 to exceed the cube root of the largest value
  333. * p might take.
  334. *
  335. * Since pcs_new wants a size specified in bits, we must count
  336. * the bits in size_needed and then add 1. Otherwise we might
  337. * get a value with the same bit count as size_needed but
  338. * slightly smaller than it.
  339. *
  340. * An exception is if size_needed = 1. In that case the
  341. * product of existing known factors is _already_ enough, so
  342. * we don't need to generate an extra factor at all.
  343. */
  344. if (mp_hs_integer(size_needed, 2)) {
  345. min_bits_needed = mp_get_nbits(size_needed) + 1;
  346. } else {
  347. min_bits_needed = 0;
  348. }
  349. mp_free(upperbound);
  350. mp_free(size_needed);
  351. mp_free(size_got);
  352. }
  353. double progress = 0.0;
  354. if (min_bits_needed) {
  355. debug_f("ppgi(%u) recursing, need [%u,%u] more bits",
  356. bits, min_bits_needed, max_bits_needed);
  357. unsigned *sizes = NULL;
  358. size_t nsizes = 0, sizesize = 0;
  359. unsigned real_min = max_bits_needed / 2;
  360. unsigned real_max = (max_bits_needed >= 20 ?
  361. max_bits_needed - 20 : 0);
  362. if (real_min < min_bits_needed)
  363. real_min = min_bits_needed;
  364. if (real_max < real_min)
  365. real_max = real_min;
  366. debug_f("ppgi(%u) revised bits interval = [%u,%u]",
  367. bits, real_min, real_max);
  368. switch (ppc->extra->spp) {
  369. case SPP_FAST:
  370. /*
  371. * Always pick the smallest subsidiary prime we can get
  372. * away with: just over n/3 bits.
  373. *
  374. * This is not a good mode for cryptographic prime
  375. * generation, because it skews the distribution of primes
  376. * greatly, and worse, it skews them in a direction that
  377. * heads away from the properties crypto algorithms tend
  378. * to like.
  379. *
  380. * (For both discrete-log systems and RSA, people have
  381. * tended to recommend in the past that p-1 should have a
  382. * _large_ factor if possible. There's some disagreement
  383. * on which algorithms this is really necessary for, but
  384. * certainly I've never seen anyone recommend arranging a
  385. * _small_ factor on purpose.)
  386. *
  387. * I originally implemented this mode because it was
  388. * convenient for debugging - it wastes as little time as
  389. * possible on finding a sub-prime and lets you get to the
  390. * interesting part! And I leave it in the code because it
  391. * might still be useful for _something_. Because it's
  392. * cryptographically questionable, it's not selectable in
  393. * the UI of either version of PuTTYgen proper; but it can
  394. * be accessed through testcrypt, and if for some reason a
  395. * definite prime is needed for non-crypto purposes, it
  396. * may still be the fastest way to put your hands on one.
  397. */
  398. debug_f("ppgi(%u) fast mode, just ask for %u bits",
  399. bits, min_bits_needed);
  400. sgrowarray(sizes, sizesize, nsizes);
  401. sizes[nsizes++] = min_bits_needed;
  402. break;
  403. case SPP_MAURER_SIMPLE: {
  404. /*
  405. * Select the size of the subsidiary prime at random from
  406. * sqrt(outputprime) up to outputprime/2^20, in such a way
  407. * that the probability distribution matches that of the
  408. * largest prime factor of a random n-bit number.
  409. *
  410. * Per [MAURER] section 3.4, the cumulative distribution
  411. * function of this relative size is 1+log2(x), for x in
  412. * [1/2,1]. You can generate a value from the distribution
  413. * given by a cdf by applying the inverse cdf to a uniform
  414. * value in [0,1]. Simplifying that in this case, what we
  415. * have to do is raise 2 to the power of a random real
  416. * number between -1 and 0. (And that gives you the number
  417. * of _bits_ in the sub-prime, as a factor of the desired
  418. * output number of bits.)
  419. *
  420. * We also require that the subsidiary prime q is at least
  421. * 20 bits smaller than the output one, to give us a
  422. * fighting chance of there being _any_ prime we can find
  423. * such that q | p-1.
  424. *
  425. * (But these rules have to be applied in an order that
  426. * still leaves us _some_ interval of possible sizes we
  427. * can pick!)
  428. */
  429. maurer_simple:
  430. debug_f("ppgi(%u) Maurer simple mode", bits);
  431. unsigned sub_bits;
  432. do {
  433. double uniform = uniform_random_double();
  434. sub_bits = real_max * pow(2.0, uniform - 1) + 0.5;
  435. debug_f(" ... %.6f -> %u?", uniform, sub_bits);
  436. } while (!(real_min <= sub_bits && sub_bits <= real_max));
  437. debug_f("ppgi(%u) asking for %u bits", bits, sub_bits);
  438. sgrowarray(sizes, sizesize, nsizes);
  439. sizes[nsizes++] = sub_bits;
  440. break;
  441. }
  442. case SPP_MAURER_COMPLEX: {
  443. /*
  444. * In this mode, we may generate multiple factors of p-1
  445. * which between them add up to at least n/2 bits, in such
  446. * a way that those are guaranteed to be the largest
  447. * factors of p-1 and that they have the same probability
  448. * distribution as the largest k factors would have in a
  449. * random integer. The idea is that this more elaborate
  450. * procedure gets as close as possible to the same
  451. * probability distribution you'd get by selecting a
  452. * completely random prime (if you feasibly could).
  453. *
  454. * Algorithm from Appendix 1 of [MAURER]: we generate
  455. * random real numbers that sum to at most 1, by choosing
  456. * each one uniformly from the range [0, 1 - sum of all
  457. * the previous ones]. We maintain them in a list in
  458. * decreasing order, and we stop as soon as we find an
  459. * initial subsequence of the list s_1,...,s_r such that
  460. * s_1 + ... + s_{r-1} + 2 s_r > 1. In particular, this
  461. * guarantees that the sum of that initial subsequence is
  462. * at least 1/2, so we end up with enough factors to
  463. * satisfy Pocklington.
  464. */
  465. if (max_bits_needed / 2 + 1 > real_max) {
  466. /* Early exit path in the case where this algorithm
  467. * can't possibly generate a value in the range we
  468. * need. In that situation, fall back to Maurer
  469. * simple. */
  470. debug_f("ppgi(%u) skipping GenerateSizeList, "
  471. "real_max too small", bits);
  472. goto maurer_simple; /* sorry! */
  473. }
  474. double *s = NULL;
  475. size_t ns, ssize = 0;
  476. while (true) {
  477. debug_f("ppgi(%u) starting GenerateSizeList", bits);
  478. ns = 0;
  479. double range = 1.0;
  480. while (true) {
  481. /* Generate the next number */
  482. double u = uniform_random_double() * range;
  483. range -= u;
  484. debug_f(" u_%"SIZEu" = %g", ns, u);
  485. /* Insert it in the list */
  486. sgrowarray(s, ssize, ns);
  487. size_t i;
  488. for (i = ns; i > 0 && s[i-1] < u; i--)
  489. s[i] = s[i-1];
  490. s[i] = u;
  491. ns++;
  492. debug_f(" inserting as s[%"SIZEu"]", i);
  493. /* Look for a suitable initial subsequence */
  494. double sum = 0;
  495. for (i = 0; i < ns; i++) {
  496. sum += s[i];
  497. if (sum + s[i] > 1.0) {
  498. debug_f(" s[0..%"SIZEu"] works!", i);
  499. /* Truncate the sequence here, and stop
  500. * generating random real numbers. */
  501. ns = i+1;
  502. goto got_list;
  503. }
  504. }
  505. }
  506. got_list:;
  507. /*
  508. * Now translate those real numbers into actual bit
  509. * counts, and do a last-minute check to make sure
  510. * their product is going to be in range.
  511. *
  512. * We have to check both the min and max sizes of the
  513. * total. A b-bit number is in [2^{b-1},2^b). So the
  514. * product of numbers of sizes b_1,...,b_k is at least
  515. * 2^{\sum (b_i-1)}, and less than 2^{\sum b_i}.
  516. */
  517. nsizes = 0;
  518. unsigned min_total = 0, max_total = 0;
  519. for (size_t i = 0; i < ns; i++) {
  520. /* These sizes are measured in actual entropy, so
  521. * add 1 bit each time to account for the
  522. * zero-information leading 1 */
  523. unsigned this_size = max_bits_needed * s[i] + 1;
  524. debug_f(" bits[%"SIZEu"] = %u", i, this_size);
  525. sgrowarray(sizes, sizesize, nsizes);
  526. sizes[nsizes++] = this_size;
  527. min_total += this_size - 1;
  528. max_total += this_size;
  529. }
  530. debug_f(" total bits = [%u,%u)", min_total, max_total);
  531. if (min_total < real_min || max_total > real_max+1) {
  532. debug_f(" total out of range, try again");
  533. } else {
  534. debug_f(" success! %"SIZEu" sub-primes totalling [%u,%u) "
  535. "bits", nsizes, min_total, max_total);
  536. break;
  537. }
  538. }
  539. smemclr(s, ssize * sizeof(*s));
  540. sfree(s);
  541. break;
  542. }
  543. default:
  544. unreachable("bad subprime policy");
  545. }
  546. for (size_t i = 0; i < nsizes; i++) {
  547. unsigned sub_bits = sizes[i];
  548. double progress_in_this_prime = (double)sub_bits / bits;
  549. mp_int *q = provableprime_generate_inner(
  550. ppc, pcs_new(sub_bits),
  551. prog, progress_origin + progress_scale * progress,
  552. progress_scale * progress_in_this_prime);
  553. progress += progress_in_this_prime;
  554. assert(q);
  555. debug_f_mp("ppgi(%u) got factor ", q, bits);
  556. pcs_require_residue_1_mod_prime(pcs, q);
  557. mp_free(q);
  558. }
  559. smemclr(sizes, sizesize * sizeof(*sizes));
  560. sfree(sizes);
  561. } else {
  562. debug_f("ppgi(%u) no need to recurse", bits);
  563. }
  564. debug_f("ppgi(%u) ready, %u bits remaining",
  565. bits, pcs_get_bits_remaining(pcs));
  566. pcs_ready(pcs);
  567. while (true) {
  568. mp_int *p = pcs_generate(pcs);
  569. if (!p) {
  570. pcs_free(pcs);
  571. return NULL;
  572. }
  573. debug_f_mp("provable_step p=", p);
  574. MillerRabin *mr = miller_rabin_new(p);
  575. debug_f("provable_step mr setup done");
  576. mp_int *witness = miller_rabin_find_potential_primitive_root(mr);
  577. miller_rabin_free(mr);
  578. if (!witness) {
  579. debug_f("provable_step mr failed");
  580. mp_free(p);
  581. continue;
  582. }
  583. size_t nfactors;
  584. mp_int **factors = pcs_get_known_prime_factors(pcs, &nfactors);
  585. PockleStatus st = pockle_add_prime(
  586. ppc->pockle, p, factors, nfactors, witness);
  587. if (st != POCKLE_OK) {
  588. debug_f("provable_step proof failed %d", (int)st);
  589. /*
  590. * Check by assertion that the error status is not one of
  591. * the ones we ought to have ruled out already by
  592. * construction. If there's a bug in this code that means
  593. * we can _never_ pass this test (e.g. picking products of
  594. * factors that never quite reach cbrt(n)), we'd rather
  595. * fail an assertion than loop forever.
  596. */
  597. assert(st == POCKLE_DISCRIMINANT_IS_SQUARE ||
  598. st == POCKLE_WITNESS_POWER_IS_1 ||
  599. st == POCKLE_WITNESS_POWER_NOT_COPRIME);
  600. mp_free(p);
  601. if (witness)
  602. mp_free(witness);
  603. continue;
  604. }
  605. mp_free(witness);
  606. pcs_free(pcs);
  607. debug_f_mp("ppgi(%u) done, got ", p, bits);
  608. progress_report(prog, progress_origin + progress_scale);
  609. return p;
  610. }
  611. }
  612. static mp_int *provableprime_generate(
  613. PrimeGenerationContext *ctx,
  614. PrimeCandidateSource *pcs, ProgressReceiver *prog)
  615. {
  616. ProvablePrimeContext *ppc = container_of(ctx, ProvablePrimeContext, pgc);
  617. mp_int *p = provableprime_generate_inner(ppc, pcs, prog, 0.0, 1.0);
  618. return p;
  619. }
  620. static inline strbuf *provableprime_mpu_certificate(
  621. PrimeGenerationContext *ctx, mp_int *p)
  622. {
  623. ProvablePrimeContext *ppc = container_of(ctx, ProvablePrimeContext, pgc);
  624. return pockle_mpu(ppc->pockle, p);
  625. }
  626. #define DECLARE_POLICY(name, policy) \
  627. static const struct ProvablePrimePolicyExtra \
  628. pppextra_##name = {policy}; \
  629. const PrimeGenerationPolicy name = { \
  630. provableprime_add_progress_phase, \
  631. provableprime_new_context, \
  632. provableprime_free_context, \
  633. provableprime_generate, \
  634. provableprime_mpu_certificate, \
  635. &pppextra_##name, \
  636. }
  637. DECLARE_POLICY(primegen_provable_fast, SPP_FAST);
  638. DECLARE_POLICY(primegen_provable_maurer_simple, SPP_MAURER_SIMPLE);
  639. DECLARE_POLICY(primegen_provable_maurer_complex, SPP_MAURER_COMPLEX);
  640. /* ----------------------------------------------------------------------
  641. * Reusable null implementation of the progress-reporting API.
  642. */
  643. static inline ProgressPhase null_progress_add(void) {
  644. ProgressPhase ph = { .n = 0 };
  645. return ph;
  646. }
  647. ProgressPhase null_progress_add_linear(
  648. ProgressReceiver *prog, double c) { return null_progress_add(); }
  649. ProgressPhase null_progress_add_probabilistic(
  650. ProgressReceiver *prog, double c, double p) { return null_progress_add(); }
  651. void null_progress_ready(ProgressReceiver *prog) {}
  652. void null_progress_start_phase(ProgressReceiver *prog, ProgressPhase phase) {}
  653. void null_progress_report(ProgressReceiver *prog, double progress) {}
  654. void null_progress_report_attempt(ProgressReceiver *prog) {}
  655. void null_progress_report_phase_complete(ProgressReceiver *prog) {}
  656. const ProgressReceiverVtable null_progress_vt = {
  657. .add_linear = null_progress_add_linear,
  658. .add_probabilistic = null_progress_add_probabilistic,
  659. .ready = null_progress_ready,
  660. .start_phase = null_progress_start_phase,
  661. .report = null_progress_report,
  662. .report_attempt = null_progress_report_attempt,
  663. .report_phase_complete = null_progress_report_phase_complete,
  664. };
  665. /* ----------------------------------------------------------------------
  666. * Helper function for progress estimation.
  667. */
  668. double estimate_modexp_cost(unsigned bits)
  669. {
  670. /*
  671. * A modexp of n bits goes roughly like O(n^2.58), on the grounds
  672. * that our modmul is O(n^1.58) (Karatsuba) and you need O(n) of
  673. * them in a modexp.
  674. */
  675. return pow(bits, 2.58);
  676. }