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"
41 * Hash block of given size.
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
45 * @param ret pointer to where to write the hashcode
48 GNUNET_CRYPTO_hash (const void *block, size_t size, GNUNET_HashCode * ret)
50 gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
55 * Context used when hashing a file.
57 struct GNUNET_CRYPTO_FileHashContext
61 * Function to call upon completion.
63 GNUNET_CRYPTO_HashCompletedCallback callback;
66 * Closure for callback.
73 unsigned char *buffer;
76 * Name of the file we are hashing.
83 struct GNUNET_DISK_FileHandle *fh;
101 * Current task for hashing.
103 GNUNET_SCHEDULER_TaskIdentifier task;
114 * Report result of hash computation to callback
115 * and free associated resources.
118 file_hash_finish (struct GNUNET_CRYPTO_FileHashContext *fhc,
119 const GNUNET_HashCode * res)
121 fhc->callback (fhc->callback_cls, res);
122 GNUNET_free (fhc->filename);
123 if (!GNUNET_DISK_handle_invalid (fhc->fh))
124 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
125 gcry_md_close (fhc->md);
126 GNUNET_free (fhc); /* also frees fhc->buffer */
137 file_hash_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
139 struct GNUNET_CRYPTO_FileHashContext *fhc = cls;
140 GNUNET_HashCode *res;
143 fhc->task = GNUNET_SCHEDULER_NO_TASK;
144 GNUNET_assert (fhc->offset <= fhc->fsize);
146 if (fhc->fsize - fhc->offset < delta)
147 delta = fhc->fsize - fhc->offset;
148 if (delta != GNUNET_DISK_file_read (fhc->fh, fhc->buffer, delta))
150 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
151 "read", fhc->filename);
152 file_hash_finish (fhc, NULL);
155 gcry_md_write (fhc->md, fhc->buffer, delta);
156 fhc->offset += delta;
157 if (fhc->offset == fhc->fsize)
159 res = (GNUNET_HashCode *) gcry_md_read (fhc->md, GCRY_MD_SHA512);
160 file_hash_finish (fhc, res);
164 = GNUNET_SCHEDULER_add_now (&file_hash_task, fhc);
169 * Compute the hash of an entire file.
171 * @param priority scheduling priority to use
172 * @param filename name of file to hash
173 * @param blocksize number of bytes to process in one task
174 * @param callback function to call upon completion
175 * @param callback_cls closure for callback
176 * @return NULL on (immediate) errror
178 struct GNUNET_CRYPTO_FileHashContext *
179 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
180 const char *filename,
182 GNUNET_CRYPTO_HashCompletedCallback callback,
185 struct GNUNET_CRYPTO_FileHashContext *fhc;
187 GNUNET_assert (blocksize > 0);
188 fhc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_FileHashContext) + blocksize);
189 fhc->callback = callback;
190 fhc->callback_cls = callback_cls;
191 fhc->buffer = (unsigned char *) &fhc[1];
192 fhc->filename = GNUNET_strdup (filename);
193 if (GPG_ERR_NO_ERROR != gcry_md_open (&fhc->md, GCRY_MD_SHA512, 0))
199 fhc->bsize = blocksize;
200 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fhc->fsize, GNUNET_NO))
202 GNUNET_free (fhc->filename);
206 fhc->fh = GNUNET_DISK_file_open (filename,
207 GNUNET_DISK_OPEN_READ,
208 GNUNET_DISK_PERM_NONE);
211 GNUNET_free (fhc->filename);
216 = GNUNET_SCHEDULER_add_with_priority (priority,
217 &file_hash_task, fhc);
223 * Cancel a file hashing operation.
225 * @param fhc operation to cancel (callback must not yet have been invoked)
228 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc)
230 GNUNET_SCHEDULER_cancel (fhc->task);
231 GNUNET_free (fhc->filename);
232 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh));
238 /* ***************** binary-ASCII encoding *************** */
241 getValue__ (unsigned char a)
243 if ((a >= '0') && (a <= '9'))
245 if ((a >= 'A') && (a <= 'V'))
246 return (a - 'A' + 10);
251 * Convert GNUNET_CRYPTO_hash to ASCII encoding. The ASCII encoding is rather
252 * GNUnet specific. It was chosen such that it only uses characters
253 * in [0-9A-V], can be produced without complex arithmetics and uses a
254 * small number of characters. The GNUnet encoding uses 103
255 * characters plus a null terminator.
257 * @param block the hash code
258 * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
259 * safely cast to char*, a '\\0' termination is set).
262 GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
263 struct GNUNET_CRYPTO_HashAsciiEncoded *result)
266 * 32 characters for encoding (GNUNET_CRYPTO_hash => 32 characters)
268 static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
274 GNUNET_assert (block != NULL);
275 GNUNET_assert (result != NULL);
280 while ((rpos < sizeof (GNUNET_HashCode)) || (vbit > 0))
282 if ((rpos < sizeof (GNUNET_HashCode)) && (vbit < 5))
284 bits = (bits << 8) | ((unsigned char *) block)[rpos++]; /* eat 8 more bits */
289 bits <<= (5 - vbit); /* zero-padding */
290 GNUNET_assert (vbit == 2); /* padding by 3: 512+3 mod 5 == 0 */
293 GNUNET_assert (wpos <
294 sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
295 result->encoding[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
298 GNUNET_assert (wpos == sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
299 GNUNET_assert (vbit == 0);
300 result->encoding[wpos] = '\0';
304 * Convert ASCII encoding back to GNUNET_CRYPTO_hash
306 * @param enc the encoding
307 * @param result where to store the GNUNET_CRYPTO_hash code
308 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
311 GNUNET_CRYPTO_hash_from_string (const char *enc, GNUNET_HashCode * result)
318 if (strlen (enc) != sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1)
319 return GNUNET_SYSERR;
321 vbit = 2; /* padding! */
322 wpos = sizeof (GNUNET_HashCode);
323 rpos = sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1;
324 bits = getValue__ (enc[--rpos]) >> 3;
327 GNUNET_assert (rpos > 0);
328 bits = (getValue__ (enc[--rpos]) << vbit) | bits;
332 ((unsigned char *) result)[--wpos] = (unsigned char) bits;
337 GNUNET_assert (rpos == 0);
338 GNUNET_assert (vbit == 0);
343 * Compute the distance between 2 hashcodes. The computation must be
344 * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
345 * somewhat consistent. And of course, the result should be a positive
348 * @param a some hash code
349 * @param b some hash code
350 * @return a positive number which is a measure for
351 * hashcode proximity.
354 GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
355 const GNUNET_HashCode * b)
357 unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
358 unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
363 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
364 GNUNET_HashCode * result)
367 for (i = (sizeof (GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--)
368 result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
372 GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
373 const GNUNET_HashCode * b,
374 GNUNET_HashCode * result)
377 for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
379 result->bits[i] = b->bits[i] - a->bits[i];
383 GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
384 const GNUNET_HashCode * delta,
385 GNUNET_HashCode * result)
388 for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
390 result->bits[i] = delta->bits[i] + a->bits[i];
395 GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a,
396 const GNUNET_HashCode * b,
397 GNUNET_HashCode * result)
400 for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
402 result->bits[i] = a->bits[i] ^ b->bits[i];
407 * Convert a hashcode into a key.
410 GNUNET_CRYPTO_hash_to_aes_key (const GNUNET_HashCode * hc,
411 struct GNUNET_CRYPTO_AesSessionKey *skey,
412 struct GNUNET_CRYPTO_AesInitializationVector
415 GNUNET_assert (sizeof (GNUNET_HashCode) >=
416 GNUNET_CRYPTO_AES_KEY_LENGTH +
417 sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
418 memcpy (skey, hc, GNUNET_CRYPTO_AES_KEY_LENGTH);
420 htonl (GNUNET_CRYPTO_crc32_n (skey, GNUNET_CRYPTO_AES_KEY_LENGTH));
421 memcpy (iv, &((char *) hc)[GNUNET_CRYPTO_AES_KEY_LENGTH],
422 sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
427 * Obtain a bit from a hashcode.
428 * @param code the GNUNET_CRYPTO_hash to index bit-wise
429 * @param bit index into the hashcode, [0...511]
430 * @return Bit \a bit from hashcode \a code, -1 for invalid index
433 GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code,
436 GNUNET_assert (bit < 8 * sizeof (GNUNET_HashCode));
437 return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
441 * Determine how many low order bits match in two
442 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
443 * the first two lowest order bits, and therefore the
444 * return value is two (NOT XOR distance, nor how many
445 * bits match absolutely!).
447 * @param first the first hashcode
448 * @param second the hashcode to compare first to
450 * @return the number of bits that match
453 GNUNET_CRYPTO_hash_matching_bits(const GNUNET_HashCode *first,
454 const GNUNET_HashCode *second)
458 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
459 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
461 return sizeof (GNUNET_HashCode) * 8;
466 * Compare function for HashCodes, producing a total ordering
468 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
471 GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1,
472 const GNUNET_HashCode * h2)
478 i1 = (unsigned int *) h1;
479 i2 = (unsigned int *) h2;
480 for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
493 * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
494 * in the XOR metric (Kademlia).
495 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
498 GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
499 const GNUNET_HashCode * h2,
500 const GNUNET_HashCode * target)
506 for (i = sizeof (GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
508 d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
509 d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
520 * @brief Derive an authentication key
521 * @param key authentication key
522 * @param rkey root key
524 * @param salt_len size of the salt
525 * @param ... pair of void * & size_t for context chunks, terminated by NULL
528 GNUNET_CRYPTO_hmac_derive_key(struct GNUNET_CRYPTO_AuthKey *key,
529 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
536 va_start (argp, salt_len);
537 GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
543 * @brief Derive an authentication key
544 * @param key authentication key
545 * @param rkey root key
547 * @param salt_len size of the salt
548 * @param argp pair of void * & size_t for context chunks, terminated by NULL
551 GNUNET_CRYPTO_hmac_derive_key_v(struct GNUNET_CRYPTO_AuthKey *key,
552 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
557 GNUNET_CRYPTO_kdf_v (key->key,
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,
577 size_t plaintext_len,
578 GNUNET_HashCode *hmac)
581 const unsigned char *mc;
583 GNUNET_assert (GPG_ERR_NO_ERROR == gcry_md_open (&md,
586 gcry_md_setkey (md, key->key, sizeof(key->key));
587 gcry_md_write (md, plaintext, plaintext_len);
588 mc = gcry_md_read (md, GCRY_MD_SHA512);
590 memcpy (hmac->bits, mc, sizeof(hmac->bits));
595 /* end of crypto_hash.c */