1 /* mpi-inv.c - MPI functions
2 * Copyright (C) 1998, 2001, 2002, 2003 Free Software Foundation, Inc.
4 * This file is part of Libgcrypt.
6 * Libgcrypt is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 2.1 of
9 * the License, or (at your option) any later version.
11 * Libgcrypt is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include "mpi-internal.h"
23 * Calculate the multiplicative inverse X of A mod N
24 * That is: Find the solution x for
27 int mpi_invm(MPI x
, MPI a
, MPI n
)
29 /* Extended Euclid's algorithm (See TAOCP Vol II, 4.5.2, Alg X)
30 * modified according to Michael Penk's solution for Exercise 35
31 * with further enhancement
33 MPI u
, v
, u1
, u2
= NULL
, u3
, v1
, v2
= NULL
, v3
, t1
, t2
= NULL
, t3
;
38 if (!mpi_cmp_ui(a
, 0))
39 return 0; /* Inverse does not exists. */
40 if (!mpi_cmp_ui(n
, 1))
41 return 0; /* Inverse does not exists. */
46 for (k
= 0; !mpi_test_bit(u
, 0) && !mpi_test_bit(v
, 0); k
++) {
50 odd
= mpi_test_bit(v
, 0);
52 u1
= mpi_alloc_set_ui(1);
54 u2
= mpi_alloc_set_ui(0);
58 v2
= mpi_alloc(mpi_get_nlimbs(u
));
59 mpi_sub(v2
, u1
, u
); /* U is used as const 1 */
62 if (mpi_test_bit(u
, 0)) { /* u is odd */
63 t1
= mpi_alloc_set_ui(0);
65 t2
= mpi_alloc_set_ui(1);
72 t1
= mpi_alloc_set_ui(1);
74 t2
= mpi_alloc_set_ui(0);
81 if (mpi_test_bit(t1
, 0) || mpi_test_bit(t2
, 0)) {
86 mpi_rshift(t1
, t1
, 1);
87 mpi_rshift(t2
, t2
, 1);
88 mpi_rshift(t3
, t3
, 1);
90 if (mpi_test_bit(t1
, 0))
92 mpi_rshift(t1
, t1
, 1);
93 mpi_rshift(t3
, t3
, 1);
97 } while (!mpi_test_bit(t3
, 0)); /* while t3 is even */
106 sign
= u
->sign
; u
->sign
= !u
->sign
;
110 sign
= t3
->sign
; t3
->sign
= !t3
->sign
;
123 } while (mpi_cmp_ui(t3
, 0)); /* while t3 != 0 */
124 /* mpi_lshift( u3, k ); */
143 EXPORT_SYMBOL_GPL(mpi_invm
);