fix bit counting mess
[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] where 0 is the leftmost bit
248  *        (bytes in code interpreted big endian)
249  * @return Bit \a bit from hashcode \a code, -1 for invalid index
250  */
251 int
252 GNUNET_CRYPTO_hash_get_bit_ltr (const struct GNUNET_HashCode *code,
253                             unsigned int bit)
254 {
255   GNUNET_assert (bit < 8 * sizeof(struct GNUNET_HashCode));
256   return (((unsigned char *) code)[bit >> 3] & (128 >> (bit & 7))) > 0;
257 }
258
259 /**
260  * Obtain a bit from a hashcode.
261  * @param code the GNUNET_CRYPTO_hash to index bit-wise
262  * @param bit index into the hashcode, [0...511] where 0 is the rightmost bit
263  *        (bytes in code interpreted little endian)
264  * @return Bit \a bit from hashcode \a code, -1 for invalid index
265  */
266 int
267 GNUNET_CRYPTO_hash_get_bit_rtl (const struct GNUNET_HashCode *code,
268                                 unsigned int bit)
269 {
270   GNUNET_assert (bit < 8 * sizeof(struct GNUNET_HashCode));
271   return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
272 }
273
274
275
276 /**
277  * Determine how many low order bits match in two
278  * `struct GNUNET_HashCode`s.  i.e. - 010011 and 011111 share
279  * the first two lowest order bits, and therefore the
280  * return value is two (NOT XOR distance, nor how many
281  * bits match absolutely!).
282  *
283  * @param first the first hashcode
284  * @param second the hashcode to compare first to
285  *
286  * @return the number of bits that match
287  */
288 unsigned int
289 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first,
290                                   const struct GNUNET_HashCode *second)
291 {
292   unsigned int i;
293
294   for (i = 0; i < sizeof(struct GNUNET_HashCode) * 8; i++)
295     if (GNUNET_CRYPTO_hash_get_bit_rtl (first, i) !=
296         GNUNET_CRYPTO_hash_get_bit_rtl (second, i))
297       return i;
298   return sizeof(struct GNUNET_HashCode) * 8;
299 }
300
301
302 /**
303  * Compare function for HashCodes, producing a total ordering
304  * of all hashcodes.
305  *
306  * @param h1 some hash code
307  * @param h2 some hash code
308  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
309  */
310 int
311 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
312                         const struct GNUNET_HashCode *h2)
313 {
314   unsigned int *i1;
315   unsigned int *i2;
316   int i;
317
318   i1 = (unsigned int *) h1;
319   i2 = (unsigned int *) h2;
320   for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
321        i--)
322   {
323     if (i1[i] > i2[i])
324       return 1;
325     if (i1[i] < i2[i])
326       return -1;
327   }
328   return 0;
329 }
330
331
332 /**
333  * Find out which of the two `struct GNUNET_HashCode`s is closer to target
334  * in the XOR metric (Kademlia).
335  *
336  * @param h1 some hash code
337  * @param h2 some hash code
338  * @param target some hash code
339  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
340  */
341 int
342 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
343                            const struct GNUNET_HashCode *h2,
344                            const struct GNUNET_HashCode *target)
345 {
346   int i;
347   unsigned int d1;
348   unsigned int d2;
349
350   for (i = sizeof(struct GNUNET_HashCode) / sizeof(unsigned int) - 1; i >= 0;
351        i--)
352   {
353     d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
354     d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
355     if (d1 > d2)
356       return 1;
357     else if (d1 < d2)
358       return -1;
359   }
360   return 0;
361 }
362
363
364 /**
365  * @brief Derive an authentication key
366  * @param key authentication key
367  * @param rkey root key
368  * @param salt salt
369  * @param salt_len size of the @a salt
370  * @param ... pair of void * & size_t for context chunks, terminated by NULL
371  */
372 void
373 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
374                                const struct
375                                GNUNET_CRYPTO_SymmetricSessionKey *rkey,
376                                const void *salt, size_t salt_len, ...)
377 {
378   va_list argp;
379
380   va_start (argp, salt_len);
381   GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
382   va_end (argp);
383 }
384
385
386 /**
387  * @brief Derive an authentication key
388  * @param key authentication key
389  * @param rkey root key
390  * @param salt salt
391  * @param salt_len size of the @a salt
392  * @param argp pair of void * & size_t for context chunks, terminated by NULL
393  */
394 void
395 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
396                                  const struct
397                                  GNUNET_CRYPTO_SymmetricSessionKey *rkey,
398                                  const void *salt, size_t salt_len,
399                                  va_list argp)
400 {
401   GNUNET_CRYPTO_kdf_v (key->key, sizeof(key->key),
402                        salt, salt_len,
403                        rkey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey),
404                        argp);
405 }
406
407
408 /**
409  * Calculate HMAC of a message (RFC 2104)
410  * TODO: Shouldn' this be the standard hmac function and
411  * the above be renamed?
412  *
413  * @param key secret key
414  * @param key_len secret key length
415  * @param plaintext input plaintext
416  * @param plaintext_len length of @a plaintext
417  * @param hmac where to store the hmac
418  */
419 void
420 GNUNET_CRYPTO_hmac_raw (const void *key, size_t key_len,
421                         const void *plaintext, size_t plaintext_len,
422                         struct GNUNET_HashCode *hmac)
423 {
424   static int once;
425   static gcry_md_hd_t md;
426   const unsigned char *mc;
427
428   if (! once)
429   {
430     once = 1;
431     GNUNET_assert (GPG_ERR_NO_ERROR ==
432                    gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
433   }
434   else
435   {
436     gcry_md_reset (md);
437   }
438   gcry_md_setkey (md, key, key_len);
439   gcry_md_write (md, plaintext, plaintext_len);
440   mc = gcry_md_read (md, GCRY_MD_SHA512);
441   GNUNET_assert (NULL != mc);
442   GNUNET_memcpy (hmac->bits, mc, sizeof(hmac->bits));
443 }
444
445
446 /**
447  * Calculate HMAC of a message (RFC 2104)
448  *
449  * @param key secret key
450  * @param plaintext input plaintext
451  * @param plaintext_len length of @a plaintext
452  * @param hmac where to store the hmac
453  */
454 void
455 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
456                     const void *plaintext, size_t plaintext_len,
457                     struct GNUNET_HashCode *hmac)
458 {
459   GNUNET_CRYPTO_hmac_raw ((void *) key->key, sizeof(key->key),
460                           plaintext, plaintext_len,
461                           hmac);
462 }
463
464
465 /**
466  * Context for cummulative hashing.
467  */
468 struct GNUNET_HashContext
469 {
470   /**
471    * Internal state of the hash function.
472    */
473   gcry_md_hd_t hd;
474 };
475
476
477 /**
478  * Start incremental hashing operation.
479  *
480  * @return context for incremental hash computation
481  */
482 struct GNUNET_HashContext *
483 GNUNET_CRYPTO_hash_context_start ()
484 {
485   struct GNUNET_HashContext *hc;
486
487   BENCHMARK_START (hash_context_start);
488
489   hc = GNUNET_new (struct GNUNET_HashContext);
490   GNUNET_assert (0 ==
491                  gcry_md_open (&hc->hd,
492                                GCRY_MD_SHA512,
493                                0));
494
495   BENCHMARK_END (hash_context_start);
496
497   return hc;
498 }
499
500
501 /**
502  * Add data to be hashed.
503  *
504  * @param hc cummulative hash context
505  * @param buf data to add
506  * @param size number of bytes in @a buf
507  */
508 void
509 GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
510                                  const void *buf,
511                                  size_t size)
512 {
513   BENCHMARK_START (hash_context_read);
514   gcry_md_write (hc->hd, buf, size);
515   BENCHMARK_END (hash_context_read);
516 }
517
518
519 /**
520  * Finish the hash computation.
521  *
522  * @param hc hash context to use
523  * @param r_hash where to write the latest / final hash code
524  */
525 void
526 GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
527                                    struct GNUNET_HashCode *r_hash)
528 {
529   const void *res = gcry_md_read (hc->hd, 0);
530
531   BENCHMARK_START (hash_context_finish);
532
533   GNUNET_assert (NULL != res);
534   if (NULL != r_hash)
535     GNUNET_memcpy (r_hash,
536                    res,
537                    sizeof(struct GNUNET_HashCode));
538   GNUNET_CRYPTO_hash_context_abort (hc);
539   BENCHMARK_END (hash_context_finish);
540 }
541
542
543 /**
544  * Abort hashing, do not bother calculating final result.
545  *
546  * @param hc hash context to destroy
547  */
548 void
549 GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc)
550 {
551   gcry_md_close (hc->hd);
552   GNUNET_free (hc);
553 }
554
555
556 /* end of crypto_hash.c */