security/nss/lib/freebl/mpi/utils/isprime.c

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:59862a5bb974
1 /*
2 * isprime.c
3 *
4 * Probabilistic primality tester command-line tool
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public
7 * License, v. 2.0. If a copy of the MPL was not distributed with this
8 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include "mpi.h"
15 #include "mpprime.h"
16
17 #define RM_TESTS 15 /* how many iterations of Rabin-Miller? */
18 #define MINIMUM 1024 /* don't bother us with a < this */
19
20 int g_tests = RM_TESTS;
21 char *g_prog = NULL;
22
23 int main(int argc, char *argv[])
24 {
25 mp_int a;
26 mp_digit np = prime_tab_size; /* from mpprime.h */
27 int res = 0;
28
29 g_prog = argv[0];
30
31 if(argc < 2) {
32 fprintf(stderr, "Usage: %s <a>, where <a> is a decimal integer\n"
33 "Use '0x' prefix for a hexadecimal value\n", g_prog);
34 return 1;
35 }
36
37 /* Read number of tests from environment, if present */
38 {
39 char *tmp;
40
41 if((tmp = getenv("RM_TESTS")) != NULL) {
42 if((g_tests = atoi(tmp)) <= 0)
43 g_tests = RM_TESTS;
44 }
45 }
46
47 mp_init(&a);
48 if(argv[1][0] == '0' && argv[1][1] == 'x')
49 mp_read_radix(&a, argv[1] + 2, 16);
50 else
51 mp_read_radix(&a, argv[1], 10);
52
53 if(mp_cmp_d(&a, MINIMUM) <= 0) {
54 fprintf(stderr, "%s: please use a value greater than %d\n",
55 g_prog, MINIMUM);
56 mp_clear(&a);
57 return 1;
58 }
59
60 /* Test for divisibility by small primes */
61 if(mpp_divis_primes(&a, &np) != MP_NO) {
62 printf("Not prime (divisible by small prime %d)\n", np);
63 res = 2;
64 goto CLEANUP;
65 }
66
67 /* Test with Fermat's test, using 2 as a witness */
68 if(mpp_fermat(&a, 2) != MP_YES) {
69 printf("Not prime (failed Fermat test)\n");
70 res = 2;
71 goto CLEANUP;
72 }
73
74 /* Test with Rabin-Miller probabilistic test */
75 if(mpp_pprime(&a, g_tests) == MP_NO) {
76 printf("Not prime (failed pseudoprime test)\n");
77 res = 2;
78 goto CLEANUP;
79 }
80
81 printf("Probably prime, 1 in 4^%d chance of false positive\n", g_tests);
82
83 CLEANUP:
84 mp_clear(&a);
85
86 return res;
87
88 }

mercurial