benchmark collection awk scripts
[oweals/gnunet.git] / src / util / crypto_hash.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2013 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 */
19 /**
20  * @file util/crypto_hash.c
21  * @brief SHA-512 #GNUNET_CRYPTO_hash() related functions
22  * @author Christian Grothoff
23  */
24 #include "platform.h"
25 #include "gnunet_crypto_lib.h"
26 #include "gnunet_strings_lib.h"
27 #include "benchmark.h"
28 #include <gcrypt.h>
29
30 #define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-hash", __VA_ARGS__)
31
32 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-crypto-hash", syscall, filename)
33
34 /**
35  * Hash block of given size.
36  *
37  * @param block the data to #GNUNET_CRYPTO_hash, length is given as a second argument
38  * @param size the length of the data to #GNUNET_CRYPTO_hash in @a block
39  * @param ret pointer to where to write the hashcode
40  */
41 void
42 GNUNET_CRYPTO_hash (const void *block,
43                     size_t size,
44                     struct GNUNET_HashCode *ret)
45 {
46   BENCHMARK_START (hash);
47   gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
48   BENCHMARK_END (hash);
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  * TODO: Shouldn' this be the standard hmac function and
372  * the above be renamed?
373  *
374  * @param key secret key
375  * @param key_len secret key length
376  * @param plaintext input plaintext
377  * @param plaintext_len length of @a plaintext
378  * @param hmac where to store the hmac
379  */
380 void
381 GNUNET_CRYPTO_hmac_raw (const void *key, size_t key_len,
382                     const void *plaintext, size_t plaintext_len,
383                     struct GNUNET_HashCode *hmac)
384 {
385   static int once;
386   static gcry_md_hd_t md;
387   const unsigned char *mc;
388
389   if (! once)
390   {
391     once = 1;
392     GNUNET_assert (GPG_ERR_NO_ERROR ==
393                    gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
394   }
395   else
396   {
397     gcry_md_reset (md);
398   }
399   gcry_md_setkey (md, key, key_len);
400   gcry_md_write (md, plaintext, plaintext_len);
401   mc = gcry_md_read (md, GCRY_MD_SHA512);
402   GNUNET_assert (NULL != mc);
403   GNUNET_memcpy (hmac->bits, mc, sizeof (hmac->bits));
404 }
405
406
407 /**
408  * Calculate HMAC of a message (RFC 2104)
409  *
410  * @param key secret key
411  * @param plaintext input plaintext
412  * @param plaintext_len length of @a plaintext
413  * @param hmac where to store the hmac
414  */
415 void
416 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
417                     const void *plaintext, size_t plaintext_len,
418                     struct GNUNET_HashCode *hmac)
419 {
420   GNUNET_CRYPTO_hmac_raw ((void*) key->key, sizeof (key->key),
421                           plaintext, plaintext_len,
422                           hmac);
423 }
424
425
426 /**
427  * Context for cummulative hashing.
428  */
429 struct GNUNET_HashContext
430 {
431   /**
432    * Internal state of the hash function.
433    */
434   gcry_md_hd_t hd;
435 };
436
437
438 /**
439  * Start incremental hashing operation.
440  *
441  * @return context for incremental hash computation
442  */
443 struct GNUNET_HashContext *
444 GNUNET_CRYPTO_hash_context_start ()
445 {
446   struct GNUNET_HashContext *hc;
447
448   BENCHMARK_START (hash_context_start);
449
450   hc = GNUNET_new (struct GNUNET_HashContext);
451   GNUNET_assert (0 ==
452                  gcry_md_open (&hc->hd,
453                                GCRY_MD_SHA512,
454                                0));
455
456   BENCHMARK_END (hash_context_start);
457
458   return hc;
459 }
460
461
462 /**
463  * Add data to be hashed.
464  *
465  * @param hc cummulative hash context
466  * @param buf data to add
467  * @param size number of bytes in @a buf
468  */
469 void
470 GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
471                                  const void *buf,
472                                  size_t size)
473 {
474   BENCHMARK_START (hash_context_read);
475   gcry_md_write (hc->hd, buf, size);
476   BENCHMARK_END (hash_context_read);
477 }
478
479
480 /**
481  * Finish the hash computation.
482  *
483  * @param hc hash context to use
484  * @param r_hash where to write the latest / final hash code
485  */
486 void
487 GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
488                            struct GNUNET_HashCode *r_hash)
489 {
490   const void *res = gcry_md_read (hc->hd, 0);
491
492   BENCHMARK_START (hash_context_finish);
493
494   GNUNET_assert (NULL != res);
495   if (NULL != r_hash)
496     GNUNET_memcpy (r_hash,
497             res,
498             sizeof (struct GNUNET_HashCode));
499   GNUNET_CRYPTO_hash_context_abort (hc);
500   BENCHMARK_END (hash_context_finish);
501 }
502
503
504 /**
505  * Abort hashing, do not bother calculating final result.
506  *
507  * @param hc hash context to destroy
508  */
509 void
510 GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc)
511 {
512   gcry_md_close (hc->hd);
513   GNUNET_free (hc);
514 }
515
516
517 /* end of crypto_hash.c */