1 #include "tommath_private.h"
2 #ifdef BN_S_MP_INVMOD_FAST_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* computes the modular inverse via binary extended euclidean algorithm,
7 * that is c = 1/a mod b
9 * Based on slow invmod except this is optimized for the case where b is
10 * odd as per HAC Note 14.64 on pp. 610
12 mp_err s_mp_invmod_fast(const mp_int *a, const mp_int *b, mp_int *c)
14 mp_int x, y, u, v, B, D;
18 /* 2. [modified] b must be odd */
23 /* init all our temps */
24 if ((err = mp_init_multi(&x, &y, &u, &v, &B, &D, NULL)) != MP_OKAY) {
28 /* x == modulus, y == value to invert */
29 if ((err = mp_copy(b, &x)) != MP_OKAY) goto LBL_ERR;
32 if ((err = mp_mod(a, b, &y)) != MP_OKAY) goto LBL_ERR;
34 /* if one of x,y is zero return an error! */
35 if (MP_IS_ZERO(&x) || MP_IS_ZERO(&y)) {
40 /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
41 if ((err = mp_copy(&x, &u)) != MP_OKAY) goto LBL_ERR;
42 if ((err = mp_copy(&y, &v)) != MP_OKAY) goto LBL_ERR;
46 /* 4. while u is even do */
47 while (MP_IS_EVEN(&u)) {
49 if ((err = mp_div_2(&u, &u)) != MP_OKAY) goto LBL_ERR;
51 /* 4.2 if B is odd then */
53 if ((err = mp_sub(&B, &x, &B)) != MP_OKAY) goto LBL_ERR;
56 if ((err = mp_div_2(&B, &B)) != MP_OKAY) goto LBL_ERR;
59 /* 5. while v is even do */
60 while (MP_IS_EVEN(&v)) {
62 if ((err = mp_div_2(&v, &v)) != MP_OKAY) goto LBL_ERR;
64 /* 5.2 if D is odd then */
67 if ((err = mp_sub(&D, &x, &D)) != MP_OKAY) goto LBL_ERR;
70 if ((err = mp_div_2(&D, &D)) != MP_OKAY) goto LBL_ERR;
73 /* 6. if u >= v then */
74 if (mp_cmp(&u, &v) != MP_LT) {
75 /* u = u - v, B = B - D */
76 if ((err = mp_sub(&u, &v, &u)) != MP_OKAY) goto LBL_ERR;
78 if ((err = mp_sub(&B, &D, &B)) != MP_OKAY) goto LBL_ERR;
80 /* v - v - u, D = D - B */
81 if ((err = mp_sub(&v, &u, &v)) != MP_OKAY) goto LBL_ERR;
83 if ((err = mp_sub(&D, &B, &D)) != MP_OKAY) goto LBL_ERR;
86 /* if not zero goto step 4 */
87 if (!MP_IS_ZERO(&u)) {
91 /* now a = C, b = D, gcd == g*v */
93 /* if v != 1 then there is no inverse */
94 if (mp_cmp_d(&v, 1uL) != MP_EQ) {
99 /* b is now the inverse */
101 while (D.sign == MP_NEG) {
102 if ((err = mp_add(&D, b, &D)) != MP_OKAY) goto LBL_ERR;
106 while (mp_cmp_mag(&D, b) != MP_LT) {
107 if ((err = mp_sub(&D, b, &D)) != MP_OKAY) goto LBL_ERR;
115 mp_clear_multi(&x, &y, &u, &v, &B, &D, NULL);