0b98618a1822665e5fd1102b2b0e55359c76013b
[openssl.git] / crypto / bn / bn_prime.c
1 /*
2  * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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_lcl.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 witness(BIGNUM *w, const BIGNUM *a, const BIGNUM *a1,
23                    const BIGNUM *a1_odd, int k, BN_CTX *ctx,
24                    BN_MONT_CTX *mont);
25 static int probable_prime(BIGNUM *rnd, int bits, prime_t *mods);
26 static int probable_prime_dh_safe(BIGNUM *rnd, int bits,
27                                   const BIGNUM *add, const BIGNUM *rem,
28                                   BN_CTX *ctx);
29
30 int BN_GENCB_call(BN_GENCB *cb, int a, int b)
31 {
32     /* No callback means continue */
33     if (!cb)
34         return 1;
35     switch (cb->ver) {
36     case 1:
37         /* Deprecated-style callbacks */
38         if (!cb->cb.cb_1)
39             return 1;
40         cb->cb.cb_1(a, b, cb->arg);
41         return 1;
42     case 2:
43         /* New-style callbacks */
44         return cb->cb.cb_2(a, b, cb);
45     default:
46         break;
47     }
48     /* Unrecognised callback type */
49     return 0;
50 }
51
52 int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe,
53                          const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb)
54 {
55     BIGNUM *t;
56     int found = 0;
57     int i, j, c1 = 0;
58     BN_CTX *ctx = NULL;
59     prime_t *mods = NULL;
60     int checks = BN_prime_checks_for_size(bits);
61
62     if (bits < 2) {
63         /* There are no prime numbers this small. */
64         BNerr(BN_F_BN_GENERATE_PRIME_EX, BN_R_BITS_TOO_SMALL);
65         return 0;
66     } else if (bits == 2 && safe) {
67         /* The smallest safe prime (7) is three bits. */
68         BNerr(BN_F_BN_GENERATE_PRIME_EX, BN_R_BITS_TOO_SMALL);
69         return 0;
70     }
71
72     mods = OPENSSL_zalloc(sizeof(*mods) * NUMPRIMES);
73     if (mods == NULL)
74         goto err;
75
76     ctx = BN_CTX_new();
77     if (ctx == NULL)
78         goto err;
79     BN_CTX_start(ctx);
80     t = BN_CTX_get(ctx);
81     if (t == NULL)
82         goto err;
83  loop:
84     /* make a random number and set the top and bottom bits */
85     if (add == NULL) {
86         if (!probable_prime(ret, bits, mods))
87             goto err;
88     } else {
89         if (safe) {
90             if (!probable_prime_dh_safe(ret, bits, add, rem, ctx))
91                 goto err;
92         } else {
93             if (!bn_probable_prime_dh(ret, bits, add, rem, ctx))
94                 goto err;
95         }
96     }
97
98     if (!BN_GENCB_call(cb, 0, c1++))
99         /* aborted */
100         goto err;
101
102     if (!safe) {
103         i = BN_is_prime_fasttest_ex(ret, checks, ctx, 0, cb);
104         if (i == -1)
105             goto err;
106         if (i == 0)
107             goto loop;
108     } else {
109         /*
110          * for "safe prime" generation, check that (p-1)/2 is prime. Since a
111          * prime is odd, We just need to divide by 2
112          */
113         if (!BN_rshift1(t, ret))
114             goto err;
115
116         for (i = 0; i < checks; i++) {
117             j = BN_is_prime_fasttest_ex(ret, 1, ctx, 0, cb);
118             if (j == -1)
119                 goto err;
120             if (j == 0)
121                 goto loop;
122
123             j = BN_is_prime_fasttest_ex(t, 1, ctx, 0, cb);
124             if (j == -1)
125                 goto err;
126             if (j == 0)
127                 goto loop;
128
129             if (!BN_GENCB_call(cb, 2, c1 - 1))
130                 goto err;
131             /* We have a safe prime test pass */
132         }
133     }
134     /* we have a prime :-) */
135     found = 1;
136  err:
137     OPENSSL_free(mods);
138     if (ctx != NULL)
139         BN_CTX_end(ctx);
140     BN_CTX_free(ctx);
141     bn_check_top(ret);
142     return found;
143 }
144
145 int BN_is_prime_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed,
146                    BN_GENCB *cb)
147 {
148     return BN_is_prime_fasttest_ex(a, checks, ctx_passed, 0, cb);
149 }
150
151 int BN_is_prime_fasttest_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed,
152                             int do_trial_division, BN_GENCB *cb)
153 {
154     int i, j, ret = -1;
155     int k;
156     BN_CTX *ctx = NULL;
157     BIGNUM *A1, *A1_odd, *check; /* taken from ctx */
158     BN_MONT_CTX *mont = NULL;
159
160     if (BN_cmp(a, BN_value_one()) <= 0)
161         return 0;
162
163     if (checks == BN_prime_checks)
164         checks = BN_prime_checks_for_size(BN_num_bits(a));
165
166     /* first look for small factors */
167     if (!BN_is_odd(a))
168         /* a is even => a is prime if and only if a == 2 */
169         return BN_is_word(a, 2);
170     if (do_trial_division) {
171         for (i = 1; i < NUMPRIMES; i++) {
172             BN_ULONG mod = BN_mod_word(a, primes[i]);
173             if (mod == (BN_ULONG)-1)
174                 goto err;
175             if (mod == 0)
176                 return BN_is_word(a, primes[i]);
177         }
178         if (!BN_GENCB_call(cb, 1, -1))
179             goto err;
180     }
181
182     if (ctx_passed != NULL)
183         ctx = ctx_passed;
184     else if ((ctx = BN_CTX_new()) == NULL)
185         goto err;
186     BN_CTX_start(ctx);
187
188     A1 = BN_CTX_get(ctx);
189     A1_odd = BN_CTX_get(ctx);
190     check = BN_CTX_get(ctx);
191     if (check == NULL)
192         goto err;
193
194     /* compute A1 := a - 1 */
195     if (!BN_copy(A1, a))
196         goto err;
197     if (!BN_sub_word(A1, 1))
198         goto err;
199     if (BN_is_zero(A1)) {
200         ret = 0;
201         goto err;
202     }
203
204     /* write  A1  as  A1_odd * 2^k */
205     k = 1;
206     while (!BN_is_bit_set(A1, k))
207         k++;
208     if (!BN_rshift(A1_odd, A1, k))
209         goto err;
210
211     /* Montgomery setup for computations mod a */
212     mont = BN_MONT_CTX_new();
213     if (mont == NULL)
214         goto err;
215     if (!BN_MONT_CTX_set(mont, a, ctx))
216         goto err;
217
218     for (i = 0; i < checks; i++) {
219         if (!BN_priv_rand_range(check, A1))
220             goto err;
221         if (!BN_add_word(check, 1))
222             goto err;
223         /* now 1 <= check < a */
224
225         j = witness(check, a, A1, A1_odd, k, ctx, mont);
226         if (j == -1)
227             goto err;
228         if (j) {
229             ret = 0;
230             goto err;
231         }
232         if (!BN_GENCB_call(cb, 1, i))
233             goto err;
234     }
235     ret = 1;
236  err:
237     if (ctx != NULL) {
238         BN_CTX_end(ctx);
239         if (ctx_passed == NULL)
240             BN_CTX_free(ctx);
241     }
242     BN_MONT_CTX_free(mont);
243
244     return (ret);
245 }
246
247 static int witness(BIGNUM *w, const BIGNUM *a, const BIGNUM *a1,
248                    const BIGNUM *a1_odd, int k, BN_CTX *ctx,
249                    BN_MONT_CTX *mont)
250 {
251     if (!BN_mod_exp_mont(w, w, a1_odd, a, ctx, mont)) /* w := w^a1_odd mod a */
252         return -1;
253     if (BN_is_one(w))
254         return 0;               /* probably prime */
255     if (BN_cmp(w, a1) == 0)
256         return 0;               /* w == -1 (mod a), 'a' is probably prime */
257     while (--k) {
258         if (!BN_mod_mul(w, w, w, a, ctx)) /* w := w^2 mod a */
259             return -1;
260         if (BN_is_one(w))
261             return 1;           /* 'a' is composite, otherwise a previous 'w'
262                                  * would have been == -1 (mod 'a') */
263         if (BN_cmp(w, a1) == 0)
264             return 0;           /* w == -1 (mod a), 'a' is probably prime */
265     }
266     /*
267      * If we get here, 'w' is the (a-1)/2-th power of the original 'w', and
268      * it is neither -1 nor +1 -- so 'a' cannot be prime
269      */
270     bn_check_top(w);
271     return 1;
272 }
273
274 static int probable_prime(BIGNUM *rnd, int bits, prime_t *mods)
275 {
276     int i;
277     BN_ULONG delta;
278     BN_ULONG maxdelta = BN_MASK2 - primes[NUMPRIMES - 1];
279     char is_single_word = bits <= BN_BITS2;
280
281  again:
282     if (!BN_priv_rand(rnd, bits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ODD))
283         return (0);
284     /* we now have a random number 'rnd' to test. */
285     for (i = 1; i < NUMPRIMES; i++) {
286         BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]);
287         if (mod == (BN_ULONG)-1)
288             return 0;
289         mods[i] = (prime_t) mod;
290     }
291     /*
292      * If bits is so small that it fits into a single word then we
293      * additionally don't want to exceed that many bits.
294      */
295     if (is_single_word) {
296         BN_ULONG size_limit;
297
298         if (bits == BN_BITS2) {
299             /*
300              * Shifting by this much has undefined behaviour so we do it a
301              * different way
302              */
303             size_limit = ~((BN_ULONG)0) - BN_get_word(rnd);
304         } else {
305             size_limit = (((BN_ULONG)1) << bits) - BN_get_word(rnd) - 1;
306         }
307         if (size_limit < maxdelta)
308             maxdelta = size_limit;
309     }
310     delta = 0;
311  loop:
312     if (is_single_word) {
313         BN_ULONG rnd_word = BN_get_word(rnd);
314
315         /*-
316          * In the case that the candidate prime is a single word then
317          * we check that:
318          *   1) It's greater than primes[i] because we shouldn't reject
319          *      3 as being a prime number because it's a multiple of
320          *      three.
321          *   2) That it's not a multiple of a known prime. We don't
322          *      check that rnd-1 is also coprime to all the known
323          *      primes because there aren't many small primes where
324          *      that's true.
325          */
326         for (i = 1; i < NUMPRIMES && primes[i] < rnd_word; i++) {
327             if ((mods[i] + delta) % primes[i] == 0) {
328                 delta += 2;
329                 if (delta > maxdelta)
330                     goto again;
331                 goto loop;
332             }
333         }
334     } else {
335         for (i = 1; i < NUMPRIMES; i++) {
336             /*
337              * check that rnd is not a prime and also that gcd(rnd-1,primes)
338              * == 1 (except for 2)
339              */
340             if (((mods[i] + delta) % primes[i]) <= 1) {
341                 delta += 2;
342                 if (delta > maxdelta)
343                     goto again;
344                 goto loop;
345             }
346         }
347     }
348     if (!BN_add_word(rnd, delta))
349         return (0);
350     if (BN_num_bits(rnd) != bits)
351         goto again;
352     bn_check_top(rnd);
353     return 1;
354 }
355
356 int bn_probable_prime_dh(BIGNUM *rnd, int bits,
357                          const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx)
358 {
359     int i, ret = 0;
360     BIGNUM *t1;
361
362     BN_CTX_start(ctx);
363     if ((t1 = BN_CTX_get(ctx)) == NULL)
364         goto err;
365
366     if (!BN_priv_rand(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD))
367         goto err;
368
369     /* we need ((rnd-rem) % add) == 0 */
370
371     if (!BN_mod(t1, rnd, add, ctx))
372         goto err;
373     if (!BN_sub(rnd, rnd, t1))
374         goto err;
375     if (rem == NULL) {
376         if (!BN_add_word(rnd, 1))
377             goto err;
378     } else {
379         if (!BN_add(rnd, rnd, rem))
380             goto err;
381     }
382
383     /* we now have a random number 'rand' to test. */
384
385  loop:
386     for (i = 1; i < NUMPRIMES; i++) {
387         /* check that rnd is a prime */
388         BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]);
389         if (mod == (BN_ULONG)-1)
390             goto err;
391         if (mod <= 1) {
392             if (!BN_add(rnd, rnd, add))
393                 goto err;
394             goto loop;
395         }
396     }
397     ret = 1;
398
399  err:
400     BN_CTX_end(ctx);
401     bn_check_top(rnd);
402     return (ret);
403 }
404
405 static int probable_prime_dh_safe(BIGNUM *p, int bits, const BIGNUM *padd,
406                                   const BIGNUM *rem, BN_CTX *ctx)
407 {
408     int i, ret = 0;
409     BIGNUM *t1, *qadd, *q;
410
411     bits--;
412     BN_CTX_start(ctx);
413     t1 = BN_CTX_get(ctx);
414     q = BN_CTX_get(ctx);
415     qadd = BN_CTX_get(ctx);
416     if (qadd == NULL)
417         goto err;
418
419     if (!BN_rshift1(qadd, padd))
420         goto err;
421
422     if (!BN_priv_rand(q, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD))
423         goto err;
424
425     /* we need ((rnd-rem) % add) == 0 */
426     if (!BN_mod(t1, q, qadd, ctx))
427         goto err;
428     if (!BN_sub(q, q, t1))
429         goto err;
430     if (rem == NULL) {
431         if (!BN_add_word(q, 1))
432             goto err;
433     } else {
434         if (!BN_rshift1(t1, rem))
435             goto err;
436         if (!BN_add(q, q, t1))
437             goto err;
438     }
439
440     /* we now have a random number 'rand' to test. */
441     if (!BN_lshift1(p, q))
442         goto err;
443     if (!BN_add_word(p, 1))
444         goto err;
445
446  loop:
447     for (i = 1; i < NUMPRIMES; i++) {
448         /* check that p and q are prime */
449         /*
450          * check that for p and q gcd(p-1,primes) == 1 (except for 2)
451          */
452         BN_ULONG pmod = BN_mod_word(p, (BN_ULONG)primes[i]);
453         BN_ULONG qmod = BN_mod_word(q, (BN_ULONG)primes[i]);
454         if (pmod == (BN_ULONG)-1 || qmod == (BN_ULONG)-1)
455             goto err;
456         if (pmod == 0 || qmod == 0) {
457             if (!BN_add(p, p, padd))
458                 goto err;
459             if (!BN_add(q, q, qadd))
460                 goto err;
461             goto loop;
462         }
463     }
464     ret = 1;
465
466  err:
467     BN_CTX_end(ctx);
468     bn_check_top(p);
469     return (ret);
470 }