1 #include "tommath_private.h"
2 #ifdef MP_PRIME_MILLER_RABIN_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* Miller-Rabin test of "a" to the base of "b" as described in
7 * HAC pp. 139 Algorithm 4.24
9 * Sets result to 0 if definitely composite or 1 if probably prime.
10 * Randomly the chance of error is no more than 1/4 and often
13 mp_err
mp_prime_miller_rabin(const mp_int
*a
, const mp_int
*b
, bool *result
)
20 if (mp_cmp_d(b
, 1uL) != MP_GT
) {
25 if ((err
= mp_init_copy(&n1
, a
)) != MP_OKAY
) {
28 if ((err
= mp_sub_d(&n1
, 1uL, &n1
)) != MP_OKAY
) {
32 /* set 2**s * r = n1 */
33 if ((err
= mp_init_copy(&r
, &n1
)) != MP_OKAY
) {
37 /* count the number of least significant bits
42 /* now divide n - 1 by 2**s */
43 if ((err
= mp_div_2d(&r
, s
, &r
, NULL
)) != MP_OKAY
) {
47 /* compute y = b**r mod a */
48 if ((err
= mp_init(&y
)) != MP_OKAY
) {
51 if ((err
= mp_exptmod(b
, &r
, a
, &y
)) != MP_OKAY
) {
55 /* if y != 1 and y != n1 do */
56 if ((mp_cmp_d(&y
, 1uL) != MP_EQ
) && (mp_cmp(&y
, &n1
) != MP_EQ
)) {
58 /* while j <= s-1 and y != n1 */
59 while ((j
<= (s
- 1)) && (mp_cmp(&y
, &n1
) != MP_EQ
)) {
60 if ((err
= mp_sqrmod(&y
, a
, &y
)) != MP_OKAY
) {
64 /* if y == 1 then composite */
65 if (mp_cmp_d(&y
, 1uL) == MP_EQ
) {
73 /* if y != n1 then composite */
74 if (mp_cmp(&y
, &n1
) != MP_EQ
) {
80 /* probably prime now */