Mercurial > dropbear
comparison tomsfastmath/src/numtheory/fp_prime_miller_rabin.c @ 643:a362b62d38b2 dropbear-tfm
Add tomsfastmath from git rev bfa4582842bc3bab42e4be4aed5703437049502a
with Makefile.in renamed
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Wed, 23 Nov 2011 18:10:20 +0700 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
642:33fd2f3499d2 | 643:a362b62d38b2 |
---|---|
1 /* TomsFastMath, a fast ISO C bignum library. | |
2 * | |
3 * This project is meant to fill in where LibTomMath | |
4 * falls short. That is speed ;-) | |
5 * | |
6 * This project is public domain and free for all purposes. | |
7 * | |
8 * Tom St Denis, [email protected] | |
9 */ | |
10 #include <tfm.h> | |
11 | |
12 /* Miller-Rabin test of "a" to the base of "b" as described in | |
13 * HAC pp. 139 Algorithm 4.24 | |
14 * | |
15 * Sets result to 0 if definitely composite or 1 if probably prime. | |
16 * Randomly the chance of error is no more than 1/4 and often | |
17 * very much lower. | |
18 */ | |
19 void fp_prime_miller_rabin (fp_int * a, fp_int * b, int *result) | |
20 { | |
21 fp_int n1, y, r; | |
22 int s, j; | |
23 | |
24 /* default */ | |
25 *result = FP_NO; | |
26 | |
27 /* ensure b > 1 */ | |
28 if (fp_cmp_d(b, 1) != FP_GT) { | |
29 return; | |
30 } | |
31 | |
32 /* get n1 = a - 1 */ | |
33 fp_init_copy(&n1, a); | |
34 fp_sub_d(&n1, 1, &n1); | |
35 | |
36 /* set 2**s * r = n1 */ | |
37 fp_init_copy(&r, &n1); | |
38 | |
39 /* count the number of least significant bits | |
40 * which are zero | |
41 */ | |
42 s = fp_cnt_lsb(&r); | |
43 | |
44 /* now divide n - 1 by 2**s */ | |
45 fp_div_2d (&r, s, &r, NULL); | |
46 | |
47 /* compute y = b**r mod a */ | |
48 fp_init(&y); | |
49 fp_exptmod(b, &r, a, &y); | |
50 | |
51 /* if y != 1 and y != n1 do */ | |
52 if (fp_cmp_d (&y, 1) != FP_EQ && fp_cmp (&y, &n1) != FP_EQ) { | |
53 j = 1; | |
54 /* while j <= s-1 and y != n1 */ | |
55 while ((j <= (s - 1)) && fp_cmp (&y, &n1) != FP_EQ) { | |
56 fp_sqrmod (&y, a, &y); | |
57 | |
58 /* if y == 1 then composite */ | |
59 if (fp_cmp_d (&y, 1) == FP_EQ) { | |
60 return; | |
61 } | |
62 ++j; | |
63 } | |
64 | |
65 /* if y != n1 then composite */ | |
66 if (fp_cmp (&y, &n1) != FP_EQ) { | |
67 return; | |
68 } | |
69 } | |
70 | |
71 /* probably prime now */ | |
72 *result = FP_YES; | |
73 } | |
74 | |
75 /* $Source$ */ | |
76 /* $Revision$ */ | |
77 /* $Date$ */ |