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