comparison bn_mp_prime_miller_rabin.c @ 2:86e0b50a9b58 libtommath-orig ltm-0.30-orig

ltm 0.30 orig import
author Matt Johnston <matt@ucc.asn.au>
date Mon, 31 May 2004 18:25:22 +0000
parents
children d29b64170cf0
comparison
equal deleted inserted replaced
-1:000000000000 2:86e0b50a9b58
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
2 *
3 * LibTomMath is a library that provides multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
5 *
6 * The library was designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
9 *
10 * The library is free for all purposes without any express
11 * guarantee it works.
12 *
13 * Tom St Denis, [email protected], http://math.libtomcrypt.org
14 */
15 #include <tommath.h>
16
17 /* Miller-Rabin test of "a" to the base of "b" as described in
18 * HAC pp. 139 Algorithm 4.24
19 *
20 * Sets result to 0 if definitely composite or 1 if probably prime.
21 * Randomly the chance of error is no more than 1/4 and often
22 * very much lower.
23 */
24 int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result)
25 {
26 mp_int n1, y, r;
27 int s, j, err;
28
29 /* default */
30 *result = MP_NO;
31
32 /* ensure b > 1 */
33 if (mp_cmp_d(b, 1) != MP_GT) {
34 return MP_VAL;
35 }
36
37 /* get n1 = a - 1 */
38 if ((err = mp_init_copy (&n1, a)) != MP_OKAY) {
39 return err;
40 }
41 if ((err = mp_sub_d (&n1, 1, &n1)) != MP_OKAY) {
42 goto __N1;
43 }
44
45 /* set 2**s * r = n1 */
46 if ((err = mp_init_copy (&r, &n1)) != MP_OKAY) {
47 goto __N1;
48 }
49
50 /* count the number of least significant bits
51 * which are zero
52 */
53 s = mp_cnt_lsb(&r);
54
55 /* now divide n - 1 by 2**s */
56 if ((err = mp_div_2d (&r, s, &r, NULL)) != MP_OKAY) {
57 goto __R;
58 }
59
60 /* compute y = b**r mod a */
61 if ((err = mp_init (&y)) != MP_OKAY) {
62 goto __R;
63 }
64 if ((err = mp_exptmod (b, &r, a, &y)) != MP_OKAY) {
65 goto __Y;
66 }
67
68 /* if y != 1 and y != n1 do */
69 if (mp_cmp_d (&y, 1) != MP_EQ && mp_cmp (&y, &n1) != MP_EQ) {
70 j = 1;
71 /* while j <= s-1 and y != n1 */
72 while ((j <= (s - 1)) && mp_cmp (&y, &n1) != MP_EQ) {
73 if ((err = mp_sqrmod (&y, a, &y)) != MP_OKAY) {
74 goto __Y;
75 }
76
77 /* if y == 1 then composite */
78 if (mp_cmp_d (&y, 1) == MP_EQ) {
79 goto __Y;
80 }
81
82 ++j;
83 }
84
85 /* if y != n1 then composite */
86 if (mp_cmp (&y, &n1) != MP_EQ) {
87 goto __Y;
88 }
89 }
90
91 /* probably prime now */
92 *result = MP_YES;
93 __Y:mp_clear (&y);
94 __R:mp_clear (&r);
95 __N1:mp_clear (&n1);
96 return err;
97 }