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