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