minor style fix
[oweals/gnunet.git] / src / util / gnunet-ecc.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012, 2013 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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  * Number of characters a Base32-encoded public key requires.
33  */
34 #define KEY_STR_LEN sizeof(struct GNUNET_CRYPTO_EddsaPublicKey)*8/5+1
35
36 /**
37  * Flag for listing public key.
38  */
39 static int list_keys;
40
41 /**
42  * Flag for listing public key.
43  */
44 static unsigned int list_keys_count;
45
46 /**
47  * Flag for printing public key.
48  */
49 static int print_public_key;
50
51 /**
52  * Flag for printing public key in hex.
53  */
54 static int print_public_key_hex;
55
56 /**
57  * Flag for printing the output of random example operations.
58  */
59 static int print_examples_flag;
60
61 /**
62  * Option set to create a bunch of keys at once.
63  */
64 static unsigned int make_keys;
65
66
67 /**
68  * Create a flat file with a large number of key pairs for testing.
69  *
70  * @param fn File name to store the keys.
71  * @param prefix Desired prefix for the public keys, NULL if any key is OK.
72  */
73 static void
74 create_keys (const char *fn, const char *prefix)
75 {
76   FILE *f;
77   struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
78   struct GNUNET_CRYPTO_EddsaPublicKey target_pub;
79   static char vanity[KEY_STR_LEN + 1];
80   size_t len;
81   size_t n;
82   size_t rest;
83   unsigned char mask;
84   unsigned target_byte;
85   char *s;
86
87   if (NULL == (f = fopen (fn, "w+")))
88   {
89     fprintf (stderr, _("Failed to open `%s': %s\n"), fn, STRERROR (errno));
90     return;
91   }
92   if (NULL != prefix)
93   {
94     strncpy (vanity, prefix, KEY_STR_LEN);
95     len = GNUNET_MIN (strlen (prefix), KEY_STR_LEN);
96     n = len * 5 / 8;
97     rest = len * 5 % 8;
98
99     memset (&vanity[len], '0', KEY_STR_LEN - len);
100     vanity[KEY_STR_LEN] = '\0';
101     GNUNET_assert (GNUNET_OK ==
102                    GNUNET_CRYPTO_eddsa_public_key_from_string (vanity,
103                                                                KEY_STR_LEN,
104                                                                &target_pub));
105     if (0 != rest)
106     {
107       /**
108        * Documentation by example:
109        * vanity = "A"
110        * len = 1
111        * n = 5/8 = 0 (bytes)
112        * rest = 5%8 = 5 (bits)
113        * mask = ~(2**(8 - 5) - 1) = ~(2**3 - 1) = ~(8 - 1) = ~b111 = b11111000
114        */
115       mask = ~ ((int)pow (2, 8 - rest) - 1);
116       target_byte = ((unsigned char *) &target_pub)[n] & mask;
117     }
118     else
119     {
120       /* Just so old (debian) versions of GCC calm down with the warnings. */
121       mask = target_byte = 0;
122     }
123     s = GNUNET_CRYPTO_eddsa_public_key_to_string (&target_pub);
124     fprintf (stderr,
125              _("Generating %u keys like %s, please wait"),
126              make_keys,
127              s);
128     GNUNET_free (s);
129     fprintf (stderr,
130              "\nattempt %s [%u, %X]\n",
131              vanity,
132              (unsigned int) n,
133              mask);
134   }
135   else
136   {
137     fprintf (stderr,
138              _("Generating %u keys, please wait"),
139              make_keys);
140     /* Just so old (debian) versions of GCC calm down with the warnings. */
141     n = rest = target_byte = mask = 0;
142   }
143
144   while (0 < make_keys--)
145   {
146     fprintf (stderr, ".");
147     if (NULL == (pk = GNUNET_CRYPTO_eddsa_key_create ()))
148     {
149        GNUNET_break (0);
150        break;
151     }
152     if (NULL != prefix)
153     {
154       struct GNUNET_CRYPTO_EddsaPublicKey newkey;
155
156       GNUNET_CRYPTO_eddsa_key_get_public (pk, &newkey);
157       if (0 != memcmp (&target_pub, &newkey, n))
158       {
159         make_keys++;
160         continue;
161       }
162       if (0 != rest)
163       {
164         unsigned char new_byte;
165
166         new_byte = ((unsigned char *) &newkey)[n] & mask;
167         if (target_byte != new_byte)
168         {
169           make_keys++;
170           continue;
171         }
172       }
173     }
174     if (GNUNET_TESTING_HOSTKEYFILESIZE !=
175         fwrite (pk, 1,
176                 GNUNET_TESTING_HOSTKEYFILESIZE, f))
177     {
178       fprintf (stderr,
179                _("\nFailed to write to `%s': %s\n"),
180                fn,
181                STRERROR (errno));
182       GNUNET_free (pk);
183       break;
184     }
185     GNUNET_free (pk);
186   }
187   if (UINT_MAX == make_keys)
188     fprintf (stderr,
189              _("\nFinished!\n"));
190   else
191     fprintf (stderr,
192              _("\nError, %u keys not generated\n"),
193              make_keys);
194   fclose (f);
195 }
196
197
198 static void
199 print_hex (const char *msg,
200            const void *buf,
201            size_t size)
202 {
203   printf ("%s: ", msg);
204   for (size_t i = 0; i < size; i++)
205   {
206     printf ("%02hhx", ((const uint8_t *)buf)[i]);
207   }
208   printf ("\n");
209 }
210
211
212 static void
213 print_examples_ecdh ()
214 {
215   struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv1;
216   struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub1;
217   struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv2;
218   struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub2;
219   struct GNUNET_HashCode hash;
220   char buf[128];
221
222   dh_pub1 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey);
223   dh_priv1 = GNUNET_CRYPTO_ecdhe_key_create ();
224   dh_pub2 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey);
225   dh_priv2 = GNUNET_CRYPTO_ecdhe_key_create ();
226   GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv1, dh_pub1);
227   GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv2, dh_pub2);
228
229   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_priv1, 32, buf, 128));
230   printf ("ECDHE key 1:\n");
231   printf ("private: %s\n", buf);
232   print_hex ("private(hex)", dh_priv1, sizeof *dh_priv1);
233   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub1, 32, buf, 128));
234   printf ("public: %s\n", buf);
235   print_hex ("public(hex)", dh_pub1, sizeof *dh_pub1);
236
237   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_priv2, 32, buf, 128));
238   printf ("ECDHE key 2:\n");
239   printf ("private: %s\n", buf);
240   print_hex ("private(hex)", dh_priv2, sizeof *dh_priv2);
241   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub2, 32, buf, 128));
242   printf ("public: %s\n", buf);
243   print_hex ("public(hex)", dh_pub2, sizeof *dh_pub2);
244
245   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_ecc_ecdh (dh_priv1, dh_pub2, &hash));
246   GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (&hash, 64, buf, 128));
247   printf ("ECDH shared secret: %s\n", buf);
248
249   GNUNET_free (dh_priv1);
250   GNUNET_free (dh_priv2);
251   GNUNET_free (dh_pub1);
252   GNUNET_free (dh_pub2);
253 }
254
255
256 /**
257  * Print some random example operations to stdout.
258  */
259 static void
260 print_examples ()
261 {
262   print_examples_ecdh ();
263   // print_examples_ecdsa ();
264   // print_examples_eddsa ();
265 }
266
267
268 static void
269 print_key (const char *filename)
270 {
271   struct GNUNET_DISK_FileHandle *fd;
272   struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
273   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
274   char *hostkeys_data;
275   char *hostkey_str;
276   uint64_t fs;
277   unsigned int total_hostkeys;
278   unsigned int c;
279
280   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
281   {
282     fprintf (stderr,
283              _("Hostkeys file `%s' not found\n"),
284              filename);
285     return;
286   }
287
288   /* Check hostkey file size, read entire thing into memory */
289   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
290     fs = 0;
291   if (0 == fs)
292   {
293     fprintf (stderr,
294              _("Hostkeys file `%s' is empty\n"),
295              filename);
296     return;       /* File is empty */
297   }
298   if (0 != (fs % GNUNET_TESTING_HOSTKEYFILESIZE))
299   {
300     fprintf (stderr,
301              _("Incorrect hostkey file format: %s\n"),
302              filename);
303     return;
304   }
305   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
306                                          GNUNET_DISK_PERM_NONE);
307   if (NULL == fd)
308   {
309     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", filename);
310     return;
311   }
312   hostkeys_data = GNUNET_malloc (fs);
313   if (fs != GNUNET_DISK_file_read (fd, hostkeys_data, fs))
314   {
315     fprintf (stderr,
316              _("Could not read hostkey file: %s\n"),
317              filename);
318     GNUNET_free (hostkeys_data);
319     GNUNET_DISK_file_close (fd);
320     return;
321   }
322   GNUNET_DISK_file_close (fd);
323
324   if (NULL == hostkeys_data)
325     return;
326   total_hostkeys = fs / GNUNET_TESTING_HOSTKEYFILESIZE;
327   for (c = 0; (c < total_hostkeys) && (c < list_keys_count); c++)
328   {
329     GNUNET_memcpy (&private_key,
330             hostkeys_data + (c * GNUNET_TESTING_HOSTKEYFILESIZE),
331             GNUNET_TESTING_HOSTKEYFILESIZE);
332     GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &public_key);
333     hostkey_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&public_key);
334     if (NULL != hostkey_str)
335     {
336       fprintf (stderr, "%4u: %s\n", c, hostkey_str);
337       GNUNET_free (hostkey_str);
338     }
339     else
340       fprintf (stderr, "%4u: %s\n", c, "invalid");
341   }
342   GNUNET_free (hostkeys_data);
343 }
344
345
346 /**
347  * Main function that will be run by the scheduler.
348  *
349  * @param cls closure
350  * @param args remaining command-line arguments
351  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
352  * @param cfg configuration
353  */
354 static void
355 run (void *cls, char *const *args, const char *cfgfile,
356      const struct GNUNET_CONFIGURATION_Handle *cfg)
357 {
358   if (print_examples_flag)
359   {
360     print_examples ();
361     return;
362   }
363   if (NULL == args[0])
364   {
365     FPRINTF (stderr,
366              "%s",
367              _("No hostkey file specified on command line\n"));
368     return;
369   }
370   if (list_keys)
371   {
372     print_key (args[0]);
373     return;
374   }
375   if (make_keys > 0)
376   {
377     create_keys (args[0], args[1]);
378     return;
379   }
380   if (print_public_key || print_public_key_hex)
381   {
382     char *str;
383     struct GNUNET_DISK_FileHandle *keyfile;
384     struct GNUNET_CRYPTO_EddsaPrivateKey pk;
385     struct GNUNET_CRYPTO_EddsaPublicKey pub;
386
387     keyfile = GNUNET_DISK_file_open (args[0], GNUNET_DISK_OPEN_READ,
388                                      GNUNET_DISK_PERM_NONE);
389     if (NULL == keyfile)
390       return;
391     while (sizeof (pk) == GNUNET_DISK_file_read (keyfile, &pk, sizeof (pk)))
392     {
393       GNUNET_CRYPTO_eddsa_key_get_public (&pk, &pub);
394       if (print_public_key_hex)
395       {
396         print_hex ("HEX:", &pub, sizeof (pub));
397       }
398       else
399       {
400         str = GNUNET_CRYPTO_eddsa_public_key_to_string (&pub);
401         FPRINTF (stdout, "%s\n", str);
402         GNUNET_free (str);
403       }
404     }
405     GNUNET_DISK_file_close (keyfile);
406   }
407
408 }
409
410
411 /**
412  * Program to manipulate ECC key files.
413  *
414  * @param argc number of arguments from the command line
415  * @param argv command line arguments
416  * @return 0 ok, 1 on error
417  */
418 int
419 main (int argc,
420       char *const *argv)
421 {
422   struct GNUNET_GETOPT_CommandLineOption options[] = {
423     GNUNET_GETOPT_option_flag ('i',
424                                "iterate",
425                                gettext_noop ("list keys included in a file (for testing)"),
426                                &list_keys),
427     GNUNET_GETOPT_option_uint ('e',
428                                "end=",
429                                "COUNT",
430                                gettext_noop ("number of keys to list included in a file (for testing)"),
431                                &list_keys_count),
432     GNUNET_GETOPT_option_uint ('g',
433                                "generate-keys",
434                                "COUNT",
435                                gettext_noop ("create COUNT public-private key pairs (for testing)"),
436                                &make_keys),
437     GNUNET_GETOPT_option_flag ('p',
438                                "print-public-key",
439                                gettext_noop ("print the public key in ASCII format"),
440                                &print_public_key),
441     GNUNET_GETOPT_option_flag ('x',
442                                "print-hex",
443                                gettext_noop ("print the public key in HEX format"),
444                                &print_public_key_hex),
445     GNUNET_GETOPT_option_flag ('E',
446                                "examples",
447                                gettext_noop ("print examples of ECC operations (used for compatibility testing)"),
448                                &print_examples_flag),
449     GNUNET_GETOPT_OPTION_END
450   };
451   int ret;
452
453   list_keys_count = UINT32_MAX;
454   if (GNUNET_OK !=
455       GNUNET_STRINGS_get_utf8_args (argc, argv,
456                                     &argc, &argv))
457     return 2;
458
459   ret = (GNUNET_OK ==
460          GNUNET_PROGRAM_run (argc,
461                              argv,
462                              "gnunet-ecc [OPTIONS] keyfile [VANITY_PREFIX]",
463                              gettext_noop ("Manipulate GNUnet private ECC key files"),
464                              options,
465                              &run,
466                              NULL)) ? 0 : 1;
467   GNUNET_free ((void*) argv);
468   return ret;
469 }
470
471 /* end of gnunet-ecc.c */