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