1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
3 * LibTomMath is library that provides for multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
6 * The library is designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
10 * The library is free for all purposes without any express
13 * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
18 mp_invmod (mp_int * a, mp_int * b, mp_int * c)
20 mp_int x, y, u, v, A, B, C, D;
23 /* b cannot be negative */
24 if (b->sign == MP_NEG) {
28 /* if the modulus is odd we can use a faster routine instead */
29 if (mp_iseven (b) == 0) {
30 return fast_mp_invmod (a, b, c);
34 if ((res = mp_init_multi(&x, &y, &u, &v, &A, &B, &C, &D, NULL)) != MP_OKAY) {
39 if ((res = mp_copy (a, &x)) != MP_OKAY) {
42 if ((res = mp_copy (b, &y)) != MP_OKAY) {
46 if ((res = mp_abs (&x, &x)) != MP_OKAY) {
50 /* 2. [modified] if x,y are both even then return an error! */
51 if (mp_iseven (&x) == 1 && mp_iseven (&y) == 1) {
56 /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
57 if ((res = mp_copy (&x, &u)) != MP_OKAY) {
60 if ((res = mp_copy (&y, &v)) != MP_OKAY) {
68 /* 4. while u is even do */
69 while (mp_iseven (&u) == 1) {
71 if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
74 /* 4.2 if A or B is odd then */
75 if (mp_iseven (&A) == 0 || mp_iseven (&B) == 0) {
76 /* A = (A+y)/2, B = (B-x)/2 */
77 if ((res = mp_add (&A, &y, &A)) != MP_OKAY) {
80 if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
84 /* A = A/2, B = B/2 */
85 if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
88 if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
94 /* 5. while v is even do */
95 while (mp_iseven (&v) == 1) {
97 if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
100 /* 5.2 if C,D are even then */
101 if (mp_iseven (&C) == 0 || mp_iseven (&D) == 0) {
102 /* C = (C+y)/2, D = (D-x)/2 */
103 if ((res = mp_add (&C, &y, &C)) != MP_OKAY) {
106 if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
110 /* C = C/2, D = D/2 */
111 if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
114 if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
119 /* 6. if u >= v then */
120 if (mp_cmp (&u, &v) != MP_LT) {
121 /* u = u - v, A = A - C, B = B - D */
122 if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
126 if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
130 if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
134 /* v - v - u, C = C - A, D = D - B */
135 if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
139 if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
143 if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
148 /* if not zero goto step 4 */
149 if (mp_iszero (&u) == 0)
152 /* now a = C, b = D, gcd == g*v */
154 /* if v != 1 then there is no inverse */
155 if (mp_cmp_d (&v, 1) != MP_EQ) {
160 /* matt - need to make 1 <= C */
161 while (mp_cmp_d(&C, 1) == MP_LT) {
162 if (mp_add(&C, b, &C) != MP_OKAY) {
167 /* a is now the inverse */
171 __ERR:mp_clear_multi (&x, &y, &u, &v, &A, &B, &C, &D, NULL);