int aws_fast_mp_invmod()

in AWSCognitoIdentityProvider/Internal/JKBigInteger/LibTomMath/tommath.c [6440:6560]


int aws_fast_mp_invmod(aws_mp_int *a, aws_mp_int *b, aws_mp_int *c)
{
  aws_mp_int x, y, u, v, B, D;
  int     res, neg;

  /* 2. [modified] b must be odd   */
  if (aws_mp_iseven (b) == 1) {
    return AWS_MP_VAL;
  }

  /* init all our temps */
  if ((res = aws_mp_init_multi(&x, &y, &u, &v, &B, &D, NULL)) != AWS_MP_OKAY) {
     return res;
  }

  /* x == modulus, y == value to invert */
  if ((res = aws_mp_copy(b, &x)) != AWS_MP_OKAY) {
    goto LBL_ERR;
  }

  /* we need y = |a| */
  if ((res = aws_mp_mod(a, b, &y)) != AWS_MP_OKAY) {
    goto LBL_ERR;
  }

  /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
  if ((res = aws_mp_copy(&x, &u)) != AWS_MP_OKAY) {
    goto LBL_ERR;
  }
  if ((res = aws_mp_copy(&y, &v)) != AWS_MP_OKAY) {
    goto LBL_ERR;
  }
    aws_mp_set(&D, 1);

top:
  /* 4.  while u is even do */
  while (aws_mp_iseven (&u) == 1) {
    /* 4.1 u = u/2 */
    if ((res = aws_mp_div_2(&u, &u)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }
    /* 4.2 if B is odd then */
    if (aws_mp_isodd (&B) == 1) {
      if ((res = aws_mp_sub(&B, &x, &B)) != AWS_MP_OKAY) {
        goto LBL_ERR;
      }
    }
    /* B = B/2 */
    if ((res = aws_mp_div_2(&B, &B)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }
  }

  /* 5.  while v is even do */
  while (aws_mp_iseven (&v) == 1) {
    /* 5.1 v = v/2 */
    if ((res = aws_mp_div_2(&v, &v)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }
    /* 5.2 if D is odd then */
    if (aws_mp_isodd (&D) == 1) {
      /* D = (D-x)/2 */
      if ((res = aws_mp_sub(&D, &x, &D)) != AWS_MP_OKAY) {
        goto LBL_ERR;
      }
    }
    /* D = D/2 */
    if ((res = aws_mp_div_2(&D, &D)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }
  }

  /* 6.  if u >= v then */
  if (aws_mp_cmp(&u, &v) != AWS_MP_LT) {
    /* u = u - v, B = B - D */
    if ((res = aws_mp_sub(&u, &v, &u)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }

    if ((res = aws_mp_sub(&B, &D, &B)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }
  } else {
    /* v - v - u, D = D - B */
    if ((res = aws_mp_sub(&v, &u, &v)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }

    if ((res = aws_mp_sub(&D, &B, &D)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }
  }

  /* if not zero goto step 4 */
  if (aws_mp_iszero (&u) == 0) {
    goto top;
  }

  /* now a = C, b = D, gcd == g*v */

  /* if v != 1 then there is no inverse */
  if (aws_mp_cmp_d(&v, 1) != AWS_MP_EQ) {
    res = AWS_MP_VAL;
    goto LBL_ERR;
  }

  /* b is now the inverse */
  neg = a->sign;
  while (D.sign == AWS_MP_NEG) {
    if ((res = aws_mp_add(&D, b, &D)) != AWS_MP_OKAY) {
      goto LBL_ERR;
    }
  }
    aws_mp_exch(&D, c);
  c->sign = neg;
  res = AWS_MP_OKAY;

LBL_ERR:
aws_mp_clear_multi(&x, &y, &u, &v, &B, &D, NULL);
  return res;
}