comparison bn_mp_exteuclid.c @ 2:86e0b50a9b58 libtommath-orig ltm-0.30-orig

ltm 0.30 orig import
author Matt Johnston <matt@ucc.asn.au>
date Mon, 31 May 2004 18:25:22 +0000
parents
children d29b64170cf0
comparison
equal deleted inserted replaced
-1:000000000000 2:86e0b50a9b58
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
2 *
3 * LibTomMath is a library that provides multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
5 *
6 * The library was designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
9 *
10 * The library is free for all purposes without any express
11 * guarantee it works.
12 *
13 * Tom St Denis, [email protected], http://math.libtomcrypt.org
14 */
15 #include <tommath.h>
16
17 /* Extended euclidean algorithm of (a, b) produces
18 a*u1 + b*u2 = u3
19 */
20 int mp_exteuclid(mp_int *a, mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3)
21 {
22 mp_int u1,u2,u3,v1,v2,v3,t1,t2,t3,q,tmp;
23 int err;
24
25 if ((err = mp_init_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL)) != MP_OKAY) {
26 return err;
27 }
28
29 /* initialize, (u1,u2,u3) = (1,0,a) */
30 mp_set(&u1, 1);
31 if ((err = mp_copy(a, &u3)) != MP_OKAY) { goto _ERR; }
32
33 /* initialize, (v1,v2,v3) = (0,1,b) */
34 mp_set(&v2, 1);
35 if ((err = mp_copy(b, &v3)) != MP_OKAY) { goto _ERR; }
36
37 /* loop while v3 != 0 */
38 while (mp_iszero(&v3) == MP_NO) {
39 /* q = u3/v3 */
40 if ((err = mp_div(&u3, &v3, &q, NULL)) != MP_OKAY) { goto _ERR; }
41
42 /* (t1,t2,t3) = (u1,u2,u3) - (v1,v2,v3)q */
43 if ((err = mp_mul(&v1, &q, &tmp)) != MP_OKAY) { goto _ERR; }
44 if ((err = mp_sub(&u1, &tmp, &t1)) != MP_OKAY) { goto _ERR; }
45 if ((err = mp_mul(&v2, &q, &tmp)) != MP_OKAY) { goto _ERR; }
46 if ((err = mp_sub(&u2, &tmp, &t2)) != MP_OKAY) { goto _ERR; }
47 if ((err = mp_mul(&v3, &q, &tmp)) != MP_OKAY) { goto _ERR; }
48 if ((err = mp_sub(&u3, &tmp, &t3)) != MP_OKAY) { goto _ERR; }
49
50 /* (u1,u2,u3) = (v1,v2,v3) */
51 if ((err = mp_copy(&v1, &u1)) != MP_OKAY) { goto _ERR; }
52 if ((err = mp_copy(&v2, &u2)) != MP_OKAY) { goto _ERR; }
53 if ((err = mp_copy(&v3, &u3)) != MP_OKAY) { goto _ERR; }
54
55 /* (v1,v2,v3) = (t1,t2,t3) */
56 if ((err = mp_copy(&t1, &v1)) != MP_OKAY) { goto _ERR; }
57 if ((err = mp_copy(&t2, &v2)) != MP_OKAY) { goto _ERR; }
58 if ((err = mp_copy(&t3, &v3)) != MP_OKAY) { goto _ERR; }
59 }
60
61 /* copy result out */
62 if (U1 != NULL) { mp_exch(U1, &u1); }
63 if (U2 != NULL) { mp_exch(U2, &u2); }
64 if (U3 != NULL) { mp_exch(U3, &u3); }
65
66 err = MP_OKAY;
67 _ERR: mp_clear_multi(&u1, &u2, &u3, &v1, &v2, &v3, &t1, &t2, &t3, &q, &tmp, NULL);
68 return err;
69 }