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