| 1 |
#include "tommath_private.h" |
| 2 |
#ifdef BN_MP_PRIME_MILLER_RABIN_C |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
mp_err mp_prime_miller_rabin(const mp_int *a, const mp_int *b, mp_bool *result) |
| 14 |
{ |
| 15 |
mp_int n1, y, r; |
| 16 |
mp_err err; |
| 17 |
int s, j; |
| 18 |
|
| 19 |
|
| 20 |
*result = MP_NO; |
| 21 |
|
| 22 |
|
| 23 |
if (mp_cmp_d(b, 1uL) != MP_GT) { |
| 24 |
return MP_VAL; |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
if ((err = mp_init_copy(&n1, a)) != MP_OKAY) { |
| 29 |
return err; |
| 30 |
} |
| 31 |
if ((err = mp_sub_d(&n1, 1uL, &n1)) != MP_OKAY) { |
| 32 |
goto LBL_N1; |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
if ((err = mp_init_copy(&r, &n1)) != MP_OKAY) { |
| 37 |
goto LBL_N1; |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
s = mp_cnt_lsb(&r); |
| 44 |
|
| 45 |
|
| 46 |
if ((err = mp_div_2d(&r, s, &r, NULL)) != MP_OKAY) { |
| 47 |
goto LBL_R; |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
if ((err = mp_init(&y)) != MP_OKAY) { |
| 52 |
goto LBL_R; |
| 53 |
} |
| 54 |
if ((err = mp_exptmod(b, &r, a, &y)) != MP_OKAY) { |
| 55 |
goto LBL_Y; |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
if ((mp_cmp_d(&y, 1uL) != MP_EQ) && (mp_cmp(&y, &n1) != MP_EQ)) { |
| 60 |
j = 1; |
| 61 |
|
| 62 |
while ((j <= (s - 1)) && (mp_cmp(&y, &n1) != MP_EQ)) { |
| 63 |
if ((err = mp_sqrmod(&y, a, &y)) != MP_OKAY) { |
| 64 |
goto LBL_Y; |
| 65 |
} |
| 66 |
|
| 67 |
|
| 68 |
if (mp_cmp_d(&y, 1uL) == MP_EQ) { |
| 69 |
goto LBL_Y; |
| 70 |
} |
| 71 |
|
| 72 |
++j; |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
if (mp_cmp(&y, &n1) != MP_EQ) { |
| 77 |
goto LBL_Y; |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
*result = MP_YES; |
| 83 |
LBL_Y: |
| 84 |
mp_clear(&y); |
| 85 |
LBL_R: |
| 86 |
mp_clear(&r); |
| 87 |
LBL_N1: |
| 88 |
mp_clear(&n1); |
| 89 |
return err; |
| 90 |
} |
| 91 |
#endif |