]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/bn/bn_prime.c
7d89d321d86c577e2bbc751f7a745f01e72d2c4a
[thirdparty/openssl.git] / crypto / bn / bn_prime.c
1 /*
2 * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <stdio.h>
11 #include <time.h>
12 #include "internal/cryptlib.h"
13 #include "bn_local.h"
14
15 /*
16 * The quick sieve algorithm approach to weeding out primes is Philip
17 * Zimmermann's, as implemented in PGP. I have had a read of his comments
18 * and implemented my own version.
19 */
20 #include "bn_prime.h"
21
22 static int probable_prime(BIGNUM *rnd, int bits, int safe, prime_t *mods,
23 BN_CTX *ctx);
24 static int probable_prime_dh(BIGNUM *rnd, int bits, int safe, prime_t *mods,
25 const BIGNUM *add, const BIGNUM *rem,
26 BN_CTX *ctx);
27
28 #define square(x) ((BN_ULONG)(x) * (BN_ULONG)(x))
29
30 #if BN_BITS2 == 64
31 # define BN_DEF(lo, hi) (BN_ULONG)hi<<32|lo
32 #else
33 # define BN_DEF(lo, hi) lo, hi
34 #endif
35
36 /*
37 * See SP800 89 5.3.3 (Step f)
38 * The product of the set of primes ranging from 3 to 751
39 * Generated using process in test/bn_internal_test.c test_bn_small_factors().
40 * This includes 751 (which is not currently included in SP 800-89).
41 */
42 static const BN_ULONG small_prime_factors[] = {
43 BN_DEF(0x3ef4e3e1, 0xc4309333), BN_DEF(0xcd2d655f, 0x71161eb6),
44 BN_DEF(0x0bf94862, 0x95e2238c), BN_DEF(0x24f7912b, 0x3eb233d3),
45 BN_DEF(0xbf26c483, 0x6b55514b), BN_DEF(0x5a144871, 0x0a84d817),
46 BN_DEF(0x9b82210a, 0x77d12fee), BN_DEF(0x97f050b3, 0xdb5b93c2),
47 BN_DEF(0x4d6c026b, 0x4acad6b9), BN_DEF(0x54aec893, 0xeb7751f3),
48 BN_DEF(0x36bc85c4, 0xdba53368), BN_DEF(0x7f5ec78e, 0xd85a1b28),
49 BN_DEF(0x6b322244, 0x2eb072d8), BN_DEF(0x5e2b3aea, 0xbba51112),
50 BN_DEF(0x0e2486bf, 0x36ed1a6c), BN_DEF(0xec0c5727, 0x5f270460),
51 (BN_ULONG)0x000017b1
52 };
53
54 #define BN_SMALL_PRIME_FACTORS_TOP OSSL_NELEM(small_prime_factors)
55 static const BIGNUM _bignum_small_prime_factors = {
56 (BN_ULONG *)small_prime_factors,
57 BN_SMALL_PRIME_FACTORS_TOP,
58 BN_SMALL_PRIME_FACTORS_TOP,
59 0,
60 BN_FLG_STATIC_DATA
61 };
62
63 const BIGNUM *bn_get0_small_factors(void)
64 {
65 return &_bignum_small_prime_factors;
66 }
67
68 /*
69 * Calculate the number of trial divisions that gives the best speed in
70 * combination with Miller-Rabin prime test, based on the sized of the prime.
71 */
72 static int calc_trial_divisions(int bits)
73 {
74 if (bits <= 512)
75 return 64;
76 else if (bits <= 1024)
77 return 128;
78 else if (bits <= 2048)
79 return 384;
80 else if (bits <= 4096)
81 return 1024;
82 return NUMPRIMES;
83 }
84
85 int BN_GENCB_call(BN_GENCB *cb, int a, int b)
86 {
87 /* No callback means continue */
88 if (!cb)
89 return 1;
90 switch (cb->ver) {
91 case 1:
92 /* Deprecated-style callbacks */
93 if (!cb->cb.cb_1)
94 return 1;
95 cb->cb.cb_1(a, b, cb->arg);
96 return 1;
97 case 2:
98 /* New-style callbacks */
99 return cb->cb.cb_2(a, b, cb);
100 default:
101 break;
102 }
103 /* Unrecognised callback type */
104 return 0;
105 }
106
107 int BN_generate_prime_ex2(BIGNUM *ret, int bits, int safe,
108 const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb,
109 BN_CTX *ctx)
110 {
111 BIGNUM *t;
112 int found = 0;
113 int i, j, c1 = 0;
114 prime_t *mods = NULL;
115 int checks = BN_prime_checks_for_size(bits);
116
117 if (bits < 2) {
118 /* There are no prime numbers this small. */
119 BNerr(BN_F_BN_GENERATE_PRIME_EX2, BN_R_BITS_TOO_SMALL);
120 return 0;
121 } else if (add == NULL && safe && bits < 6 && bits != 3) {
122 /*
123 * The smallest safe prime (7) is three bits.
124 * But the following two safe primes with less than 6 bits (11, 23)
125 * are unreachable for BN_rand with BN_RAND_TOP_TWO.
126 */
127 BNerr(BN_F_BN_GENERATE_PRIME_EX2, BN_R_BITS_TOO_SMALL);
128 return 0;
129 }
130
131 mods = OPENSSL_zalloc(sizeof(*mods) * NUMPRIMES);
132 if (mods == NULL)
133 goto err;
134
135 BN_CTX_start(ctx);
136 t = BN_CTX_get(ctx);
137 if (t == NULL)
138 goto err;
139 loop:
140 /* make a random number and set the top and bottom bits */
141 if (add == NULL) {
142 if (!probable_prime(ret, bits, safe, mods, ctx))
143 goto err;
144 } else {
145 if (!probable_prime_dh(ret, bits, safe, mods, add, rem, ctx))
146 goto err;
147 }
148
149 if (!BN_GENCB_call(cb, 0, c1++))
150 /* aborted */
151 goto err;
152
153 if (!safe) {
154 i = BN_is_prime_fasttest_ex(ret, checks, ctx, 0, cb);
155 if (i == -1)
156 goto err;
157 if (i == 0)
158 goto loop;
159 } else {
160 /*
161 * for "safe prime" generation, check that (p-1)/2 is prime. Since a
162 * prime is odd, We just need to divide by 2
163 */
164 if (!BN_rshift1(t, ret))
165 goto err;
166
167 for (i = 0; i < checks; i++) {
168 j = BN_is_prime_fasttest_ex(ret, 1, ctx, 0, cb);
169 if (j == -1)
170 goto err;
171 if (j == 0)
172 goto loop;
173
174 j = BN_is_prime_fasttest_ex(t, 1, ctx, 0, cb);
175 if (j == -1)
176 goto err;
177 if (j == 0)
178 goto loop;
179
180 if (!BN_GENCB_call(cb, 2, c1 - 1))
181 goto err;
182 /* We have a safe prime test pass */
183 }
184 }
185 /* we have a prime :-) */
186 found = 1;
187 err:
188 OPENSSL_free(mods);
189 BN_CTX_end(ctx);
190 bn_check_top(ret);
191 return found;
192 }
193
194 #ifndef FIPS_MODE
195 int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe,
196 const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb)
197 {
198 BN_CTX *ctx = BN_CTX_new();
199 int retval;
200
201 if (ctx == NULL)
202 return 0;
203
204 retval = BN_generate_prime_ex2(ret, bits, safe, add, rem, cb, ctx);
205
206 BN_CTX_free(ctx);
207 return retval;
208 }
209 #endif
210
211 int BN_is_prime_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed,
212 BN_GENCB *cb)
213 {
214 return BN_is_prime_fasttest_ex(a, checks, ctx_passed, 0, cb);
215 }
216
217 /* See FIPS 186-4 C.3.1 Miller Rabin Probabilistic Primality Test. */
218 int BN_is_prime_fasttest_ex(const BIGNUM *w, int checks, BN_CTX *ctx,
219 int do_trial_division, BN_GENCB *cb)
220 {
221 int i, status, ret = -1;
222 #ifndef FIPS_MODE
223 BN_CTX *ctxlocal = NULL;
224 #else
225
226 if (ctx == NULL)
227 return -1;
228 #endif
229
230 /* w must be bigger than 1 */
231 if (BN_cmp(w, BN_value_one()) <= 0)
232 return 0;
233
234 /* w must be odd */
235 if (BN_is_odd(w)) {
236 /* Take care of the really small prime 3 */
237 if (BN_is_word(w, 3))
238 return 1;
239 } else {
240 /* 2 is the only even prime */
241 return BN_is_word(w, 2);
242 }
243
244 /* first look for small factors */
245 if (do_trial_division) {
246 int trial_divisions = calc_trial_divisions(BN_num_bits(w));
247
248 for (i = 1; i < trial_divisions; i++) {
249 BN_ULONG mod = BN_mod_word(w, primes[i]);
250 if (mod == (BN_ULONG)-1)
251 return -1;
252 if (mod == 0)
253 return BN_is_word(w, primes[i]);
254 }
255 if (!BN_GENCB_call(cb, 1, -1))
256 return -1;
257 }
258 #ifndef FIPS_MODE
259 if (ctx == NULL && (ctxlocal = ctx = BN_CTX_new()) == NULL)
260 goto err;
261 #endif
262
263 ret = bn_miller_rabin_is_prime(w, checks, ctx, cb, 0, &status);
264 if (!ret)
265 goto err;
266 ret = (status == BN_PRIMETEST_PROBABLY_PRIME);
267 err:
268 #ifndef FIPS_MODE
269 BN_CTX_free(ctxlocal);
270 #endif
271 return ret;
272 }
273
274 /*
275 * Refer to FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test.
276 * OR C.3.1 Miller-Rabin Probabilistic Primality Test (if enhanced is zero).
277 * The Step numbers listed in the code refer to the enhanced case.
278 *
279 * if enhanced is set, then status returns one of the following:
280 * BN_PRIMETEST_PROBABLY_PRIME
281 * BN_PRIMETEST_COMPOSITE_WITH_FACTOR
282 * BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME
283 * if enhanced is zero, then status returns either
284 * BN_PRIMETEST_PROBABLY_PRIME or
285 * BN_PRIMETEST_COMPOSITE
286 *
287 * returns 0 if there was an error, otherwise it returns 1.
288 */
289 int bn_miller_rabin_is_prime(const BIGNUM *w, int iterations, BN_CTX *ctx,
290 BN_GENCB *cb, int enhanced, int *status)
291 {
292 int i, j, a, ret = 0;
293 BIGNUM *g, *w1, *w3, *x, *m, *z, *b;
294 BN_MONT_CTX *mont = NULL;
295
296 /* w must be odd */
297 if (!BN_is_odd(w))
298 return 0;
299
300 BN_CTX_start(ctx);
301 g = BN_CTX_get(ctx);
302 w1 = BN_CTX_get(ctx);
303 w3 = BN_CTX_get(ctx);
304 x = BN_CTX_get(ctx);
305 m = BN_CTX_get(ctx);
306 z = BN_CTX_get(ctx);
307 b = BN_CTX_get(ctx);
308
309 if (!(b != NULL
310 /* w1 := w - 1 */
311 && BN_copy(w1, w)
312 && BN_sub_word(w1, 1)
313 /* w3 := w - 3 */
314 && BN_copy(w3, w)
315 && BN_sub_word(w3, 3)))
316 goto err;
317
318 /* check w is larger than 3, otherwise the random b will be too small */
319 if (BN_is_zero(w3) || BN_is_negative(w3))
320 goto err;
321
322 /* (Step 1) Calculate largest integer 'a' such that 2^a divides w-1 */
323 a = 1;
324 while (!BN_is_bit_set(w1, a))
325 a++;
326 /* (Step 2) m = (w-1) / 2^a */
327 if (!BN_rshift(m, w1, a))
328 goto err;
329
330 /* Montgomery setup for computations mod a */
331 mont = BN_MONT_CTX_new();
332 if (mont == NULL || !BN_MONT_CTX_set(mont, w, ctx))
333 goto err;
334
335 if (iterations == BN_prime_checks)
336 iterations = BN_prime_checks_for_size(BN_num_bits(w));
337
338 /* (Step 4) */
339 for (i = 0; i < iterations; ++i) {
340 /* (Step 4.1) obtain a Random string of bits b where 1 < b < w-1 */
341 if (!BN_priv_rand_range_ex(b, w3, ctx)
342 || !BN_add_word(b, 2)) /* 1 < b < w-1 */
343 goto err;
344
345 if (enhanced) {
346 /* (Step 4.3) */
347 if (!BN_gcd(g, b, w, ctx))
348 goto err;
349 /* (Step 4.4) */
350 if (!BN_is_one(g)) {
351 *status = BN_PRIMETEST_COMPOSITE_WITH_FACTOR;
352 ret = 1;
353 goto err;
354 }
355 }
356 /* (Step 4.5) z = b^m mod w */
357 if (!BN_mod_exp_mont(z, b, m, w, ctx, mont))
358 goto err;
359 /* (Step 4.6) if (z = 1 or z = w-1) */
360 if (BN_is_one(z) || BN_cmp(z, w1) == 0)
361 goto outer_loop;
362 /* (Step 4.7) for j = 1 to a-1 */
363 for (j = 1; j < a ; ++j) {
364 /* (Step 4.7.1 - 4.7.2) x = z. z = x^2 mod w */
365 if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx))
366 goto err;
367 /* (Step 4.7.3) */
368 if (BN_cmp(z, w1) == 0)
369 goto outer_loop;
370 /* (Step 4.7.4) */
371 if (BN_is_one(z))
372 goto composite;
373 }
374 /* At this point z = b^((w-1)/2) mod w */
375 /* (Steps 4.8 - 4.9) x = z, z = x^2 mod w */
376 if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx))
377 goto err;
378 /* (Step 4.10) */
379 if (BN_is_one(z))
380 goto composite;
381 /* (Step 4.11) x = b^(w-1) mod w */
382 if (!BN_copy(x, z))
383 goto err;
384 composite:
385 if (enhanced) {
386 /* (Step 4.1.2) g = GCD(x-1, w) */
387 if (!BN_sub_word(x, 1) || !BN_gcd(g, x, w, ctx))
388 goto err;
389 /* (Steps 4.1.3 - 4.1.4) */
390 if (BN_is_one(g))
391 *status = BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME;
392 else
393 *status = BN_PRIMETEST_COMPOSITE_WITH_FACTOR;
394 } else {
395 *status = BN_PRIMETEST_COMPOSITE;
396 }
397 ret = 1;
398 goto err;
399 outer_loop: ;
400 /* (Step 4.1.5) */
401 if (!BN_GENCB_call(cb, 1, i))
402 goto err;
403 }
404 /* (Step 5) */
405 *status = BN_PRIMETEST_PROBABLY_PRIME;
406 ret = 1;
407 err:
408 BN_clear(g);
409 BN_clear(w1);
410 BN_clear(w3);
411 BN_clear(x);
412 BN_clear(m);
413 BN_clear(z);
414 BN_clear(b);
415 BN_CTX_end(ctx);
416 BN_MONT_CTX_free(mont);
417 return ret;
418 }
419
420 /*
421 * Generate a random number of |bits| bits that is probably prime by sieving.
422 * If |safe| != 0, it generates a safe prime.
423 * |mods| is a preallocated array that gets reused when called again.
424 *
425 * The probably prime is saved in |rnd|.
426 *
427 * Returns 1 on success and 0 on error.
428 */
429 static int probable_prime(BIGNUM *rnd, int bits, int safe, prime_t *mods,
430 BN_CTX *ctx)
431 {
432 int i;
433 BN_ULONG delta;
434 int trial_divisions = calc_trial_divisions(bits);
435 BN_ULONG maxdelta = BN_MASK2 - primes[trial_divisions - 1];
436
437 again:
438 /* TODO: Not all primes are private */
439 if (!BN_priv_rand_ex(rnd, bits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ODD, ctx))
440 return 0;
441 if (safe && !BN_set_bit(rnd, 1))
442 return 0;
443 /* we now have a random number 'rnd' to test. */
444 for (i = 1; i < trial_divisions; i++) {
445 BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]);
446 if (mod == (BN_ULONG)-1)
447 return 0;
448 mods[i] = (prime_t) mod;
449 }
450 delta = 0;
451 loop:
452 for (i = 1; i < trial_divisions; i++) {
453 /*
454 * check that rnd is a prime and also that
455 * gcd(rnd-1,primes) == 1 (except for 2)
456 * do the second check only if we are interested in safe primes
457 * in the case that the candidate prime is a single word then
458 * we check only the primes up to sqrt(rnd)
459 */
460 if (bits <= 31 && delta <= 0x7fffffff
461 && square(primes[i]) > BN_get_word(rnd) + delta)
462 break;
463 if (safe ? (mods[i] + delta) % primes[i] <= 1
464 : (mods[i] + delta) % primes[i] == 0) {
465 delta += safe ? 4 : 2;
466 if (delta > maxdelta)
467 goto again;
468 goto loop;
469 }
470 }
471 if (!BN_add_word(rnd, delta))
472 return 0;
473 if (BN_num_bits(rnd) != bits)
474 goto again;
475 bn_check_top(rnd);
476 return 1;
477 }
478
479 /*
480 * Generate a random number |rnd| of |bits| bits that is probably prime
481 * and satisfies |rnd| % |add| == |rem| by sieving.
482 * If |safe| != 0, it generates a safe prime.
483 * |mods| is a preallocated array that gets reused when called again.
484 *
485 * Returns 1 on success and 0 on error.
486 */
487 static int probable_prime_dh(BIGNUM *rnd, int bits, int safe, prime_t *mods,
488 const BIGNUM *add, const BIGNUM *rem,
489 BN_CTX *ctx)
490 {
491 int i, ret = 0;
492 BIGNUM *t1;
493 BN_ULONG delta;
494 int trial_divisions = calc_trial_divisions(bits);
495 BN_ULONG maxdelta = BN_MASK2 - primes[trial_divisions - 1];
496
497 BN_CTX_start(ctx);
498 if ((t1 = BN_CTX_get(ctx)) == NULL)
499 goto err;
500
501 if (maxdelta > BN_MASK2 - BN_get_word(add))
502 maxdelta = BN_MASK2 - BN_get_word(add);
503
504 again:
505 if (!BN_rand_ex(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD, ctx))
506 goto err;
507
508 /* we need ((rnd-rem) % add) == 0 */
509
510 if (!BN_mod(t1, rnd, add, ctx))
511 goto err;
512 if (!BN_sub(rnd, rnd, t1))
513 goto err;
514 if (rem == NULL) {
515 if (!BN_add_word(rnd, safe ? 3u : 1u))
516 goto err;
517 } else {
518 if (!BN_add(rnd, rnd, rem))
519 goto err;
520 }
521
522 if (BN_num_bits(rnd) < bits
523 || BN_get_word(rnd) < (safe ? 5u : 3u)) {
524 if (!BN_add(rnd, rnd, add))
525 goto err;
526 }
527
528 /* we now have a random number 'rnd' to test. */
529 for (i = 1; i < trial_divisions; i++) {
530 BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]);
531 if (mod == (BN_ULONG)-1)
532 goto err;
533 mods[i] = (prime_t) mod;
534 }
535 delta = 0;
536 loop:
537 for (i = 1; i < trial_divisions; i++) {
538 /* check that rnd is a prime */
539 if (bits <= 31 && delta <= 0x7fffffff
540 && square(primes[i]) > BN_get_word(rnd) + delta)
541 break;
542 /* rnd mod p == 1 implies q = (rnd-1)/2 is divisible by p */
543 if (safe ? (mods[i] + delta) % primes[i] <= 1
544 : (mods[i] + delta) % primes[i] == 0) {
545 delta += BN_get_word(add);
546 if (delta > maxdelta)
547 goto again;
548 goto loop;
549 }
550 }
551 if (!BN_add_word(rnd, delta))
552 goto err;
553 ret = 1;
554
555 err:
556 BN_CTX_end(ctx);
557 bn_check_top(rnd);
558 return ret;
559 }