2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2012 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
20 SHA-512 code by Jean-Luc Cooke <jlcooke@certainkey.com>
22 Copyright (c) Jean-Luc Cooke <jlcooke@certainkey.com>
23 Copyright (c) Andrew McDonald <andrew@mcdonald.org.uk>
24 Copyright (c) 2003 Kyle McMartin <kyle@debian.org>
28 * @file util/crypto_hash.c
29 * @brief SHA-512 GNUNET_CRYPTO_hash related functions
30 * @author Christian Grothoff
34 #include "gnunet_common.h"
35 #include "gnunet_crypto_lib.h"
36 #include "gnunet_disk_lib.h"
37 #include "gnunet_strings_lib.h"
40 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
42 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
45 * Hash block of given size.
47 * @param block the data to GNUNET_CRYPTO_hash, length is given as a second argument
48 * @param size the length of the data to GNUNET_CRYPTO_hash
49 * @param ret pointer to where to write the hashcode
52 GNUNET_CRYPTO_hash (const void *block, size_t size, struct GNUNET_HashCode * ret)
54 gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
59 * Compute short (256-bit) hash of a given block.
61 * @param block the data to GNUNET_CRYPTO_hash, length is given as a second argument
62 * @param size the length of the data to GNUNET_CRYPTO_hash
63 * @param ret pointer to where to write the hashcode
66 GNUNET_CRYPTO_short_hash (const void *block, size_t size,
67 struct GNUNET_CRYPTO_ShortHashCode * ret)
69 gcry_md_hash_buffer (GCRY_MD_SHA256, ret, block, size);
74 * Context used when hashing a file.
76 struct GNUNET_CRYPTO_FileHashContext
80 * Function to call upon completion.
82 GNUNET_CRYPTO_HashCompletedCallback callback;
85 * Closure for callback.
92 unsigned char *buffer;
95 * Name of the file we are hashing.
102 struct GNUNET_DISK_FileHandle *fh;
120 * Current task for hashing.
122 GNUNET_SCHEDULER_TaskIdentifier task;
127 enum GNUNET_SCHEDULER_Priority priority;
138 * Report result of hash computation to callback
139 * and free associated resources.
142 file_hash_finish (struct GNUNET_CRYPTO_FileHashContext *fhc,
143 const struct GNUNET_HashCode * res)
145 fhc->callback (fhc->callback_cls, res);
146 GNUNET_free (fhc->filename);
147 if (!GNUNET_DISK_handle_invalid (fhc->fh))
148 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
149 gcry_md_close (fhc->md);
150 GNUNET_free (fhc); /* also frees fhc->buffer */
161 file_hash_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
163 struct GNUNET_CRYPTO_FileHashContext *fhc = cls;
164 struct GNUNET_HashCode *res;
167 fhc->task = GNUNET_SCHEDULER_NO_TASK;
168 GNUNET_assert (fhc->offset <= fhc->fsize);
170 if (fhc->fsize - fhc->offset < delta)
171 delta = fhc->fsize - fhc->offset;
172 if (delta != GNUNET_DISK_file_read (fhc->fh, fhc->buffer, delta))
174 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "read", fhc->filename);
175 file_hash_finish (fhc, NULL);
178 gcry_md_write (fhc->md, fhc->buffer, delta);
179 fhc->offset += delta;
180 if (fhc->offset == fhc->fsize)
182 res = (struct GNUNET_HashCode *) gcry_md_read (fhc->md, GCRY_MD_SHA512);
183 file_hash_finish (fhc, res);
186 fhc->task = GNUNET_SCHEDULER_add_with_priority (fhc->priority,
187 &file_hash_task, fhc);
192 * Compute the hash of an entire file.
194 * @param priority scheduling priority to use
195 * @param filename name of file to hash
196 * @param blocksize number of bytes to process in one task
197 * @param callback function to call upon completion
198 * @param callback_cls closure for callback
199 * @return NULL on (immediate) errror
201 struct GNUNET_CRYPTO_FileHashContext *
202 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
203 const char *filename, size_t blocksize,
204 GNUNET_CRYPTO_HashCompletedCallback callback,
207 struct GNUNET_CRYPTO_FileHashContext *fhc;
209 GNUNET_assert (blocksize > 0);
211 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_FileHashContext) + blocksize);
212 fhc->callback = callback;
213 fhc->callback_cls = callback_cls;
214 fhc->buffer = (unsigned char *) &fhc[1];
215 fhc->filename = GNUNET_strdup (filename);
216 if (GPG_ERR_NO_ERROR != gcry_md_open (&fhc->md, GCRY_MD_SHA512, 0))
222 fhc->bsize = blocksize;
223 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fhc->fsize, GNUNET_NO, GNUNET_YES))
225 GNUNET_free (fhc->filename);
230 GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
231 GNUNET_DISK_PERM_NONE);
234 GNUNET_free (fhc->filename);
238 fhc->priority = priority;
240 GNUNET_SCHEDULER_add_with_priority (priority, &file_hash_task, fhc);
246 * Cancel a file hashing operation.
248 * @param fhc operation to cancel (callback must not yet have been invoked)
251 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc)
253 GNUNET_SCHEDULER_cancel (fhc->task);
254 GNUNET_free (fhc->filename);
255 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
260 /* ***************** binary-ASCII encoding *************** */
264 * Convert GNUNET_CRYPTO_hash to ASCII encoding. The ASCII encoding is rather
265 * GNUnet specific. It was chosen such that it only uses characters
266 * in [0-9A-V], can be produced without complex arithmetics and uses a
267 * small number of characters. The GNUnet encoding uses 103
268 * characters plus a null terminator.
270 * @param block the hash code
271 * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
272 * safely cast to char*, a '\\0' termination is set).
275 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode * block,
276 struct GNUNET_CRYPTO_HashAsciiEncoded *result)
280 np = GNUNET_STRINGS_data_to_string ((const unsigned char *) block,
281 sizeof (struct GNUNET_HashCode),
283 sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
284 GNUNET_assert (NULL != np);
290 * Convert ASCII encoding back to hash code.
292 * @param enc the encoding
293 * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
294 * @param result where to store the hash code
295 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
298 GNUNET_CRYPTO_hash_from_string2 (const char *enc, size_t enclen,
299 struct GNUNET_HashCode * result)
301 char upper_enc[enclen];
302 char* up_ptr = upper_enc;
304 GNUNET_STRINGS_utf8_toupper(enc, &up_ptr);
306 return GNUNET_STRINGS_string_to_data (upper_enc, enclen,
307 (unsigned char*) result,
308 sizeof (struct GNUNET_HashCode));
313 * Compute the distance between 2 hashcodes. The computation must be
314 * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
315 * somewhat consistent. And of course, the result should be a positive
318 * @param a some hash code
319 * @param b some hash code
320 * @return a positive number which is a measure for
321 * hashcode proximity.
324 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode * a,
325 const struct GNUNET_HashCode * b)
327 unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
328 unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
335 * Create a random hash code.
337 * @param mode desired quality level
338 * @param result hash code that is randomized
341 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
342 struct GNUNET_HashCode *result)
346 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--)
347 result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
352 * compute result(delta) = b - a
354 * @param a some hash code
355 * @param b some hash code
356 * @param result set to b - a
359 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode * a,
360 const struct GNUNET_HashCode * b,
361 struct GNUNET_HashCode * result)
365 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
366 result->bits[i] = b->bits[i] - a->bits[i];
371 * compute result(b) = a + delta
373 * @param a some hash code
374 * @param delta some hash code
375 * @param result set to a + delta
378 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode * a,
379 const struct GNUNET_HashCode * delta, struct GNUNET_HashCode * result)
383 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
384 result->bits[i] = delta->bits[i] + a->bits[i];
389 * compute result = a ^ b
391 * @param a some hash code
392 * @param b some hash code
393 * @param result set to a ^ b
396 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode * a, const struct GNUNET_HashCode * b,
397 struct GNUNET_HashCode * result)
401 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
402 result->bits[i] = a->bits[i] ^ b->bits[i];
407 * Convert a hashcode into a key.
409 * @param hc hash code that serves to generate the key
410 * @param skey set to a valid session key
411 * @param iv set to a valid initialization vector
414 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode * hc,
415 struct GNUNET_CRYPTO_AesSessionKey *skey,
416 struct GNUNET_CRYPTO_AesInitializationVector *iv)
418 GNUNET_assert (sizeof (struct GNUNET_HashCode) >=
419 GNUNET_CRYPTO_AES_KEY_LENGTH +
420 sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
421 memcpy (skey, hc, GNUNET_CRYPTO_AES_KEY_LENGTH);
422 memcpy (iv, &((char *) hc)[GNUNET_CRYPTO_AES_KEY_LENGTH],
423 sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
428 * Obtain a bit from a hashcode.
429 * @param code the GNUNET_CRYPTO_hash to index bit-wise
430 * @param bit index into the hashcode, [0...511]
431 * @return Bit \a bit from hashcode \a code, -1 for invalid index
434 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode * code, unsigned int bit)
436 GNUNET_assert (bit < 8 * sizeof (struct GNUNET_HashCode));
437 return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
442 * Determine how many low order bits match in two
443 * struct GNUNET_HashCodes. i.e. - 010011 and 011111 share
444 * the first two lowest order bits, and therefore the
445 * return value is two (NOT XOR distance, nor how many
446 * bits match absolutely!).
448 * @param first the first hashcode
449 * @param second the hashcode to compare first to
451 * @return the number of bits that match
454 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode * first,
455 const struct GNUNET_HashCode * second)
459 for (i = 0; i < sizeof (struct GNUNET_HashCode) * 8; i++)
460 if (GNUNET_CRYPTO_hash_get_bit (first, i) !=
461 GNUNET_CRYPTO_hash_get_bit (second, i))
463 return sizeof (struct GNUNET_HashCode) * 8;
468 * Compare function for HashCodes, producing a total ordering
471 * @param h1 some hash code
472 * @param h2 some hash code
473 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
476 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode * h1, const struct GNUNET_HashCode * h2)
482 i1 = (unsigned int *) h1;
483 i2 = (unsigned int *) h2;
484 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
496 * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
497 * in the XOR metric (Kademlia).
499 * @param h1 some hash code
500 * @param h2 some hash code
501 * @param target some hash code
502 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
505 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode * h1,
506 const struct GNUNET_HashCode * h2,
507 const struct GNUNET_HashCode * target)
513 for (i = sizeof (struct GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
515 d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
516 d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
527 * @brief Derive an authentication key
528 * @param key authentication key
529 * @param rkey root key
531 * @param salt_len size of the salt
532 * @param ... pair of void * & size_t for context chunks, terminated by NULL
535 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
536 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
537 const void *salt, size_t salt_len, ...)
541 va_start (argp, salt_len);
542 GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
548 * @brief Derive an authentication key
549 * @param key authentication key
550 * @param rkey root key
552 * @param salt_len size of the salt
553 * @param argp pair of void * & size_t for context chunks, terminated by NULL
556 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
557 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
558 const void *salt, size_t salt_len,
561 GNUNET_CRYPTO_kdf_v (key->key, sizeof (key->key), salt, salt_len, rkey->key,
562 sizeof (rkey->key), argp);
567 * Calculate HMAC of a message (RFC 2104)
569 * @param key secret key
570 * @param plaintext input plaintext
571 * @param plaintext_len length of plaintext
572 * @param hmac where to store the hmac
575 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
576 const void *plaintext, size_t plaintext_len,
577 struct GNUNET_HashCode * hmac)
580 const unsigned char *mc;
582 GNUNET_assert (GPG_ERR_NO_ERROR ==
583 gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
584 gcry_md_setkey (md, key->key, sizeof (key->key));
585 gcry_md_write (md, plaintext, plaintext_len);
586 mc = gcry_md_read (md, GCRY_MD_SHA512);
588 memcpy (hmac->bits, mc, sizeof (hmac->bits));
595 * Double short (256-bit) hash to create a long hash.
597 * @param sh short hash to double
598 * @param dh where to store the (doubled) long hash (not really a hash)
601 GNUNET_CRYPTO_short_hash_double (const struct GNUNET_CRYPTO_ShortHashCode *sh,
602 struct GNUNET_HashCode *dh)
607 memcpy (ptr, sh, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
608 memcpy (&ptr[sizeof (struct GNUNET_CRYPTO_ShortHashCode)], sh, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
613 * Truncate doubled short hash back to a short hash.
615 * @param dh doubled short hash to reduce again
616 * @param sh where to store the short hash
617 * @return GNUNET_OK on success, GNUNET_SYSERR if this was not a
621 GNUNET_CRYPTO_short_hash_from_truncation (const struct GNUNET_HashCode *dh,
622 struct GNUNET_CRYPTO_ShortHashCode *sh)
624 const struct GNUNET_CRYPTO_ShortHashCode *s;
626 s = (const struct GNUNET_CRYPTO_ShortHashCode *) dh;
627 if (0 != memcmp (&s[0],
629 sizeof (struct GNUNET_CRYPTO_ShortHashCode)))
630 return GNUNET_SYSERR;
637 * Convert ASCII encoding back to a 'struct GNUNET_CRYPTO_ShortHash'
639 * @param enc the encoding
640 * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
641 * @param result where to store the GNUNET_CRYPTO_hash code
642 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
645 GNUNET_CRYPTO_short_hash_from_string2 (const char *enc, size_t enclen,
646 struct GNUNET_CRYPTO_ShortHashCode * result)
649 char upper_enc[enclen];
650 char* up_ptr = upper_enc;
652 GNUNET_STRINGS_utf8_toupper(enc, &up_ptr);
653 return GNUNET_STRINGS_string_to_data (upper_enc, enclen,
654 (unsigned char*) result,
655 sizeof (struct GNUNET_CRYPTO_ShortHashCode));
660 * Convert short hash to ASCII encoding.
662 * @param block the hash code
663 * @param result where to store the encoding (struct GNUNET_CRYPTO_ShortHashAsciiEncoded can be
664 * safely cast to char*, a '\\0' termination is set).
667 GNUNET_CRYPTO_short_hash_to_enc (const struct GNUNET_CRYPTO_ShortHashCode * block,
668 struct GNUNET_CRYPTO_ShortHashAsciiEncoded *result)
672 np = GNUNET_STRINGS_data_to_string ((const unsigned char *) block,
673 sizeof (struct GNUNET_CRYPTO_ShortHashCode),
675 sizeof (struct GNUNET_CRYPTO_ShortHashAsciiEncoded) - 1);
676 GNUNET_assert (NULL != np);
681 * Compare function for ShortHashCodes, producing a total ordering
684 * @param h1 some hash code
685 * @param h2 some hash code
686 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
689 GNUNET_CRYPTO_short_hash_cmp (const struct GNUNET_CRYPTO_ShortHashCode * h1,
690 const struct GNUNET_CRYPTO_ShortHashCode * h2)
696 i1 = (unsigned int *) h1;
697 i2 = (unsigned int *) h2;
698 for (i = (sizeof (struct GNUNET_CRYPTO_ShortHashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
708 /* end of crypto_hash.c */