fix
[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   gcry_md_close (fhc->md);
131   GNUNET_free (fhc);            /* also frees fhc->buffer */
132 }
133
134
135 /**
136  * File hashing task.
137  *
138  * @param cls closure
139  * @param tc context
140  */
141 static void
142 file_hash_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
143 {
144   struct GNUNET_CRYPTO_FileHashContext *fhc = cls;
145   GNUNET_HashCode *res;
146   size_t delta;
147
148   fhc->task = GNUNET_SCHEDULER_NO_TASK;
149   GNUNET_assert (fhc->offset < fhc->fsize);
150   delta = fhc->bsize;
151   if (fhc->fsize - fhc->offset < delta)
152     delta = fhc->fsize - fhc->offset;
153   if (delta != GNUNET_DISK_file_read (fhc->fh, fhc->buffer, delta))
154     {
155       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
156                                 "read", fhc->filename);
157       file_hash_finish (fhc, NULL);
158       return;
159     }
160   gcry_md_write (fhc->md, fhc->buffer, delta);
161   fhc->offset += delta;
162   if (fhc->offset == fhc->fsize)
163     {
164       res = (GNUNET_HashCode *) gcry_md_read (fhc->md, GCRY_MD_SHA512);
165       file_hash_finish (fhc, res);
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   if (GPG_ERR_NO_ERROR != gcry_md_open (&fhc->md, GCRY_MD_SHA512, 0))
204     {
205       GNUNET_break (0);
206       GNUNET_free (fhc);
207       return NULL;
208     }
209   fhc->bsize = blocksize;
210   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fhc->fsize, GNUNET_NO))
211     {
212       GNUNET_free (fhc->filename);
213       GNUNET_free (fhc);
214       return NULL;
215     }
216   fhc->fh = GNUNET_DISK_file_open (filename,
217                                    GNUNET_DISK_OPEN_READ,
218                                    GNUNET_DISK_PERM_NONE);
219   if (!fhc->fh)
220     {
221       GNUNET_free (fhc->filename);
222       GNUNET_free (fhc);
223       return NULL;
224     }
225   fhc->task 
226     = GNUNET_SCHEDULER_add_with_priority (sched, priority, 
227                                           &file_hash_task, fhc);
228   return fhc;
229 }
230
231
232 /**
233  * Cancel a file hashing operation.
234  *
235  * @param fhc operation to cancel (callback must not yet have been invoked)
236  */
237 void
238 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc)
239 {
240   GNUNET_SCHEDULER_cancel (fhc->sched,
241                            fhc->task);
242   GNUNET_free (fhc->filename);
243   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
244   GNUNET_free (fhc);
245 }
246
247
248
249 /* ***************** binary-ASCII encoding *************** */
250
251 static unsigned int
252 getValue__ (unsigned char a)
253 {
254   if ((a >= '0') && (a <= '9'))
255     return a - '0';
256   if ((a >= 'A') && (a <= 'V'))
257     return (a - 'A' + 10);
258   return -1;
259 }
260
261 /**
262  * Convert GNUNET_CRYPTO_hash to ASCII encoding.  The ASCII encoding is rather
263  * GNUnet specific.  It was chosen such that it only uses characters
264  * in [0-9A-V], can be produced without complex arithmetics and uses a
265  * small number of characters.  The GNUnet encoding uses 102
266  * characters plus a null terminator.
267  *
268  * @param block the hash code
269  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
270  *  safely cast to char*, a '\\0' termination is set).
271  */
272 void
273 GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
274                            struct GNUNET_CRYPTO_HashAsciiEncoded *result)
275 {
276   /**
277    * 32 characters for encoding (GNUNET_CRYPTO_hash => 32 characters)
278    */
279   static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
280   unsigned int wpos;
281   unsigned int rpos;
282   unsigned int bits;
283   unsigned int vbit;
284
285   GNUNET_assert (block != NULL);
286   GNUNET_assert (result != NULL);
287   vbit = 0;
288   wpos = 0;
289   rpos = 0;
290   bits = 0;
291   while ((rpos < sizeof (GNUNET_HashCode)) || (vbit > 0))
292     {
293       if ((rpos < sizeof (GNUNET_HashCode)) && (vbit < 5))
294         {
295           bits = (bits << 8) | ((unsigned char *) block)[rpos++];       /* eat 8 more bits */
296           vbit += 8;
297         }
298       if (vbit < 5)
299         {
300           bits <<= (5 - vbit);  /* zero-padding */
301           GNUNET_assert (vbit == 2);    /* padding by 3: 512+3 mod 5 == 0 */
302           vbit = 5;
303         }
304       GNUNET_assert (wpos <
305                      sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
306       result->encoding[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
307       vbit -= 5;
308     }
309   GNUNET_assert (wpos == sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
310   GNUNET_assert (vbit == 0);
311   result->encoding[wpos] = '\0';
312 }
313
314 /**
315  * Convert ASCII encoding back to GNUNET_CRYPTO_hash
316  *
317  * @param enc the encoding
318  * @param result where to store the GNUNET_CRYPTO_hash code
319  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
320  */
321 int
322 GNUNET_CRYPTO_hash_from_string (const char *enc, GNUNET_HashCode * result)
323 {
324   unsigned int rpos;
325   unsigned int wpos;
326   unsigned int bits;
327   unsigned int vbit;
328
329   if (strlen (enc) != sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1)
330     return GNUNET_SYSERR;
331
332   vbit = 2;                     /* padding! */
333   wpos = sizeof (GNUNET_HashCode);
334   rpos = sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1;
335   bits = getValue__ (enc[--rpos]) >> 3;
336   while (wpos > 0)
337     {
338       GNUNET_assert (rpos > 0);
339       bits = (getValue__ (enc[--rpos]) << vbit) | bits;
340       vbit += 5;
341       if (vbit >= 8)
342         {
343           ((unsigned char *) result)[--wpos] = (unsigned char) bits;
344           bits >>= 8;
345           vbit -= 8;
346         }
347     }
348   GNUNET_assert (rpos == 0);
349   GNUNET_assert (vbit == 0);
350   return GNUNET_OK;
351 }
352
353 /**
354  * Compute the distance between 2 hashcodes.  The computation must be
355  * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
356  * somewhat consistent. And of course, the result should be a positive
357  * number.
358  * 
359  * @param a some hash code
360  * @param b some hash code
361  * @return a positive number which is a measure for
362  *  hashcode proximity.
363  */
364 unsigned int
365 GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
366                                  const GNUNET_HashCode * b)
367 {
368   unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
369   unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
370   return (x1 * x2);
371 }
372
373 void
374 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
375                                   GNUNET_HashCode * result)
376 {
377   int i;
378   for (i = (sizeof (GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--)
379     result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
380 }
381
382 void
383 GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
384                                const GNUNET_HashCode * b,
385                                GNUNET_HashCode * result)
386 {
387   int i;
388   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
389        i--)
390     result->bits[i] = b->bits[i] - a->bits[i];
391 }
392
393 void
394 GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
395                         const GNUNET_HashCode * delta,
396                         GNUNET_HashCode * result)
397 {
398   int i;
399   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
400        i--)
401     result->bits[i] = delta->bits[i] + a->bits[i];
402 }
403
404
405 void
406 GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a,
407                         const GNUNET_HashCode * b,
408                         GNUNET_HashCode * result)
409 {
410   int i;
411   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
412        i--)
413     result->bits[i] = a->bits[i] ^ b->bits[i];
414 }
415
416
417 /**
418  * Convert a hashcode into a key.
419  */
420 void
421 GNUNET_CRYPTO_hash_to_aes_key (const GNUNET_HashCode * hc,
422                                struct GNUNET_CRYPTO_AesSessionKey *skey,
423                                struct GNUNET_CRYPTO_AesInitializationVector
424                                *iv)
425 {
426   GNUNET_assert (sizeof (GNUNET_HashCode) >=
427                  GNUNET_CRYPTO_AES_KEY_LENGTH +
428                  sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
429   memcpy (skey, hc, GNUNET_CRYPTO_AES_KEY_LENGTH);
430   skey->crc32 =
431     htonl (GNUNET_CRYPTO_crc32_n (skey, GNUNET_CRYPTO_AES_KEY_LENGTH));
432   memcpy (iv, &((char *) hc)[GNUNET_CRYPTO_AES_KEY_LENGTH],
433           sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
434 }
435
436
437 /**
438  * Obtain a bit from a hashcode.
439  * @param code the GNUNET_CRYPTO_hash to index bit-wise
440  * @param bit index into the hashcode, [0...511]
441  * @return Bit \a bit from hashcode \a code, -1 for invalid index
442  */
443 int
444 GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code, 
445                             unsigned int bit)
446 {
447   GNUNET_assert (bit < 8 * sizeof (GNUNET_HashCode));
448   return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
449 }
450
451 /**
452  * Determine how many low order bits match in two
453  * GNUNET_HashCodes.  i.e. - 010011 and 011111 share
454  * the first two lowest order bits, and therefore the
455  * return value is two (NOT XOR distance, nor how many
456  * bits match absolutely!).
457  *
458  * @param first the first hashcode
459  * @param second the hashcode to compare first to
460  *
461  * @return the number of bits that match
462  */
463 unsigned int 
464 GNUNET_CRYPTO_hash_matching_bits(const GNUNET_HashCode *first,
465                                  const GNUNET_HashCode *second)
466 {
467   unsigned int i;
468
469   for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
470     if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
471       return i;
472   return sizeof (GNUNET_HashCode) * 8;
473 }
474
475
476 /**
477  * Compare function for HashCodes, producing a total ordering
478  * of all hashcodes.
479  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
480  */
481 int
482 GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1,
483                         const GNUNET_HashCode * h2)
484 {
485   unsigned int *i1;
486   unsigned int *i2;
487   int i;
488
489   i1 = (unsigned int *) h1;
490   i2 = (unsigned int *) h2;
491   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
492        i--)
493     {
494       if (i1[i] > i2[i])
495         return 1;
496       if (i1[i] < i2[i])
497         return -1;
498     }
499   return 0;
500 }
501
502
503 /**
504  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
505  * in the XOR metric (Kademlia).
506  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
507  */
508 int
509 GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
510                            const GNUNET_HashCode * h2,
511                            const GNUNET_HashCode * target)
512 {
513   int i;
514   unsigned int d1;
515   unsigned int d2;
516
517   for (i = sizeof (GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
518     {
519       d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
520       d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
521       if (d1 > d2)
522         return 1;
523       else if (d1 < d2)
524         return -1;
525     }
526   return 0;
527 }
528
529
530 /**
531  * @brief Derive an authentication key
532  * @param key authentication key
533  * @param rkey root key
534  * @param salt salt
535  * @param salt_len size of the salt
536  * @param ... pair of void * & size_t for context chunks, terminated by NULL
537  */
538 void
539 GNUNET_CRYPTO_hmac_derive_key(struct GNUNET_CRYPTO_AuthKey *key,
540                               const struct GNUNET_CRYPTO_AesSessionKey *rkey,
541                               const void *salt,
542                               size_t salt_len,
543                               ...)
544 {
545   va_list argp;
546
547   va_start (argp, salt_len);
548   GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
549   va_end (argp);
550 }
551
552
553 /**
554  * @brief Derive an authentication key
555  * @param key authentication key
556  * @param rkey root key
557  * @param salt salt
558  * @param salt_len size of the salt
559  * @param argp pair of void * & size_t for context chunks, terminated by NULL
560  */
561 void
562 GNUNET_CRYPTO_hmac_derive_key_v(struct GNUNET_CRYPTO_AuthKey *key,
563                                 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
564                                 const void *salt,
565                                 size_t salt_len,
566                                 va_list argp)
567 {
568   GNUNET_CRYPTO_kdf_v (key->key,
569                        sizeof(key->key), 
570                        salt, salt_len, 
571                        rkey->key,
572                        sizeof(rkey->key),
573                        argp);
574 }
575
576
577 /**
578  * Calculate HMAC of a message (RFC 2104)
579  *
580  * @param key secret key
581  * @param plaintext input plaintext
582  * @param plaintext_len length of plaintext
583  * @param hmac where to store the hmac
584  */
585 void 
586 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
587                     const void *plaintext,
588                     size_t plaintext_len,
589                     GNUNET_HashCode *hmac)
590 {
591   gcry_md_hd_t md;
592   const unsigned char *mc;
593
594   GNUNET_assert (GPG_ERR_NO_ERROR == gcry_md_open (&md,
595                                                    GCRY_MD_SHA512, 
596                                                    GCRY_MD_FLAG_HMAC));
597   gcry_md_setkey (md, key->key, sizeof(key->key));
598   gcry_md_write (md, plaintext, plaintext_len);
599   mc = gcry_md_read (md, GCRY_MD_SHA512);
600   if (mc != NULL)
601     memcpy (hmac->bits, mc, sizeof(hmac->bits));
602   gcry_md_close (md);
603 }
604
605
606 /* end of crypto_hash.c */