2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009 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"
39 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
41 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
44 * Hash block of given size.
46 * @param block the data to GNUNET_CRYPTO_hash, length is given as a second argument
47 * @param size the length of the data to GNUNET_CRYPTO_hash
48 * @param ret pointer to where to write the hashcode
51 GNUNET_CRYPTO_hash (const void *block, size_t size, GNUNET_HashCode * ret)
53 gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
58 * Context used when hashing a file.
60 struct GNUNET_CRYPTO_FileHashContext
64 * Function to call upon completion.
66 GNUNET_CRYPTO_HashCompletedCallback callback;
69 * Closure for callback.
76 unsigned char *buffer;
79 * Name of the file we are hashing.
86 struct GNUNET_DISK_FileHandle *fh;
104 * Current task for hashing.
106 GNUNET_SCHEDULER_TaskIdentifier task;
111 enum GNUNET_SCHEDULER_Priority priority;
122 * Report result of hash computation to callback
123 * and free associated resources.
126 file_hash_finish (struct GNUNET_CRYPTO_FileHashContext *fhc,
127 const GNUNET_HashCode * res)
129 fhc->callback (fhc->callback_cls, res);
130 GNUNET_free (fhc->filename);
131 if (!GNUNET_DISK_handle_invalid (fhc->fh))
132 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
133 gcry_md_close (fhc->md);
134 GNUNET_free (fhc); /* also frees fhc->buffer */
145 file_hash_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
147 struct GNUNET_CRYPTO_FileHashContext *fhc = cls;
148 GNUNET_HashCode *res;
151 fhc->task = GNUNET_SCHEDULER_NO_TASK;
152 GNUNET_assert (fhc->offset <= fhc->fsize);
154 if (fhc->fsize - fhc->offset < delta)
155 delta = fhc->fsize - fhc->offset;
156 if (delta != GNUNET_DISK_file_read (fhc->fh, fhc->buffer, delta))
158 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "read", fhc->filename);
159 file_hash_finish (fhc, NULL);
162 gcry_md_write (fhc->md, fhc->buffer, delta);
163 fhc->offset += delta;
164 if (fhc->offset == fhc->fsize)
166 res = (GNUNET_HashCode *) gcry_md_read (fhc->md, GCRY_MD_SHA512);
167 file_hash_finish (fhc, res);
170 fhc->task = GNUNET_SCHEDULER_add_with_priority (fhc->priority,
171 &file_hash_task, fhc);
176 * Compute the hash of an entire file.
178 * @param priority scheduling priority to use
179 * @param filename name of file to hash
180 * @param blocksize number of bytes to process in one task
181 * @param callback function to call upon completion
182 * @param callback_cls closure for callback
183 * @return NULL on (immediate) errror
185 struct GNUNET_CRYPTO_FileHashContext *
186 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
187 const char *filename, size_t blocksize,
188 GNUNET_CRYPTO_HashCompletedCallback callback,
191 struct GNUNET_CRYPTO_FileHashContext *fhc;
193 GNUNET_assert (blocksize > 0);
195 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_FileHashContext) + blocksize);
196 fhc->callback = callback;
197 fhc->callback_cls = callback_cls;
198 fhc->buffer = (unsigned char *) &fhc[1];
199 fhc->filename = GNUNET_strdup (filename);
200 if (GPG_ERR_NO_ERROR != gcry_md_open (&fhc->md, GCRY_MD_SHA512, 0))
206 fhc->bsize = blocksize;
207 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fhc->fsize, GNUNET_NO))
209 GNUNET_free (fhc->filename);
214 GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
215 GNUNET_DISK_PERM_NONE);
218 GNUNET_free (fhc->filename);
222 fhc->priority = priority;
224 GNUNET_SCHEDULER_add_with_priority (priority, &file_hash_task, fhc);
230 * Cancel a file hashing operation.
232 * @param fhc operation to cancel (callback must not yet have been invoked)
235 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc)
237 GNUNET_SCHEDULER_cancel (fhc->task);
238 GNUNET_free (fhc->filename);
239 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
244 /* ***************** binary-ASCII encoding *************** */
246 /* FIXME: should use GNUNET_STRINGS_data_to_string and strings_to_data below!!! */
249 * Get the numeric value corresponding to a character.
251 * @param a a character
252 * @return corresponding numeric value
255 getValue__ (unsigned char a)
257 if ((a >= '0') && (a <= '9'))
259 if ((a >= 'A') && (a <= 'V'))
260 return (a - 'A' + 10);
266 * Convert GNUNET_CRYPTO_hash to ASCII encoding. The ASCII encoding is rather
267 * GNUnet specific. It was chosen such that it only uses characters
268 * in [0-9A-V], can be produced without complex arithmetics and uses a
269 * small number of characters. The GNUnet encoding uses 103
270 * characters plus a null terminator.
272 * @param block the hash code
273 * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
274 * safely cast to char*, a '\\0' termination is set).
277 GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
278 struct GNUNET_CRYPTO_HashAsciiEncoded *result)
281 * 32 characters for encoding (GNUNET_CRYPTO_hash => 32 characters)
283 static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
289 GNUNET_assert (block != NULL);
290 GNUNET_assert (result != NULL);
295 while ((rpos < sizeof (GNUNET_HashCode)) || (vbit > 0))
297 if ((rpos < sizeof (GNUNET_HashCode)) && (vbit < 5))
299 bits = (bits << 8) | ((unsigned char *) block)[rpos++]; /* eat 8 more bits */
304 bits <<= (5 - vbit); /* zero-padding */
305 GNUNET_assert (vbit == 2); /* padding by 3: 512+3 mod 5 == 0 */
308 GNUNET_assert (wpos < sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
309 result->encoding[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
312 GNUNET_assert (wpos == sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
313 GNUNET_assert (vbit == 0);
314 result->encoding[wpos] = '\0';
319 * Convert ASCII encoding back to GNUNET_CRYPTO_hash
321 * @param enc the encoding
322 * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
323 * @param result where to store the GNUNET_CRYPTO_hash code
324 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
327 GNUNET_CRYPTO_hash_from_string2 (const char *enc, size_t enclen,
328 GNUNET_HashCode * result)
336 if (enclen != sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1)
337 return GNUNET_SYSERR;
339 vbit = 2; /* padding! */
340 wpos = sizeof (GNUNET_HashCode);
341 rpos = sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1;
342 bits = (ret = getValue__ (enc[--rpos])) >> 3;
344 return GNUNET_SYSERR;
347 GNUNET_assert (rpos > 0);
348 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits;
350 return GNUNET_SYSERR;
354 ((unsigned char *) result)[--wpos] = (unsigned char) bits;
359 GNUNET_assert (rpos == 0);
360 GNUNET_assert (vbit == 0);
366 * Compute the distance between 2 hashcodes. The computation must be
367 * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
368 * somewhat consistent. And of course, the result should be a positive
371 * @param a some hash code
372 * @param b some hash code
373 * @return a positive number which is a measure for
374 * hashcode proximity.
377 GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
378 const GNUNET_HashCode * b)
380 unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
381 unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
388 * Create a random hash code.
390 * @param mode desired quality level
391 * @param result hash code that is randomized
394 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
395 GNUNET_HashCode * result)
399 for (i = (sizeof (GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--)
400 result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
405 * compute result(delta) = b - a
407 * @param a some hash code
408 * @param b some hash code
409 * @param result set to b - a
412 GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
413 const GNUNET_HashCode * b,
414 GNUNET_HashCode * result)
418 for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
419 result->bits[i] = b->bits[i] - a->bits[i];
424 * compute result(b) = a + delta
426 * @param a some hash code
427 * @param delta some hash code
428 * @param result set to a + delta
431 GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
432 const GNUNET_HashCode * delta, GNUNET_HashCode * result)
436 for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
437 result->bits[i] = delta->bits[i] + a->bits[i];
442 * compute result = a ^ b
444 * @param a some hash code
445 * @param b some hash code
446 * @param result set to a ^ b
449 GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a, const GNUNET_HashCode * b,
450 GNUNET_HashCode * result)
454 for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
455 result->bits[i] = a->bits[i] ^ b->bits[i];
460 * Convert a hashcode into a key.
462 * @param hc hash code that serves to generate the key
463 * @param skey set to a valid session key
464 * @param iv set to a valid initialization vector
467 GNUNET_CRYPTO_hash_to_aes_key (const GNUNET_HashCode * hc,
468 struct GNUNET_CRYPTO_AesSessionKey *skey,
469 struct GNUNET_CRYPTO_AesInitializationVector *iv)
471 GNUNET_assert (sizeof (GNUNET_HashCode) >=
472 GNUNET_CRYPTO_AES_KEY_LENGTH +
473 sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
474 memcpy (skey, hc, GNUNET_CRYPTO_AES_KEY_LENGTH);
476 htonl (GNUNET_CRYPTO_crc32_n (skey, GNUNET_CRYPTO_AES_KEY_LENGTH));
477 memcpy (iv, &((char *) hc)[GNUNET_CRYPTO_AES_KEY_LENGTH],
478 sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
483 * Obtain a bit from a hashcode.
484 * @param code the GNUNET_CRYPTO_hash to index bit-wise
485 * @param bit index into the hashcode, [0...511]
486 * @return Bit \a bit from hashcode \a code, -1 for invalid index
489 GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code, unsigned int bit)
491 GNUNET_assert (bit < 8 * sizeof (GNUNET_HashCode));
492 return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
497 * Determine how many low order bits match in two
498 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
499 * the first two lowest order bits, and therefore the
500 * return value is two (NOT XOR distance, nor how many
501 * bits match absolutely!).
503 * @param first the first hashcode
504 * @param second the hashcode to compare first to
506 * @return the number of bits that match
509 GNUNET_CRYPTO_hash_matching_bits (const GNUNET_HashCode * first,
510 const GNUNET_HashCode * second)
514 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
515 if (GNUNET_CRYPTO_hash_get_bit (first, i) !=
516 GNUNET_CRYPTO_hash_get_bit (second, i))
518 return sizeof (GNUNET_HashCode) * 8;
523 * Compare function for HashCodes, producing a total ordering
526 * @param h1 some hash code
527 * @param h2 some hash code
528 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
531 GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1, const GNUNET_HashCode * h2)
537 i1 = (unsigned int *) h1;
538 i2 = (unsigned int *) h2;
539 for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
551 * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
552 * in the XOR metric (Kademlia).
554 * @param h1 some hash code
555 * @param h2 some hash code
556 * @param target some hash code
557 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
560 GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
561 const GNUNET_HashCode * h2,
562 const GNUNET_HashCode * target)
568 for (i = sizeof (GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
570 d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
571 d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
582 * @brief Derive an authentication key
583 * @param key authentication key
584 * @param rkey root key
586 * @param salt_len size of the salt
587 * @param ... pair of void * & size_t for context chunks, terminated by NULL
590 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
591 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
592 const void *salt, size_t salt_len, ...)
596 va_start (argp, salt_len);
597 GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
603 * @brief Derive an authentication key
604 * @param key authentication key
605 * @param rkey root key
607 * @param salt_len size of the salt
608 * @param argp pair of void * & size_t for context chunks, terminated by NULL
611 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
612 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
613 const void *salt, size_t salt_len,
616 GNUNET_CRYPTO_kdf_v (key->key, sizeof (key->key), salt, salt_len, rkey->key,
617 sizeof (rkey->key), argp);
622 * Calculate HMAC of a message (RFC 2104)
624 * @param key secret key
625 * @param plaintext input plaintext
626 * @param plaintext_len length of plaintext
627 * @param hmac where to store the hmac
630 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
631 const void *plaintext, size_t plaintext_len,
632 GNUNET_HashCode * hmac)
635 const unsigned char *mc;
637 GNUNET_assert (GPG_ERR_NO_ERROR ==
638 gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
639 gcry_md_setkey (md, key->key, sizeof (key->key));
640 gcry_md_write (md, plaintext, plaintext_len);
641 mc = gcry_md_read (md, GCRY_MD_SHA512);
643 memcpy (hmac->bits, mc, sizeof (hmac->bits));
648 /* end of crypto_hash.c */