5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2005 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 #include "silccrypto.h"
22 /* Table for finding multiplicative inverse */
27 #define plus1 (i == 2 ? 0 : i + 1)
28 #define minus1 (i == 0 ? 2 : i - 1)
30 /* Find multiplicative inverse using Euclid's extended algorithm.
31 Computes inverse such that a * inv mod n = 1, where 0 < a < n.
32 Algorithm goes like this:
38 g(i+1) = g(i-1) - y * g(i) = g(i)-1 mod g(i)
39 v(i+1) = v(i-1) - y * v(i)
41 do until g(i) = 0, then inverse = v(i-1). If inverse is negative then n,
42 is added to inverse making it positive again. (Sometimes the algorithm
43 has a variable u defined too and it behaves just like v, except that
44 initalize values are swapped (i.e. u(0) = 1, u(1) = 0). However, u is
45 not needed by the algorithm so it does not have to be included.)
48 void silc_mp_modinv(SilcMPInt *inv, SilcMPInt *a, SilcMPInt *n)
60 silc_mp_init(&v[0].x);
61 silc_mp_init(&v[1].x);
62 silc_mp_set_ui(&v[0].x, 0L); /* v(0) = 0 */
63 silc_mp_set_ui(&v[1].x, 1L); /* v(1) = 1 */
64 silc_mp_init(&v[2].x);
65 silc_mp_init(&g[0].x);
66 silc_mp_init(&g[1].x);
67 silc_mp_set(&g[0].x, n); /* g(0) = n */
68 silc_mp_set(&g[1].x, a); /* g(1) = a */
69 silc_mp_init(&g[2].x);
72 while(silc_mp_cmp_ui(&g[i].x, 0) != 0) {
73 silc_mp_div(&y, &g[minus1].x, &g[i].x); /* y = n / a */
74 silc_mp_mod(&g[plus1].x, &g[minus1].x, &g[i].x); /* remainder */
75 silc_mp_mul(&x, &y, &v[i].x);
76 silc_mp_set(&v[plus1].x, &v[minus1].x);
77 silc_mp_sub(&v[plus1].x, &v[plus1].x, &x);
82 silc_mp_set(inv, &v[minus1].x);
84 /* if inverse is negative, add n to inverse */
85 if (silc_mp_cmp_ui(inv, 0) < 0)
86 silc_mp_add(inv, inv, n);
89 memset(&g, 0, sizeof(g));
90 memset(&v, 0, sizeof(v));
93 silc_mp_uninit(&g[0].x);
94 silc_mp_uninit(&g[1].x);
95 silc_mp_uninit(&g[2].x);
96 silc_mp_uninit(&v[0].x);
97 silc_mp_uninit(&v[1].x);
98 silc_mp_uninit(&v[2].x);