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