missing check
[oweals/gnunet.git] / src / util / crypto_hash.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-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 /**
23  * @file util/crypto_hash.c
24  * @brief SHA-512 GNUNET_CRYPTO_hash related functions
25  * @author Christian Grothoff
26  */
27
28 #include "platform.h"
29 #include "gnunet_common.h"
30 #include "gnunet_crypto_lib.h"
31 #include "gnunet_disk_lib.h"
32 #include "gnunet_strings_lib.h"
33 #include <gcrypt.h>
34
35 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
36
37 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
38
39 /**
40  * Hash block of given size.
41  *
42  * @param block the data to GNUNET_CRYPTO_hash, length is given as a second argument
43  * @param size the length of the data to GNUNET_CRYPTO_hash
44  * @param ret pointer to where to write the hashcode
45  */
46 void
47 GNUNET_CRYPTO_hash (const void *block, size_t size, struct GNUNET_HashCode * ret)
48 {
49   gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
50 }
51
52
53 /**
54  * Context used when hashing a file.
55  */
56 struct GNUNET_CRYPTO_FileHashContext
57 {
58
59   /**
60    * Function to call upon completion.
61    */
62   GNUNET_CRYPTO_HashCompletedCallback callback;
63
64   /**
65    * Closure for callback.
66    */
67   void *callback_cls;
68
69   /**
70    * IO buffer.
71    */
72   unsigned char *buffer;
73
74   /**
75    * Name of the file we are hashing.
76    */
77   char *filename;
78
79   /**
80    * File descriptor.
81    */
82   struct GNUNET_DISK_FileHandle *fh;
83
84   /**
85    * Cummulated hash.
86    */
87   gcry_md_hd_t md;
88
89   /**
90    * Size of the file.
91    */
92   uint64_t fsize;
93
94   /**
95    * Current offset.
96    */
97   uint64_t offset;
98
99   /**
100    * Current task for hashing.
101    */
102   GNUNET_SCHEDULER_TaskIdentifier task;
103
104   /**
105    * Priority we use.
106    */
107   enum GNUNET_SCHEDULER_Priority priority;
108
109   /**
110    * Blocksize.
111    */
112   size_t bsize;
113
114 };
115
116
117 /**
118  * Report result of hash computation to callback
119  * and free associated resources.
120  */
121 static void
122 file_hash_finish (struct GNUNET_CRYPTO_FileHashContext *fhc,
123                   const struct GNUNET_HashCode * res)
124 {
125   fhc->callback (fhc->callback_cls, res);
126   GNUNET_free (fhc->filename);
127   if (!GNUNET_DISK_handle_invalid (fhc->fh))
128     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
129   gcry_md_close (fhc->md);
130   GNUNET_free (fhc);            /* also frees fhc->buffer */
131 }
132
133
134 /**
135  * File hashing task.
136  *
137  * @param cls closure
138  * @param tc context
139  */
140 static void
141 file_hash_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
142 {
143   struct GNUNET_CRYPTO_FileHashContext *fhc = cls;
144   struct GNUNET_HashCode *res;
145   size_t delta;
146
147   fhc->task = GNUNET_SCHEDULER_NO_TASK;
148   GNUNET_assert (fhc->offset <= fhc->fsize);
149   delta = fhc->bsize;
150   if (fhc->fsize - fhc->offset < delta)
151     delta = fhc->fsize - fhc->offset;
152   if (delta != GNUNET_DISK_file_read (fhc->fh, fhc->buffer, delta))
153   {
154     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "read", fhc->filename);
155     file_hash_finish (fhc, NULL);
156     return;
157   }
158   gcry_md_write (fhc->md, fhc->buffer, delta);
159   fhc->offset += delta;
160   if (fhc->offset == fhc->fsize)
161   {
162     res = (struct GNUNET_HashCode *) gcry_md_read (fhc->md, GCRY_MD_SHA512);
163     file_hash_finish (fhc, res);
164     return;
165   }
166   fhc->task = GNUNET_SCHEDULER_add_with_priority (fhc->priority,
167                                                   &file_hash_task, fhc);
168 }
169
170
171 /**
172  * Compute the hash of an entire file.
173  *
174  * @param priority scheduling priority to use
175  * @param filename name of file to hash
176  * @param blocksize number of bytes to process in one task
177  * @param callback function to call upon completion
178  * @param callback_cls closure for callback
179  * @return NULL on (immediate) errror
180  */
181 struct GNUNET_CRYPTO_FileHashContext *
182 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
183                          const char *filename, size_t blocksize,
184                          GNUNET_CRYPTO_HashCompletedCallback callback,
185                          void *callback_cls)
186 {
187   struct GNUNET_CRYPTO_FileHashContext *fhc;
188
189   GNUNET_assert (blocksize > 0);
190   fhc =
191       GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_FileHashContext) + blocksize);
192   fhc->callback = callback;
193   fhc->callback_cls = callback_cls;
194   fhc->buffer = (unsigned char *) &fhc[1];
195   fhc->filename = GNUNET_strdup (filename);
196   if (GPG_ERR_NO_ERROR != gcry_md_open (&fhc->md, GCRY_MD_SHA512, 0))
197   {
198     GNUNET_break (0);
199     GNUNET_free (fhc);
200     return NULL;
201   }
202   fhc->bsize = blocksize;
203   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fhc->fsize, GNUNET_NO, GNUNET_YES))
204   {
205     GNUNET_free (fhc->filename);
206     GNUNET_free (fhc);
207     return NULL;
208   }
209   fhc->fh =
210       GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
211                              GNUNET_DISK_PERM_NONE);
212   if (!fhc->fh)
213   {
214     GNUNET_free (fhc->filename);
215     GNUNET_free (fhc);
216     return NULL;
217   }
218   fhc->priority = priority;
219   fhc->task =
220       GNUNET_SCHEDULER_add_with_priority (priority, &file_hash_task, fhc);
221   return fhc;
222 }
223
224
225 /**
226  * Cancel a file hashing operation.
227  *
228  * @param fhc operation to cancel (callback must not yet have been invoked)
229  */
230 void
231 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc)
232 {
233   GNUNET_SCHEDULER_cancel (fhc->task);
234   GNUNET_free (fhc->filename);
235   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
236   GNUNET_free (fhc);
237 }
238
239
240 /* ***************** binary-ASCII encoding *************** */
241
242
243 /**
244  * Convert GNUNET_CRYPTO_hash to ASCII encoding.  The ASCII encoding is rather
245  * GNUnet specific.  It was chosen such that it only uses characters
246  * in [0-9A-V], can be produced without complex arithmetics and uses a
247  * small number of characters.  The GNUnet encoding uses 103
248  * characters plus a null terminator.
249  *
250  * @param block the hash code
251  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
252  *  safely cast to char*, a '\\0' termination is set).
253  */
254 void
255 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode * block,
256                            struct GNUNET_CRYPTO_HashAsciiEncoded *result)
257 {
258   char *np;
259
260   np = GNUNET_STRINGS_data_to_string ((const unsigned char *) block,
261                                       sizeof (struct GNUNET_HashCode),
262                                       (char*) result,
263                                       sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
264   GNUNET_assert (NULL != np);
265   *np = '\0';
266 }
267
268
269 /**
270  * Convert ASCII encoding back to hash code.
271  *
272  * @param enc the encoding
273  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
274  * @param result where to store the hash code
275  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
276  */
277 int
278 GNUNET_CRYPTO_hash_from_string2 (const char *enc, size_t enclen,
279                                 struct GNUNET_HashCode * result)
280 {
281   char upper_enc[enclen];
282   char* up_ptr = upper_enc;
283
284   GNUNET_STRINGS_utf8_toupper(enc, &up_ptr);
285
286   return GNUNET_STRINGS_string_to_data (upper_enc, enclen,
287                                         (unsigned char*) result,
288                                         sizeof (struct GNUNET_HashCode));
289 }
290
291
292 /**
293  * Compute the distance between 2 hashcodes.  The computation must be
294  * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
295  * somewhat consistent. And of course, the result should be a positive
296  * number.
297  *
298  * @param a some hash code
299  * @param b some hash code
300  * @return a positive number which is a measure for
301  *  hashcode proximity.
302  */
303 unsigned int
304 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode * a,
305                                  const struct GNUNET_HashCode * b)
306 {
307   unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
308   unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
309
310   return (x1 * x2);
311 }
312
313
314 /**
315  * Create a random hash code.
316  *
317  * @param mode desired quality level
318  * @param result hash code that is randomized
319  */
320 void
321 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
322                                   struct GNUNET_HashCode *result)
323 {
324   int i;
325
326   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--)
327     result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
328 }
329
330
331 /**
332  * compute result(delta) = b - a
333  *
334  * @param a some hash code
335  * @param b some hash code
336  * @param result set to b - a
337  */
338 void
339 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode * a,
340                                const struct GNUNET_HashCode * b,
341                                struct GNUNET_HashCode * result)
342 {
343   int i;
344
345   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
346     result->bits[i] = b->bits[i] - a->bits[i];
347 }
348
349
350 /**
351  * compute result(b) = a + delta
352  *
353  * @param a some hash code
354  * @param delta some hash code
355  * @param result set to a + delta
356  */
357 void
358 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode * a,
359                         const struct GNUNET_HashCode * delta, struct GNUNET_HashCode * result)
360 {
361   int i;
362
363   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
364     result->bits[i] = delta->bits[i] + a->bits[i];
365 }
366
367
368 /**
369  * compute result = a ^ b
370  *
371  * @param a some hash code
372  * @param b some hash code
373  * @param result set to a ^ b
374  */
375 void
376 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode * a, const struct GNUNET_HashCode * b,
377                         struct GNUNET_HashCode * result)
378 {
379   int i;
380
381   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
382     result->bits[i] = a->bits[i] ^ b->bits[i];
383 }
384
385
386 /**
387  * Convert a hashcode into a key.
388  *
389  * @param hc hash code that serves to generate the key
390  * @param skey set to a valid session key
391  * @param iv set to a valid initialization vector
392  */
393 void
394 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode * hc,
395                                struct GNUNET_CRYPTO_AesSessionKey *skey,
396                                struct GNUNET_CRYPTO_AesInitializationVector *iv)
397 {
398   GNUNET_assert (sizeof (struct GNUNET_HashCode) >=
399                  GNUNET_CRYPTO_AES_KEY_LENGTH +
400                  sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
401   memcpy (skey, hc, GNUNET_CRYPTO_AES_KEY_LENGTH);
402   memcpy (iv, &((char *) hc)[GNUNET_CRYPTO_AES_KEY_LENGTH],
403           sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
404 }
405
406
407 /**
408  * Obtain a bit from a hashcode.
409  * @param code the GNUNET_CRYPTO_hash to index bit-wise
410  * @param bit index into the hashcode, [0...511]
411  * @return Bit \a bit from hashcode \a code, -1 for invalid index
412  */
413 int
414 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode * code, unsigned int bit)
415 {
416   GNUNET_assert (bit < 8 * sizeof (struct GNUNET_HashCode));
417   return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
418 }
419
420
421 /**
422  * Determine how many low order bits match in two
423  * struct GNUNET_HashCodes.  i.e. - 010011 and 011111 share
424  * the first two lowest order bits, and therefore the
425  * return value is two (NOT XOR distance, nor how many
426  * bits match absolutely!).
427  *
428  * @param first the first hashcode
429  * @param second the hashcode to compare first to
430  *
431  * @return the number of bits that match
432  */
433 unsigned int
434 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode * first,
435                                   const struct GNUNET_HashCode * second)
436 {
437   unsigned int i;
438
439   for (i = 0; i < sizeof (struct GNUNET_HashCode) * 8; i++)
440     if (GNUNET_CRYPTO_hash_get_bit (first, i) !=
441         GNUNET_CRYPTO_hash_get_bit (second, i))
442       return i;
443   return sizeof (struct GNUNET_HashCode) * 8;
444 }
445
446
447 /**
448  * Compare function for HashCodes, producing a total ordering
449  * of all hashcodes.
450  *
451  * @param h1 some hash code
452  * @param h2 some hash code
453  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
454  */
455 int
456 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode * h1, const struct GNUNET_HashCode * h2)
457 {
458   unsigned int *i1;
459   unsigned int *i2;
460   int i;
461
462   i1 = (unsigned int *) h1;
463   i2 = (unsigned int *) h2;
464   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
465   {
466     if (i1[i] > i2[i])
467       return 1;
468     if (i1[i] < i2[i])
469       return -1;
470   }
471   return 0;
472 }
473
474
475 /**
476  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
477  * in the XOR metric (Kademlia).
478  *
479  * @param h1 some hash code
480  * @param h2 some hash code
481  * @param target some hash code
482  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
483  */
484 int
485 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode * h1,
486                            const struct GNUNET_HashCode * h2,
487                            const struct GNUNET_HashCode * target)
488 {
489   int i;
490   unsigned int d1;
491   unsigned int d2;
492
493   for (i = sizeof (struct GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
494   {
495     d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
496     d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
497     if (d1 > d2)
498       return 1;
499     else if (d1 < d2)
500       return -1;
501   }
502   return 0;
503 }
504
505
506 /**
507  * @brief Derive an authentication key
508  * @param key authentication key
509  * @param rkey root key
510  * @param salt salt
511  * @param salt_len size of the salt
512  * @param ... pair of void * & size_t for context chunks, terminated by NULL
513  */
514 void
515 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
516                                const struct GNUNET_CRYPTO_AesSessionKey *rkey,
517                                const void *salt, size_t salt_len, ...)
518 {
519   va_list argp;
520
521   va_start (argp, salt_len);
522   GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
523   va_end (argp);
524 }
525
526
527 /**
528  * @brief Derive an authentication key
529  * @param key authentication key
530  * @param rkey root key
531  * @param salt salt
532  * @param salt_len size of the salt
533  * @param argp pair of void * & size_t for context chunks, terminated by NULL
534  */
535 void
536 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
537                                  const struct GNUNET_CRYPTO_AesSessionKey *rkey,
538                                  const void *salt, size_t salt_len,
539                                  va_list argp)
540 {
541   GNUNET_CRYPTO_kdf_v (key->key, sizeof (key->key), salt, salt_len, rkey->key,
542                        sizeof (rkey->key), argp);
543 }
544
545
546 /**
547  * Calculate HMAC of a message (RFC 2104)
548  *
549  * @param key secret key
550  * @param plaintext input plaintext
551  * @param plaintext_len length of plaintext
552  * @param hmac where to store the hmac
553  */
554 void
555 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
556                     const void *plaintext, size_t plaintext_len,
557                     struct GNUNET_HashCode * hmac)
558 {
559   gcry_md_hd_t md;
560   const unsigned char *mc;
561
562   GNUNET_assert (GPG_ERR_NO_ERROR ==
563                  gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
564   gcry_md_setkey (md, key->key, sizeof (key->key));
565   gcry_md_write (md, plaintext, plaintext_len);
566   mc = gcry_md_read (md, GCRY_MD_SHA512);
567   if (mc != NULL)
568     memcpy (hmac->bits, mc, sizeof (hmac->bits));
569   gcry_md_close (md);
570 }
571
572
573 /* end of crypto_hash.c */