Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/security/nss/lib/freebl/mpi/mpprime.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 *  mpprime.c
3
 *
4
 *  Utilities for finding and working with prime and pseudo-prime
5
 *  integers
6
 *
7
 * This Source Code Form is subject to the terms of the Mozilla Public
8
 * License, v. 2.0. If a copy of the MPL was not distributed with this
9
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
10
11
#include "mpi-priv.h"
12
#include "mpprime.h"
13
#include "mplogic.h"
14
#include <stdlib.h>
15
#include <string.h>
16
17
#define SMALL_TABLE 0 /* determines size of hard-wired prime table */
18
19
0
#define RANDOM() rand()
20
21
#include "primes.c" /* pull in the prime digit table */
22
23
/*
24
   Test if any of a given vector of digits divides a.  If not, MP_NO
25
   is returned; otherwise, MP_YES is returned and 'which' is set to
26
   the index of the integer in the vector which divided a.
27
 */
28
mp_err s_mpp_divp(mp_int *a, const mp_digit *vec, int size, int *which);
29
30
/* {{{ mpp_divis(a, b) */
31
32
/*
33
  mpp_divis(a, b)
34
35
  Returns MP_YES if a is divisible by b, or MP_NO if it is not.
36
 */
37
38
mp_err
39
mpp_divis(mp_int *a, mp_int *b)
40
0
{
41
0
    mp_err res;
42
0
    mp_int rem;
43
0
44
0
    if ((res = mp_init(&rem)) != MP_OKAY)
45
0
        return res;
46
0
47
0
    if ((res = mp_mod(a, b, &rem)) != MP_OKAY)
48
0
        goto CLEANUP;
49
0
50
0
    if (mp_cmp_z(&rem) == 0)
51
0
        res = MP_YES;
52
0
    else
53
0
        res = MP_NO;
54
0
55
0
CLEANUP:
56
0
    mp_clear(&rem);
57
0
    return res;
58
0
59
0
} /* end mpp_divis() */
60
61
/* }}} */
62
63
/* {{{ mpp_divis_d(a, d) */
64
65
/*
66
  mpp_divis_d(a, d)
67
68
  Return MP_YES if a is divisible by d, or MP_NO if it is not.
69
 */
70
71
mp_err
72
mpp_divis_d(mp_int *a, mp_digit d)
73
0
{
74
0
    mp_err res;
75
0
    mp_digit rem;
76
0
77
0
    ARGCHK(a != NULL, MP_BADARG);
78
0
79
0
    if (d == 0)
80
0
        return MP_NO;
81
0
82
0
    if ((res = mp_mod_d(a, d, &rem)) != MP_OKAY)
83
0
        return res;
84
0
85
0
    if (rem == 0)
86
0
        return MP_YES;
87
0
    else
88
0
        return MP_NO;
89
0
90
0
} /* end mpp_divis_d() */
91
92
/* }}} */
93
94
/* {{{ mpp_random(a) */
95
96
/*
97
  mpp_random(a)
98
99
  Assigns a random value to a.  This value is generated using the
100
  standard C library's rand() function, so it should not be used for
101
  cryptographic purposes, but it should be fine for primality testing,
102
  since all we really care about there is good statistical properties.
103
104
  As many digits as a currently has are filled with random digits.
105
 */
106
107
mp_err
108
mpp_random(mp_int *a)
109
110
0
{
111
0
    mp_digit next = 0;
112
0
    unsigned int ix, jx;
113
0
114
0
    ARGCHK(a != NULL, MP_BADARG);
115
0
116
0
    for (ix = 0; ix < USED(a); ix++) {
117
0
        for (jx = 0; jx < sizeof(mp_digit); jx++) {
118
0
            next = (next << CHAR_BIT) | (RANDOM() & UCHAR_MAX);
119
0
        }
120
0
        DIGIT(a, ix) = next;
121
0
    }
122
0
123
0
    return MP_OKAY;
124
0
125
0
} /* end mpp_random() */
126
127
/* }}} */
128
129
/* {{{ mpp_random_size(a, prec) */
130
131
mp_err
132
mpp_random_size(mp_int *a, mp_size prec)
133
0
{
134
0
    mp_err res;
135
0
136
0
    ARGCHK(a != NULL && prec > 0, MP_BADARG);
137
0
138
0
    if ((res = s_mp_pad(a, prec)) != MP_OKAY)
139
0
        return res;
140
0
141
0
    return mpp_random(a);
142
0
143
0
} /* end mpp_random_size() */
144
145
/* }}} */
146
147
/* {{{ mpp_divis_vector(a, vec, size, which) */
148
149
/*
150
  mpp_divis_vector(a, vec, size, which)
151
152
  Determines if a is divisible by any of the 'size' digits in vec.
153
  Returns MP_YES and sets 'which' to the index of the offending digit,
154
  if it is; returns MP_NO if it is not.
155
 */
156
157
mp_err
158
mpp_divis_vector(mp_int *a, const mp_digit *vec, int size, int *which)
159
0
{
160
0
    ARGCHK(a != NULL && vec != NULL && size > 0, MP_BADARG);
161
0
162
0
    return s_mpp_divp(a, vec, size, which);
163
0
164
0
} /* end mpp_divis_vector() */
165
166
/* }}} */
167
168
/* {{{ mpp_divis_primes(a, np) */
169
170
/*
171
  mpp_divis_primes(a, np)
172
173
  Test whether a is divisible by any of the first 'np' primes.  If it
174
  is, returns MP_YES and sets *np to the value of the digit that did
175
  it.  If not, returns MP_NO.
176
 */
177
mp_err
178
mpp_divis_primes(mp_int *a, mp_digit *np)
179
0
{
180
0
    int size, which;
181
0
    mp_err res;
182
0
183
0
    ARGCHK(a != NULL && np != NULL, MP_BADARG);
184
0
185
0
    size = (int)*np;
186
0
    if (size > prime_tab_size)
187
0
        size = prime_tab_size;
188
0
189
0
    res = mpp_divis_vector(a, prime_tab, size, &which);
190
0
    if (res == MP_YES)
191
0
        *np = prime_tab[which];
192
0
193
0
    return res;
194
0
195
0
} /* end mpp_divis_primes() */
196
197
/* }}} */
198
199
/* {{{ mpp_fermat(a, w) */
200
201
/*
202
  Using w as a witness, try pseudo-primality testing based on Fermat's
203
  little theorem.  If a is prime, and (w, a) = 1, then w^a == w (mod
204
  a).  So, we compute z = w^a (mod a) and compare z to w; if they are
205
  equal, the test passes and we return MP_YES.  Otherwise, we return
206
  MP_NO.
207
 */
208
mp_err
209
mpp_fermat(mp_int *a, mp_digit w)
210
0
{
211
0
    mp_int base, test;
212
0
    mp_err res;
213
0
214
0
    if ((res = mp_init(&base)) != MP_OKAY)
215
0
        return res;
216
0
217
0
    mp_set(&base, w);
218
0
219
0
    if ((res = mp_init(&test)) != MP_OKAY)
220
0
        goto TEST;
221
0
222
0
    /* Compute test = base^a (mod a) */
223
0
    if ((res = mp_exptmod(&base, a, a, &test)) != MP_OKAY)
224
0
        goto CLEANUP;
225
0
226
0
    if (mp_cmp(&base, &test) == 0)
227
0
        res = MP_YES;
228
0
    else
229
0
        res = MP_NO;
230
0
231
0
CLEANUP:
232
0
    mp_clear(&test);
233
0
TEST:
234
0
    mp_clear(&base);
235
0
236
0
    return res;
237
0
238
0
} /* end mpp_fermat() */
239
240
/* }}} */
241
242
/*
243
  Perform the fermat test on each of the primes in a list until
244
  a) one of them shows a is not prime, or
245
  b) the list is exhausted.
246
  Returns:  MP_YES if it passes tests.
247
        MP_NO  if fermat test reveals it is composite
248
        Some MP error code if some other error occurs.
249
 */
250
mp_err
251
mpp_fermat_list(mp_int *a, const mp_digit *primes, mp_size nPrimes)
252
0
{
253
0
    mp_err rv = MP_YES;
254
0
255
0
    while (nPrimes-- > 0 && rv == MP_YES) {
256
0
        rv = mpp_fermat(a, *primes++);
257
0
    }
258
0
    return rv;
259
0
}
260
261
/* {{{ mpp_pprime(a, nt) */
262
263
/*
264
  mpp_pprime(a, nt)
265
266
  Performs nt iteration of the Miller-Rabin probabilistic primality
267
  test on a.  Returns MP_YES if the tests pass, MP_NO if one fails.
268
  If MP_NO is returned, the number is definitely composite.  If MP_YES
269
  is returned, it is probably prime (but that is not guaranteed).
270
 */
271
272
mp_err
273
mpp_pprime(mp_int *a, int nt)
274
0
{
275
0
    mp_err res;
276
0
    mp_int x, amo, m, z; /* "amo" = "a minus one" */
277
0
    int iter;
278
0
    unsigned int jx;
279
0
    mp_size b;
280
0
281
0
    ARGCHK(a != NULL, MP_BADARG);
282
0
283
0
    MP_DIGITS(&x) = 0;
284
0
    MP_DIGITS(&amo) = 0;
285
0
    MP_DIGITS(&m) = 0;
286
0
    MP_DIGITS(&z) = 0;
287
0
288
0
    /* Initialize temporaries... */
289
0
    MP_CHECKOK(mp_init(&amo));
290
0
    /* Compute amo = a - 1 for what follows...    */
291
0
    MP_CHECKOK(mp_sub_d(a, 1, &amo));
292
0
293
0
    b = mp_trailing_zeros(&amo);
294
0
    if (!b) { /* a was even ? */
295
0
        res = MP_NO;
296
0
        goto CLEANUP;
297
0
    }
298
0
299
0
    MP_CHECKOK(mp_init_size(&x, MP_USED(a)));
300
0
    MP_CHECKOK(mp_init(&z));
301
0
    MP_CHECKOK(mp_init(&m));
302
0
    MP_CHECKOK(mp_div_2d(&amo, b, &m, 0));
303
0
304
0
    /* Do the test nt times... */
305
0
    for (iter = 0; iter < nt; iter++) {
306
0
307
0
        /* Choose a random value for 1 < x < a      */
308
0
        MP_CHECKOK(s_mp_pad(&x, USED(a)));
309
0
        mpp_random(&x);
310
0
        MP_CHECKOK(mp_mod(&x, a, &x));
311
0
        if (mp_cmp_d(&x, 1) <= 0) {
312
0
            iter--;   /* don't count this iteration */
313
0
            continue; /* choose a new x */
314
0
        }
315
0
316
0
        /* Compute z = (x ** m) mod a               */
317
0
        MP_CHECKOK(mp_exptmod(&x, &m, a, &z));
318
0
319
0
        if (mp_cmp_d(&z, 1) == 0 || mp_cmp(&z, &amo) == 0) {
320
0
            res = MP_YES;
321
0
            continue;
322
0
        }
323
0
324
0
        res = MP_NO; /* just in case the following for loop never executes. */
325
0
        for (jx = 1; jx < b; jx++) {
326
0
            /* z = z^2 (mod a) */
327
0
            MP_CHECKOK(mp_sqrmod(&z, a, &z));
328
0
            res = MP_NO; /* previous line set res to MP_YES */
329
0
330
0
            if (mp_cmp_d(&z, 1) == 0) {
331
0
                break;
332
0
            }
333
0
            if (mp_cmp(&z, &amo) == 0) {
334
0
                res = MP_YES;
335
0
                break;
336
0
            }
337
0
        } /* end testing loop */
338
0
339
0
        /* If the test passes, we will continue iterating, but a failed
340
0
           test means the candidate is definitely NOT prime, so we will
341
0
           immediately break out of this loop
342
0
         */
343
0
        if (res == MP_NO)
344
0
            break;
345
0
346
0
    } /* end iterations loop */
347
0
348
0
CLEANUP:
349
0
    mp_clear(&m);
350
0
    mp_clear(&z);
351
0
    mp_clear(&x);
352
0
    mp_clear(&amo);
353
0
    return res;
354
0
355
0
} /* end mpp_pprime() */
356
357
/* }}} */
358
359
/* Produce table of composites from list of primes and trial value.
360
** trial must be odd. List of primes must not include 2.
361
** sieve should have dimension >= MAXPRIME/2, where MAXPRIME is largest
362
** prime in list of primes.  After this function is finished,
363
** if sieve[i] is non-zero, then (trial + 2*i) is composite.
364
** Each prime used in the sieve costs one division of trial, and eliminates
365
** one or more values from the search space. (3 eliminates 1/3 of the values
366
** alone!)  Each value left in the search space costs 1 or more modular
367
** exponentations.  So, these divisions are a bargain!
368
*/
369
mp_err
370
mpp_sieve(mp_int *trial, const mp_digit *primes, mp_size nPrimes,
371
          unsigned char *sieve, mp_size nSieve)
372
0
{
373
0
    mp_err res;
374
0
    mp_digit rem;
375
0
    mp_size ix;
376
0
    unsigned long offset;
377
0
378
0
    memset(sieve, 0, nSieve);
379
0
380
0
    for (ix = 0; ix < nPrimes; ix++) {
381
0
        mp_digit prime = primes[ix];
382
0
        mp_size i;
383
0
        if ((res = mp_mod_d(trial, prime, &rem)) != MP_OKAY)
384
0
            return res;
385
0
386
0
        if (rem == 0) {
387
0
            offset = 0;
388
0
        } else {
389
0
            offset = prime - rem;
390
0
        }
391
0
392
0
        for (i = offset; i < nSieve * 2; i += prime) {
393
0
            if (i % 2 == 0) {
394
0
                sieve[i / 2] = 1;
395
0
            }
396
0
        }
397
0
    }
398
0
399
0
    return MP_OKAY;
400
0
}
401
402
0
#define SIEVE_SIZE 32 * 1024
403
404
mp_err
405
mpp_make_prime(mp_int *start, mp_size nBits, mp_size strong)
406
0
{
407
0
    mp_digit np;
408
0
    mp_err res;
409
0
    unsigned int i = 0;
410
0
    mp_int trial;
411
0
    mp_int q;
412
0
    mp_size num_tests;
413
0
    unsigned char *sieve;
414
0
415
0
    ARGCHK(start != 0, MP_BADARG);
416
0
    ARGCHK(nBits > 16, MP_RANGE);
417
0
418
0
    sieve = malloc(SIEVE_SIZE);
419
0
    ARGCHK(sieve != NULL, MP_MEM);
420
0
421
0
    MP_DIGITS(&trial) = 0;
422
0
    MP_DIGITS(&q) = 0;
423
0
    MP_CHECKOK(mp_init(&trial));
424
0
    MP_CHECKOK(mp_init(&q));
425
0
    /* values originally taken from table 4.4,
426
0
   * HandBook of Applied Cryptography, augmented by FIPS-186
427
0
   * requirements, Table C.2 and C.3 */
428
0
    if (nBits >= 2000) {
429
0
        num_tests = 3;
430
0
    } else if (nBits >= 1536) {
431
0
        num_tests = 4;
432
0
    } else if (nBits >= 1024) {
433
0
        num_tests = 5;
434
0
    } else if (nBits >= 550) {
435
0
        num_tests = 6;
436
0
    } else if (nBits >= 450) {
437
0
        num_tests = 7;
438
0
    } else if (nBits >= 400) {
439
0
        num_tests = 8;
440
0
    } else if (nBits >= 350) {
441
0
        num_tests = 9;
442
0
    } else if (nBits >= 300) {
443
0
        num_tests = 10;
444
0
    } else if (nBits >= 250) {
445
0
        num_tests = 20;
446
0
    } else if (nBits >= 200) {
447
0
        num_tests = 41;
448
0
    } else if (nBits >= 100) {
449
0
        num_tests = 38; /* funny anomaly in the FIPS tables, for aux primes, the
450
0
                         * required more iterations for larger aux primes */
451
0
    } else
452
0
        num_tests = 50;
453
0
454
0
    if (strong)
455
0
        --nBits;
456
0
    MP_CHECKOK(mpl_set_bit(start, nBits - 1, 1));
457
0
    MP_CHECKOK(mpl_set_bit(start, 0, 1));
458
0
    for (i = mpl_significant_bits(start) - 1; i >= nBits; --i) {
459
0
        MP_CHECKOK(mpl_set_bit(start, i, 0));
460
0
    }
461
0
    /* start sieveing with prime value of 3. */
462
0
    MP_CHECKOK(mpp_sieve(start, prime_tab + 1, prime_tab_size - 1,
463
0
                         sieve, SIEVE_SIZE));
464
0
465
#ifdef DEBUG_SIEVE
466
    res = 0;
467
    for (i = 0; i < SIEVE_SIZE; ++i) {
468
        if (!sieve[i])
469
            ++res;
470
    }
471
    fprintf(stderr, "sieve found %d potential primes.\n", res);
472
#define FPUTC(x, y) fputc(x, y)
473
#else
474
#define FPUTC(x, y)
475
0
#endif
476
0
477
0
    res = MP_NO;
478
0
    for (i = 0; i < SIEVE_SIZE; ++i) {
479
0
        if (sieve[i]) /* this number is composite */
480
0
            continue;
481
0
        MP_CHECKOK(mp_add_d(start, 2 * i, &trial));
482
0
        FPUTC('.', stderr);
483
0
        /* run a Fermat test */
484
0
        res = mpp_fermat(&trial, 2);
485
0
        if (res != MP_OKAY) {
486
0
            if (res == MP_NO)
487
0
                continue; /* was composite */
488
0
            goto CLEANUP;
489
0
        }
490
0
491
0
        FPUTC('+', stderr);
492
0
        /* If that passed, run some Miller-Rabin tests  */
493
0
        res = mpp_pprime(&trial, num_tests);
494
0
        if (res != MP_OKAY) {
495
0
            if (res == MP_NO)
496
0
                continue; /* was composite */
497
0
            goto CLEANUP;
498
0
        }
499
0
        FPUTC('!', stderr);
500
0
501
0
        if (!strong)
502
0
            break; /* success !! */
503
0
504
0
        /* At this point, we have strong evidence that our candidate
505
0
           is itself prime.  If we want a strong prime, we need now
506
0
           to test q = 2p + 1 for primality...
507
0
        */
508
0
        MP_CHECKOK(mp_mul_2(&trial, &q));
509
0
        MP_CHECKOK(mp_add_d(&q, 1, &q));
510
0
511
0
        /* Test q for small prime divisors ... */
512
0
        np = prime_tab_size;
513
0
        res = mpp_divis_primes(&q, &np);
514
0
        if (res == MP_YES) { /* is composite */
515
0
            mp_clear(&q);
516
0
            continue;
517
0
        }
518
0
        if (res != MP_NO)
519
0
            goto CLEANUP;
520
0
521
0
        /* And test with Fermat, as with its parent ... */
522
0
        res = mpp_fermat(&q, 2);
523
0
        if (res != MP_YES) {
524
0
            mp_clear(&q);
525
0
            if (res == MP_NO)
526
0
                continue; /* was composite */
527
0
            goto CLEANUP;
528
0
        }
529
0
530
0
        /* And test with Miller-Rabin, as with its parent ... */
531
0
        res = mpp_pprime(&q, num_tests);
532
0
        if (res != MP_YES) {
533
0
            mp_clear(&q);
534
0
            if (res == MP_NO)
535
0
                continue; /* was composite */
536
0
            goto CLEANUP;
537
0
        }
538
0
539
0
        /* If it passed, we've got a winner */
540
0
        mp_exch(&q, &trial);
541
0
        mp_clear(&q);
542
0
        break;
543
0
544
0
    } /* end of loop through sieved values */
545
0
    if (res == MP_YES)
546
0
        mp_exch(&trial, start);
547
0
CLEANUP:
548
0
    mp_clear(&trial);
549
0
    mp_clear(&q);
550
0
    if (sieve != NULL) {
551
0
        memset(sieve, 0, SIEVE_SIZE);
552
0
        free(sieve);
553
0
    }
554
0
    return res;
555
0
}
556
557
/*========================================================================*/
558
/*------------------------------------------------------------------------*/
559
/* Static functions visible only to the library internally                */
560
561
/* {{{ s_mpp_divp(a, vec, size, which) */
562
563
/*
564
   Test for divisibility by members of a vector of digits.  Returns
565
   MP_NO if a is not divisible by any of them; returns MP_YES and sets
566
   'which' to the index of the offender, if it is.  Will stop on the
567
   first digit against which a is divisible.
568
 */
569
570
mp_err
571
s_mpp_divp(mp_int *a, const mp_digit *vec, int size, int *which)
572
0
{
573
0
    mp_err res;
574
0
    mp_digit rem;
575
0
576
0
    int ix;
577
0
578
0
    for (ix = 0; ix < size; ix++) {
579
0
        if ((res = mp_mod_d(a, vec[ix], &rem)) != MP_OKAY)
580
0
            return res;
581
0
582
0
        if (rem == 0) {
583
0
            if (which)
584
0
                *which = ix;
585
0
            return MP_YES;
586
0
        }
587
0
    }
588
0
589
0
    return MP_NO;
590
0
591
0
} /* end s_mpp_divp() */
592
593
/* }}} */
594
595
/*------------------------------------------------------------------------*/
596
/* HERE THERE BE DRAGONS                                                  */