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