#include <tfm.h>
static int fp_invmod_slow (fp_int * a, fp_int * b, fp_int * c)
{
fp_int x, y, u, v, A, B, C, D;
int res;
if (b->sign == FP_NEG || fp_iszero(b) == 1) {
return FP_VAL;
}
fp_init(&x); fp_init(&y);
fp_init(&u); fp_init(&v);
fp_init(&A); fp_init(&B);
fp_init(&C); fp_init(&D);
if ((res = fp_mod(a, b, &x)) != FP_OKAY) {
return res;
}
fp_copy(b, &y);
if (fp_iseven (&x) == 1 && fp_iseven (&y) == 1) {
return FP_VAL;
}
fp_copy (&x, &u);
fp_copy (&y, &v);
fp_set (&A, 1);
fp_set (&D, 1);
top:
while (fp_iseven (&u) == 1) {
fp_div_2 (&u, &u);
if (fp_isodd (&A) == 1 || fp_isodd (&B) == 1) {
fp_add (&A, &y, &A);
fp_sub (&B, &x, &B);
}
fp_div_2 (&A, &A);
fp_div_2 (&B, &B);
}
while (fp_iseven (&v) == 1) {
fp_div_2 (&v, &v);
if (fp_isodd (&C) == 1 || fp_isodd (&D) == 1) {
fp_add (&C, &y, &C);
fp_sub (&D, &x, &D);
}
fp_div_2 (&C, &C);
fp_div_2 (&D, &D);
}
if (fp_cmp (&u, &v) != FP_LT) {
fp_sub (&u, &v, &u);
fp_sub (&A, &C, &A);
fp_sub (&B, &D, &B);
} else {
fp_sub (&v, &u, &v);
fp_sub (&C, &A, &C);
fp_sub (&D, &B, &D);
}
if (fp_iszero (&u) == 0)
goto top;
if (fp_cmp_d (&v, 1) != FP_EQ) {
return FP_VAL;
}
while (fp_cmp_d(&C, 0) == FP_LT) {
fp_add(&C, b, &C);
}
while (fp_cmp_mag(&C, b) != FP_LT) {
fp_sub(&C, b, &C);
}
fp_copy(&C, c);
return FP_OKAY;
}
int fp_invmod(fp_int *a, fp_int *b, fp_int *c)
{
fp_int x, y, u, v, B, D;
int neg;
if (fp_iseven (b) == FP_YES) {
return fp_invmod_slow(a,b,c);
}
fp_init(&x); fp_init(&y);
fp_init(&u); fp_init(&v);
fp_init(&B); fp_init(&D);
fp_copy(b, &x);
fp_abs(a, &y);
fp_copy(&x, &u);
fp_copy(&y, &v);
fp_set (&D, 1);
top:
while (fp_iseven (&u) == FP_YES) {
fp_div_2 (&u, &u);
if (fp_isodd (&B) == FP_YES) {
fp_sub (&B, &x, &B);
}
fp_div_2 (&B, &B);
}
while (fp_iseven (&v) == FP_YES) {
fp_div_2 (&v, &v);
if (fp_isodd (&D) == FP_YES) {
fp_sub (&D, &x, &D);
}
fp_div_2 (&D, &D);
}
if (fp_cmp (&u, &v) != FP_LT) {
fp_sub (&u, &v, &u);
fp_sub (&B, &D, &B);
} else {
fp_sub (&v, &u, &v);
fp_sub (&D, &B, &D);
}
if (fp_iszero (&u) == FP_NO) {
goto top;
}
if (fp_cmp_d (&v, 1) != FP_EQ) {
return FP_VAL;
}
neg = a->sign;
while (D.sign == FP_NEG) {
fp_add (&D, b, &D);
}
fp_copy (&D, c);
c->sign = neg;
return FP_OKAY;
}