CryptX
view release on metacpan or search on metacpan
src/ltm/bn_mp_sqrtmod_prime.c view on Meta::CPAN
*/
/* Tonelli-Shanks algorithm
* https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
* https://gmplib.org/list-archives/gmp-discuss/2013-April/005300.html
*
*/
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;
/* first handle the simple cases */
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; /* prime must be odd */
if ((res = mp_jacobi(n, prime, &legendre)) != MP_OKAY) return res;
if (legendre == -1) return MP_VAL; /* quadratic non-residue mod prime */
if ((res = mp_init_multi(&t1, &C, &Q, &S, &Z, &M, &T, &R, &two, NULL)) != MP_OKAY) {
return res;
}
/* SPECIAL CASE: if prime mod 4 == 3
* compute directly: res = n^(prime+1)/4 mod prime
* Handbook of Applied Cryptography algorithm 3.36
*/
if ((res = mp_mod_d(prime, 4uL, &i)) != MP_OKAY) goto cleanup;
src/ltm/bn_mp_sqrtmod_prime.c view on Meta::CPAN
if ((res = mp_div_2(&Q, &Q)) != MP_OKAY) goto cleanup;
/* Q = Q / 2 */
if ((res = mp_add_d(&S, 1uL, &S)) != MP_OKAY) goto cleanup;
/* S = S + 1 */
}
/* find a Z such that the Legendre symbol (Z|prime) == -1 */
if ((res = mp_set_int(&Z, 2uL)) != MP_OKAY) goto cleanup;
/* Z = 2 */
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;
/* Z = Z + 1 */
}
if ((res = mp_exptmod(&Z, &Q, prime, &C)) != MP_OKAY) goto cleanup;
/* C = Z ^ Q mod prime */
if ((res = mp_add_d(&Q, 1uL, &t1)) != MP_OKAY) goto cleanup;
if ((res = mp_div_2(&t1, &t1)) != MP_OKAY) goto cleanup;
/* t1 = (Q + 1) / 2 */
if ((res = mp_exptmod(n, &t1, prime, &R)) != MP_OKAY) goto cleanup;
( run in 1.163 second using v1.01-cache-2.11-cpan-49f99fa48dc )