minor changes for address conversion
[oweals/gnunet.git] / src / util / gnunet-ecc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012, 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/gnunet-ecc.c
23  * @brief tool to manipulate EDDSA key files
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_testing_lib.h"
29 #include <gcrypt.h>
30
31
32 /**
33  * Flag for listing public key.
34  */
35 static int list_keys;
36
37 /**
38  * Flag for listing public key.
39  */
40 static int list_keys_count;
41
42 /**
43  * Flag for printing public key.
44  */
45 static int print_public_key;
46
47 /**
48  * Flag for printing the output of random example operations.
49  */
50 static int print_examples_flag;
51
52 /**
53  * Flag for printing hash of public key.
54  */
55 static int print_peer_identity;
56
57 /**
58  * Option set to create a bunch of keys at once.
59  */
60 static unsigned int make_keys;
61
62
63 /**
64  * Create a flat file with a large number of key pairs for testing.
65  */
66 static void
67 create_keys (const char *fn)
68 {
69   FILE *f;
70   struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
71
72   if (NULL == (f = fopen (fn, "w+")))
73   {
74     fprintf (stderr,
75              _("Failed to open `%s': %s\n"),
76              fn,
77              STRERROR (errno));
78     return;
79   }
80   fprintf (stderr,
81            _("Generating %u keys, please wait"),
82            make_keys);
83   while (0 < make_keys--)
84   {
85     fprintf (stderr,
86              ".");
87     if (NULL == (pk = GNUNET_CRYPTO_eddsa_key_create ()))
88     {
89        GNUNET_break (0);
90        break;
91     }
92     if (GNUNET_TESTING_HOSTKEYFILESIZE !=
93         fwrite (pk, 1,
94                 GNUNET_TESTING_HOSTKEYFILESIZE, f))
95     {
96       fprintf (stderr,
97                _("\nFailed to write to `%s': %s\n"),
98                fn,
99                STRERROR (errno));
100       GNUNET_free (pk);
101       break;
102     }
103     GNUNET_free (pk);
104   }
105   if (UINT_MAX == make_keys)
106     fprintf (stderr,
107              _("\nFinished!\n"));
108   else
109     fprintf (stderr,
110              _("\nError, %u keys not generated\n"), make_keys);
111   fclose (f);
112 }
113
114
115 static void
116 print_hex (char *msg, void *buf, size_t size)
117 {
118   size_t i;
119   printf ("%s: ", msg);
120   for (i = 0; i < size; i++)
121   {
122     printf ("%02hhx", ((char *)buf)[i]);
123   }
124   printf ("\n");
125 }
126
127
128 static void
129 print_examples_ecdh ()
130 {
131   struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv1;
132   struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub1;
133   struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv2;
134   struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub2;
135   struct GNUNET_HashCode hash;
136   char buf[128];
137
138   dh_pub1 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey);
139   dh_priv1 = GNUNET_CRYPTO_ecdhe_key_create ();
140   dh_pub2 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey);
141   dh_priv2 = GNUNET_CRYPTO_ecdhe_key_create ();
142   GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv1, dh_pub1);
143   GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv2, dh_pub2);
144
145   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_priv1, 32, buf, 128));
146   printf ("ECDHE key 1:\n");
147   printf ("private: %s\n", buf);
148   print_hex ("private(hex)", dh_priv1, sizeof *dh_priv1);
149   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub1, 32, buf, 128));
150   printf ("public: %s\n", buf);
151   print_hex ("public(hex)", dh_pub1, sizeof *dh_pub1);
152
153   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_priv2, 32, buf, 128));
154   printf ("ECDHE key 2:\n");
155   printf ("private: %s\n", buf);
156   print_hex ("private(hex)", dh_priv2, sizeof *dh_priv2);
157   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub2, 32, buf, 128));
158   printf ("public: %s\n", buf);
159   print_hex ("public(hex)", dh_pub2, sizeof *dh_pub2);
160
161   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_ecc_ecdh (dh_priv1, dh_pub2, &hash));
162   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (&hash, 64, buf, 128));
163   printf ("ECDH shared secret: %s\n", buf);
164
165   GNUNET_free (dh_priv1);
166   GNUNET_free (dh_priv2);
167   GNUNET_free (dh_pub1);
168   GNUNET_free (dh_pub2);
169 }
170
171
172 /**
173  * Print some random example operations to stdout.
174  */
175 static void
176 print_examples ()
177 {
178   print_examples_ecdh ();
179   // print_examples_ecdsa ();
180   // print_examples_eddsa ();
181 }
182
183
184 static void
185 print_key (const char *filename)
186 {
187   struct GNUNET_DISK_FileHandle *fd;
188   struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
189   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
190   char *hostkeys_data;
191   char *hostkey_str;
192   uint64_t fs;
193   unsigned int total_hostkeys;
194   unsigned int c;
195
196   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
197   {
198     fprintf (stderr,
199              _("Hostkeys file `%s' not found\n"),
200              filename);
201     return;
202   }
203
204   /* Check hostkey file size, read entire thing into memory */
205   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
206     fs = 0;
207   if (0 == fs)
208   {
209     fprintf (stderr,
210              _("Hostkeys file `%s' is empty\n"),
211              filename);
212     return;       /* File is empty */
213   }
214   if (0 != (fs % GNUNET_TESTING_HOSTKEYFILESIZE))
215   {
216     fprintf (stderr,
217              _("Incorrect hostkey file format: %s\n"),
218              filename);
219     return;
220   }
221   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
222                                          GNUNET_DISK_PERM_NONE);
223   if (NULL == fd)
224   {
225     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", filename);
226     return;
227   }
228   hostkeys_data = GNUNET_malloc (fs);
229   if (fs != GNUNET_DISK_file_read (fd, hostkeys_data, fs))
230   {
231     fprintf (stderr,
232              _("Could not read hostkey file: %s\n"),
233              filename);
234     GNUNET_free (hostkeys_data);
235     GNUNET_DISK_file_close (fd);
236     return;
237   }
238   GNUNET_DISK_file_close (fd);
239
240   if (NULL == hostkeys_data)
241     return;
242   total_hostkeys = fs / GNUNET_TESTING_HOSTKEYFILESIZE;
243   for (c = 0; (c < total_hostkeys) && (c < list_keys_count); c++)
244   {
245     memcpy (&private_key,
246             hostkeys_data + (c * GNUNET_TESTING_HOSTKEYFILESIZE),
247             GNUNET_TESTING_HOSTKEYFILESIZE);
248     GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &public_key);
249     hostkey_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&public_key);
250     if (NULL != hostkey_str)
251     {
252       fprintf (stderr, "%4u: %s\n", c, hostkey_str);
253       GNUNET_free (hostkey_str);
254     }
255     else
256       fprintf (stderr, "%4u: %s\n", c, "invalid");
257   }
258   GNUNET_free (hostkeys_data);
259 }
260
261
262 /**
263  * Main function that will be run by the scheduler.
264  *
265  * @param cls closure
266  * @param args remaining command-line arguments
267  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
268  * @param cfg configuration
269  */
270 static void
271 run (void *cls, char *const *args, const char *cfgfile,
272      const struct GNUNET_CONFIGURATION_Handle *cfg)
273 {
274   if (print_examples_flag)
275   {
276     print_examples ();
277     return;
278   }
279   if (NULL == args[0])
280   {
281     FPRINTF (stderr,
282              "%s",
283              _("No hostkey file specified on command line\n"));
284     return;
285   }
286   if (list_keys)
287   {
288     print_key (args[0]);
289     return;
290   }
291   if (make_keys > 0)
292   {
293     create_keys (args[0]);
294     return;
295   }
296   if (print_public_key)
297   {
298     struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
299     struct GNUNET_CRYPTO_EddsaPublicKey pub;
300     char *s;
301
302     pk = GNUNET_CRYPTO_eddsa_key_create_from_file (args[0]);
303     if (NULL == pk)
304       return;
305     GNUNET_CRYPTO_eddsa_key_get_public (pk, &pub);
306     s = GNUNET_CRYPTO_eddsa_public_key_to_string (&pub);
307     FPRINTF (stdout,
308              "%s\n",
309              s);
310     GNUNET_free (s);
311     GNUNET_free (pk);
312   }
313   if (print_peer_identity)
314   {
315     char *str;
316     struct GNUNET_DISK_FileHandle *keyfile;
317     struct GNUNET_CRYPTO_EddsaPrivateKey pk;
318     struct GNUNET_CRYPTO_EddsaPublicKey pub;
319
320     keyfile = GNUNET_DISK_file_open (args[0], GNUNET_DISK_OPEN_READ,
321                                      GNUNET_DISK_PERM_NONE);
322     if (NULL == keyfile)
323       return;
324     while (sizeof (pk) == GNUNET_DISK_file_read (keyfile, &pk, sizeof (pk)))
325     {
326       GNUNET_CRYPTO_eddsa_key_get_public (&pk, &pub);
327       str = GNUNET_CRYPTO_eddsa_public_key_to_string (&pub);
328       FPRINTF (stdout, "%s\n", str);
329       GNUNET_free (str);
330     }
331   }
332
333 }
334
335
336 /**
337  * Program to manipulate ECC key files.
338  *
339  * @param argc number of arguments from the command line
340  * @param argv command line arguments
341  * @return 0 ok, 1 on error
342  */
343 int
344 main (int argc, char *const *argv)
345 {
346   list_keys_count = UINT32_MAX;
347   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
348     { 'i', "iterate", "FILE",
349       gettext_noop ("list keys included in a file (for testing)"),
350       0, &GNUNET_GETOPT_set_one, &list_keys },
351     { 'e', "end=", "COUNT",
352       gettext_noop ("number of keys to list included in a file (for testing)"),
353       1, &GNUNET_GETOPT_set_uint, &list_keys_count },
354     { 'g', "generate-keys", "COUNT",
355       gettext_noop ("create COUNT public-private key pairs (for testing)"),
356       1, &GNUNET_GETOPT_set_uint, &make_keys },
357     { 'p', "print-public-key", NULL,
358       gettext_noop ("print the public key in ASCII format"),
359       0, &GNUNET_GETOPT_set_one, &print_public_key },
360     { 'P', "print-peer-identity", NULL,
361       gettext_noop ("print the hash of the public key in ASCII format"),
362       0, &GNUNET_GETOPT_set_one, &print_peer_identity },
363     { 'E', "examples", NULL,
364       gettext_noop ("print examples of ECC operations (used for compatibility testing)"),
365       0, &GNUNET_GETOPT_set_one, &print_examples_flag },
366     GNUNET_GETOPT_OPTION_END
367   };
368   int ret;
369
370   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
371     return 2;
372
373   ret = (GNUNET_OK ==
374          GNUNET_PROGRAM_run (argc, argv, "gnunet-ecc [OPTIONS] keyfile",
375                              gettext_noop ("Manipulate GNUnet private ECC key files"),
376                              options, &run, NULL)) ? 0 : 1;
377   GNUNET_free ((void*) argv);
378   return ret;
379 }
380
381 /* end of gnunet-ecc.c */