#include "tommath_private.h"
#ifdef BN_MP_SQRTMOD_PRIME_C
int
mp_sqrtmod_prime(
const
mp_int *n,
const
mp_int *prime, mp_int *ret)
{
int
res, legendre;
mp_int t1, C, Q, S, Z, M, T, R, two;
mp_digit i;
if
(mp_cmp_d(n, 0uL) == MP_EQ) {
mp_zero(ret);
return
MP_OKAY;
}
if
(mp_cmp_d(prime, 2uL) == MP_EQ)
return
MP_VAL;
if
((res = mp_jacobi(n, prime, &legendre)) != MP_OKAY)
return
res;
if
(legendre == -1)
return
MP_VAL;
if
((res = mp_init_multi(&t1, &C, &Q, &S, &Z, &M, &T, &R, &two, NULL)) != MP_OKAY) {
return
res;
}
if
((res = mp_mod_d(prime, 4uL, &i)) != MP_OKAY)
goto
cleanup;
if
(i == 3u) {
if
((res = mp_add_d(prime, 1uL, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_div_2(&t1, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_div_2(&t1, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_exptmod(n, &t1, prime, ret)) != MP_OKAY)
goto
cleanup;
res = MP_OKAY;
goto
cleanup;
}
if
((res = mp_copy(prime, &Q)) != MP_OKAY)
goto
cleanup;
if
((res = mp_sub_d(&Q, 1uL, &Q)) != MP_OKAY)
goto
cleanup;
mp_zero(&S);
while
(mp_iseven(&Q) != MP_NO) {
if
((res = mp_div_2(&Q, &Q)) != MP_OKAY)
goto
cleanup;
if
((res = mp_add_d(&S, 1uL, &S)) != MP_OKAY)
goto
cleanup;
}
if
((res = mp_set_int(&Z, 2uL)) != MP_OKAY)
goto
cleanup;
while
(1) {
if
((res = mp_jacobi(&Z, prime, &legendre)) != MP_OKAY)
goto
cleanup;
if
(legendre == -1)
break
;
if
((res = mp_add_d(&Z, 1uL, &Z)) != MP_OKAY)
goto
cleanup;
}
if
((res = mp_exptmod(&Z, &Q, prime, &C)) != MP_OKAY)
goto
cleanup;
if
((res = mp_add_d(&Q, 1uL, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_div_2(&t1, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_exptmod(n, &t1, prime, &R)) != MP_OKAY)
goto
cleanup;
if
((res = mp_exptmod(n, &Q, prime, &T)) != MP_OKAY)
goto
cleanup;
if
((res = mp_copy(&S, &M)) != MP_OKAY)
goto
cleanup;
if
((res = mp_set_int(&two, 2uL)) != MP_OKAY)
goto
cleanup;
res = MP_VAL;
while
(1) {
if
((res = mp_copy(&T, &t1)) != MP_OKAY)
goto
cleanup;
i = 0;
while
(1) {
if
(mp_cmp_d(&t1, 1uL) == MP_EQ)
break
;
if
((res = mp_exptmod(&t1, &two, prime, &t1)) != MP_OKAY)
goto
cleanup;
i++;
}
if
(i == 0u) {
if
((res = mp_copy(&R, ret)) != MP_OKAY)
goto
cleanup;
res = MP_OKAY;
goto
cleanup;
}
if
((res = mp_sub_d(&M, i, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_sub_d(&t1, 1uL, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_exptmod(&two, &t1, prime, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_exptmod(&C, &t1, prime, &t1)) != MP_OKAY)
goto
cleanup;
if
((res = mp_sqrmod(&t1, prime, &C)) != MP_OKAY)
goto
cleanup;
if
((res = mp_mulmod(&R, &t1, prime, &R)) != MP_OKAY)
goto
cleanup;
if
((res = mp_mulmod(&T, &C, prime, &T)) != MP_OKAY)
goto
cleanup;
mp_set(&M, i);
}
cleanup:
mp_clear_multi(&t1, &C, &Q, &S, &Z, &M, &T, &R, &two, NULL);
return
res;
}
#endif