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