1 #include "tommath_private.h"
2 #ifdef BN_MP_EXTEUCLID_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
5
6 /* Extended euclidean algorithm of (a, b) produces
7 a*u1 + b*u2 = u3
8 */
mp_exteuclid(const mp_int * a,const mp_int * b,mp_int * U1,mp_int * U2,mp_int * U3)9 mp_err mp_exteuclid(const mp_int *a, const mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3)
10 {
11 mp_int u1, u2, u3, v1, v2, v3, t1, t2, t3, q, tmp;
12 mp_err err;
13
14 if ((err = mp_init_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL)) != MP_OKAY) {
15 return err;
16 }
17
18 /* initialize, (u1,u2,u3) = (1,0,a) */
19 mp_set(&u1, 1uL);
20 if ((err = mp_copy(a, &u3)) != MP_OKAY) goto LBL_ERR;
21
22 /* initialize, (v1,v2,v3) = (0,1,b) */
23 mp_set(&v2, 1uL);
24 if ((err = mp_copy(b, &v3)) != MP_OKAY) goto LBL_ERR;
25
26 /* loop while v3 != 0 */
27 while (!MP_IS_ZERO(&v3)) {
28 /* q = u3/v3 */
29 if ((err = mp_div(&u3, &v3, &q, NULL)) != MP_OKAY) goto LBL_ERR;
30
31 /* (t1,t2,t3) = (u1,u2,u3) - (v1,v2,v3)q */
32 if ((err = mp_mul(&v1, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
33 if ((err = mp_sub(&u1, &tmp, &t1)) != MP_OKAY) goto LBL_ERR;
34 if ((err = mp_mul(&v2, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
35 if ((err = mp_sub(&u2, &tmp, &t2)) != MP_OKAY) goto LBL_ERR;
36 if ((err = mp_mul(&v3, &q, &tmp)) != MP_OKAY) goto LBL_ERR;
37 if ((err = mp_sub(&u3, &tmp, &t3)) != MP_OKAY) goto LBL_ERR;
38
39 /* (u1,u2,u3) = (v1,v2,v3) */
40 if ((err = mp_copy(&v1, &u1)) != MP_OKAY) goto LBL_ERR;
41 if ((err = mp_copy(&v2, &u2)) != MP_OKAY) goto LBL_ERR;
42 if ((err = mp_copy(&v3, &u3)) != MP_OKAY) goto LBL_ERR;
43
44 /* (v1,v2,v3) = (t1,t2,t3) */
45 if ((err = mp_copy(&t1, &v1)) != MP_OKAY) goto LBL_ERR;
46 if ((err = mp_copy(&t2, &v2)) != MP_OKAY) goto LBL_ERR;
47 if ((err = mp_copy(&t3, &v3)) != MP_OKAY) goto LBL_ERR;
48 }
49
50 /* make sure U3 >= 0 */
51 if (u3.sign == MP_NEG) {
52 if ((err = mp_neg(&u1, &u1)) != MP_OKAY) goto LBL_ERR;
53 if ((err = mp_neg(&u2, &u2)) != MP_OKAY) goto LBL_ERR;
54 if ((err = mp_neg(&u3, &u3)) != MP_OKAY) goto LBL_ERR;
55 }
56
57 /* copy result out */
58 if (U1 != NULL) {
59 mp_exch(U1, &u1);
60 }
61 if (U2 != NULL) {
62 mp_exch(U2, &u2);
63 }
64 if (U3 != NULL) {
65 mp_exch(U3, &u3);
66 }
67
68 err = MP_OKAY;
69 LBL_ERR:
70 mp_clear_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL);
71 return err;
72 }
73 #endif
74