f612c6de349d7b59dafa72379ca1c14e0c4481d7
[platform/upstream/nettle.git] / examples / rsa-verify.c
1 /* rsa-verify.c
2
3    Copyright (C) 2002 Niels Möller
4
5    This file is part of GNU Nettle.
6
7    GNU Nettle is free software: you can redistribute it and/or
8    modify it under the terms of either:
9
10      * the GNU Lesser General Public License as published by the Free
11        Software Foundation; either version 3 of the License, or (at your
12        option) any later version.
13
14    or
15
16      * the GNU General Public License as published by the Free
17        Software Foundation; either version 2 of the License, or (at your
18        option) any later version.
19
20    or both in parallel, as here.
21
22    GNU Nettle is distributed in the hope that it will be useful,
23    but WITHOUT ANY WARRANTY; without even the implied warranty of
24    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25    General Public License for more details.
26
27    You should have received copies of the GNU General Public License and
28    the GNU Lesser General Public License along with this program.  If
29    not, see http://www.gnu.org/licenses/.
30 */
31
32 #if HAVE_CONFIG_H
33 # include "config.h"
34 #endif
35
36 #include <errno.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <string.h>
40
41 #include "rsa.h"
42 #include "io.h"
43
44 static int
45 read_signature(const char *name, mpz_t s)
46 {
47   char *buffer;
48   unsigned length;
49   int res;
50   
51   length = read_file(name, 0, &buffer);
52   if (!length)
53     return 0;
54
55   res = (mpz_set_str(s, buffer, 16) == 0);
56   free(buffer);
57
58   return res;
59 }
60
61 int
62 main(int argc, char **argv)
63 {
64   struct rsa_public_key key;
65   struct sha1_ctx hash;
66   mpz_t s;
67   
68   if (argc != 3)
69     {
70       werror("Usage: rsa-verify PUBLIC-KEY SIGNATURE-FILE < FILE\n");
71       return EXIT_FAILURE;
72     }
73
74   rsa_public_key_init(&key);
75   
76   if (!read_rsa_key(argv[1], &key, NULL))
77     {
78       werror("Invalid key\n");
79       return EXIT_FAILURE;
80     }
81
82   mpz_init(s);
83
84   if (!read_signature(argv[2], s))
85     {
86       werror("Failed to read signature file `%s'\n",
87               argv[2]);
88       return EXIT_FAILURE;
89     }
90   
91   sha1_init(&hash);
92   if (!hash_file(&nettle_sha1, &hash, stdin))
93     {
94       werror("Failed reading stdin: %s\n",
95               strerror(errno));
96       return 0;
97     }
98
99   if (!rsa_sha1_verify(&key, &hash, s))
100     {
101       werror("Invalid signature!\n");
102       return EXIT_FAILURE;
103     }
104     
105   mpz_clear(s);
106   rsa_public_key_clear(&key);
107
108   return EXIT_SUCCESS;
109 }