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