|
1 /* |
|
2 * invmod.c |
|
3 * |
|
4 * Compute modular inverses |
|
5 * |
|
6 * This Source Code Form is subject to the terms of the Mozilla Public |
|
7 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
8 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
9 |
|
10 #include <stdio.h> |
|
11 #include <stdlib.h> |
|
12 |
|
13 #include "mpi.h" |
|
14 |
|
15 int main(int argc, char *argv[]) |
|
16 { |
|
17 mp_int a, m; |
|
18 mp_err res; |
|
19 char *buf; |
|
20 int len, out = 0; |
|
21 |
|
22 if(argc < 3) { |
|
23 fprintf(stderr, "Usage: %s <a> <m>\n", argv[0]); |
|
24 return 1; |
|
25 } |
|
26 |
|
27 mp_init(&a); mp_init(&m); |
|
28 mp_read_radix(&a, argv[1], 10); |
|
29 mp_read_radix(&m, argv[2], 10); |
|
30 |
|
31 if(mp_cmp(&a, &m) > 0) |
|
32 mp_mod(&a, &m, &a); |
|
33 |
|
34 switch((res = mp_invmod(&a, &m, &a))) { |
|
35 case MP_OKAY: |
|
36 len = mp_radix_size(&a, 10); |
|
37 buf = malloc(len); |
|
38 |
|
39 mp_toradix(&a, buf, 10); |
|
40 printf("%s\n", buf); |
|
41 free(buf); |
|
42 break; |
|
43 |
|
44 case MP_UNDEF: |
|
45 printf("No inverse\n"); |
|
46 out = 1; |
|
47 break; |
|
48 |
|
49 default: |
|
50 printf("error: %s (%d)\n", mp_strerror(res), res); |
|
51 out = 2; |
|
52 break; |
|
53 } |
|
54 |
|
55 mp_clear(&a); |
|
56 mp_clear(&m); |
|
57 |
|
58 return out; |
|
59 } |