adding --enable-taler-wallet configure option to build a reduced version of libgnunet...
[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 /* ***************** binary-ASCII encoding *************** */
53
54
55 /**
56  * Convert GNUNET_CRYPTO_hash to ASCII encoding.  The ASCII encoding is rather
57  * GNUnet specific.  It was chosen such that it only uses characters
58  * in [0-9A-V], can be produced without complex arithmetics and uses a
59  * small number of characters.  The GNUnet encoding uses 103
60  * characters plus a null terminator.
61  *
62  * @param block the hash code
63  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
64  *  safely cast to char*, a '\\0' termination is set).
65  */
66 void
67 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block,
68                            struct GNUNET_CRYPTO_HashAsciiEncoded *result)
69 {
70   char *np;
71
72   np = GNUNET_STRINGS_data_to_string ((const unsigned char *) block,
73                                       sizeof (struct GNUNET_HashCode),
74                                       (char*) result,
75                                       sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
76   GNUNET_assert (NULL != np);
77   *np = '\0';
78 }
79
80
81 /**
82  * Convert ASCII encoding back to hash code.
83  *
84  * @param enc the encoding
85  * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
86  * @param result where to store the hash code
87  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
88  */
89 int
90 GNUNET_CRYPTO_hash_from_string2 (const char *enc,
91                                  size_t enclen,
92                                  struct GNUNET_HashCode *result)
93 {
94   char upper_enc[enclen];
95   char *up_ptr = upper_enc;
96
97   GNUNET_STRINGS_utf8_toupper (enc, up_ptr);
98
99   return GNUNET_STRINGS_string_to_data (upper_enc, enclen,
100                                         (unsigned char*) result,
101                                         sizeof (struct GNUNET_HashCode));
102 }
103
104
105 /**
106  * @ingroup hash
107  *
108  * Compute the distance between 2 hashcodes.  The computation must be
109  * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
110  * somewhat consistent. And of course, the result should be a positive
111  * number.
112  *
113  * @param a some hash code
114  * @param b some hash code
115  * @return a positive number which is a measure for
116  *  hashcode proximity.
117  */
118 unsigned int
119 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a,
120                                  const struct GNUNET_HashCode *b)
121 {
122   unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
123   unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
124
125   return (x1 * x2);
126 }
127
128
129 /**
130  * Create a random hash code.
131  *
132  * @param mode desired quality level
133  * @param result hash code that is randomized
134  */
135 void
136 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
137                                   struct GNUNET_HashCode *result)
138 {
139   int i;
140
141   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--)
142     result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
143 }
144
145
146 /**
147  * compute result(delta) = b - a
148  *
149  * @param a some hash code
150  * @param b some hash code
151  * @param result set to b - a
152  */
153 void
154 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a,
155                                const struct GNUNET_HashCode *b,
156                                struct GNUNET_HashCode *result)
157 {
158   int i;
159
160   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
161     result->bits[i] = b->bits[i] - a->bits[i];
162 }
163
164
165 /**
166  * compute result(b) = a + delta
167  *
168  * @param a some hash code
169  * @param delta some hash code
170  * @param result set to a + delta
171  */
172 void
173 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode * a,
174                         const struct GNUNET_HashCode * delta, struct GNUNET_HashCode * result)
175 {
176   int i;
177
178   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
179     result->bits[i] = delta->bits[i] + a->bits[i];
180 }
181
182
183 /**
184  * compute result = a ^ b
185  *
186  * @param a some hash code
187  * @param b some hash code
188  * @param result set to a ^ b
189  */
190 void
191 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a,
192                         const struct GNUNET_HashCode *b,
193                         struct GNUNET_HashCode *result)
194 {
195   int i;
196
197   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
198     result->bits[i] = a->bits[i] ^ b->bits[i];
199 }
200
201
202 /**
203  * Convert a hashcode into a key.
204  *
205  * @param hc hash code that serves to generate the key
206  * @param skey set to a valid session key
207  * @param iv set to a valid initialization vector
208  */
209 void
210 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode *hc,
211                                struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
212                                struct GNUNET_CRYPTO_SymmetricInitializationVector *iv)
213 {
214   GNUNET_assert (GNUNET_YES ==
215                  GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
216                                     "Hash key derivation", strlen ("Hash key derivation"),
217                                     hc, sizeof (struct GNUNET_HashCode),
218                                     NULL, 0));
219   GNUNET_assert (GNUNET_YES ==
220                  GNUNET_CRYPTO_kdf (iv, sizeof (struct GNUNET_CRYPTO_SymmetricInitializationVector),
221                                     "Initialization vector derivation", strlen ("Initialization vector derivation"),
222                                     hc, sizeof (struct GNUNET_HashCode),
223                                     NULL, 0));
224 }
225
226
227 /**
228  * Obtain a bit from a hashcode.
229  * @param code the GNUNET_CRYPTO_hash to index bit-wise
230  * @param bit index into the hashcode, [0...511]
231  * @return Bit \a bit from hashcode \a code, -1 for invalid index
232  */
233 int
234 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode * code, unsigned int bit)
235 {
236   GNUNET_assert (bit < 8 * sizeof (struct GNUNET_HashCode));
237   return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
238 }
239
240
241 /**
242  * Determine how many low order bits match in two
243  * `struct GNUNET_HashCode`s.  i.e. - 010011 and 011111 share
244  * the first two lowest order bits, and therefore the
245  * return value is two (NOT XOR distance, nor how many
246  * bits match absolutely!).
247  *
248  * @param first the first hashcode
249  * @param second the hashcode to compare first to
250  *
251  * @return the number of bits that match
252  */
253 unsigned int
254 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode * first,
255                                   const struct GNUNET_HashCode * second)
256 {
257   unsigned int i;
258
259   for (i = 0; i < sizeof (struct GNUNET_HashCode) * 8; i++)
260     if (GNUNET_CRYPTO_hash_get_bit (first, i) !=
261         GNUNET_CRYPTO_hash_get_bit (second, i))
262       return i;
263   return sizeof (struct GNUNET_HashCode) * 8;
264 }
265
266
267 /**
268  * Compare function for HashCodes, producing a total ordering
269  * of all hashcodes.
270  *
271  * @param h1 some hash code
272  * @param h2 some hash code
273  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
274  */
275 int
276 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
277                         const struct GNUNET_HashCode *h2)
278 {
279   unsigned int *i1;
280   unsigned int *i2;
281   int i;
282
283   i1 = (unsigned int *) h1;
284   i2 = (unsigned int *) h2;
285   for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
286   {
287     if (i1[i] > i2[i])
288       return 1;
289     if (i1[i] < i2[i])
290       return -1;
291   }
292   return 0;
293 }
294
295
296 /**
297  * Find out which of the two `struct GNUNET_HashCode`s is closer to target
298  * in the XOR metric (Kademlia).
299  *
300  * @param h1 some hash code
301  * @param h2 some hash code
302  * @param target some hash code
303  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
304  */
305 int
306 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
307                            const struct GNUNET_HashCode *h2,
308                            const struct GNUNET_HashCode *target)
309 {
310   int i;
311   unsigned int d1;
312   unsigned int d2;
313
314   for (i = sizeof (struct GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
315   {
316     d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
317     d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
318     if (d1 > d2)
319       return 1;
320     else if (d1 < d2)
321       return -1;
322   }
323   return 0;
324 }
325
326
327 /**
328  * @brief Derive an authentication key
329  * @param key authentication key
330  * @param rkey root key
331  * @param salt salt
332  * @param salt_len size of the @a salt
333  * @param ... pair of void * & size_t for context chunks, terminated by NULL
334  */
335 void
336 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
337                                const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
338                                const void *salt, size_t salt_len, ...)
339 {
340   va_list argp;
341
342   va_start (argp, salt_len);
343   GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
344   va_end (argp);
345 }
346
347
348 /**
349  * @brief Derive an authentication key
350  * @param key authentication key
351  * @param rkey root key
352  * @param salt salt
353  * @param salt_len size of the @a salt
354  * @param argp pair of void * & size_t for context chunks, terminated by NULL
355  */
356 void
357 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
358                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
359                                  const void *salt, size_t salt_len,
360                                  va_list argp)
361 {
362   GNUNET_CRYPTO_kdf_v (key->key, sizeof (key->key),
363                        salt, salt_len,
364                        rkey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
365                        argp);
366 }
367
368
369 /**
370  * Calculate HMAC of a message (RFC 2104)
371  *
372  * @param key secret key
373  * @param plaintext input plaintext
374  * @param plaintext_len length of @a plaintext
375  * @param hmac where to store the hmac
376  */
377 void
378 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
379                     const void *plaintext, size_t plaintext_len,
380                     struct GNUNET_HashCode *hmac)
381 {
382   static int once;
383   static gcry_md_hd_t md;
384   const unsigned char *mc;
385
386   if (! once)
387   {
388     once = 1;
389     GNUNET_assert (GPG_ERR_NO_ERROR ==
390                    gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
391   }
392   else
393   {
394     gcry_md_reset (md);
395   }
396   gcry_md_setkey (md, key->key, sizeof (key->key));
397   gcry_md_write (md, plaintext, plaintext_len);
398   mc = gcry_md_read (md, GCRY_MD_SHA512);
399   GNUNET_assert (NULL != mc);
400   memcpy (hmac->bits, mc, sizeof (hmac->bits));
401 }
402
403
404 /**
405  * Context for cummulative hashing.
406  */
407 struct GNUNET_HashContext
408 {
409   /**
410    * Internal state of the hash function.
411    */
412   gcry_md_hd_t hd;
413 };
414
415
416 /**
417  * Start incremental hashing operation.
418  *
419  * @return context for incremental hash computation
420  */
421 struct GNUNET_HashContext *
422 GNUNET_CRYPTO_hash_context_start ()
423 {
424   struct GNUNET_HashContext *hc;
425
426   hc = GNUNET_new (struct GNUNET_HashContext);
427   GNUNET_assert (0 ==
428                  gcry_md_open (&hc->hd,
429                                GCRY_MD_SHA512,
430                                0));
431   return hc;
432 }
433
434
435 /**
436  * Add data to be hashed.
437  *
438  * @param hc cummulative hash context
439  * @param buf data to add
440  * @param size number of bytes in @a buf
441  */
442 void
443 GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
444                          const void *buf,
445                          size_t size)
446 {
447   gcry_md_write (hc->hd, buf, size);
448 }
449
450
451 /**
452  * Finish the hash computation.
453  *
454  * @param hc hash context to use
455  * @param r_hash where to write the latest / final hash code
456  */
457 void
458 GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
459                            struct GNUNET_HashCode *r_hash)
460 {
461   const void *res = gcry_md_read (hc->hd, 0);
462
463   GNUNET_assert (NULL != res);
464   if (NULL != r_hash)
465     memcpy (r_hash,
466             res,
467             sizeof (struct GNUNET_HashCode));
468   GNUNET_CRYPTO_hash_context_abort (hc);
469 }
470
471
472 /**
473  * Abort hashing, do not bother calculating final result.
474  *
475  * @param hc hash context to destroy
476  */
477 void
478 GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc)
479 {
480   gcry_md_close (hc->hd);
481   GNUNET_free (hc);
482 }
483
484
485 /* end of crypto_hash.c */