2 This file is part of GNUnet.
3 Copyright (C) 2001-2013 GNUnet e.V.
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.
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.
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/>.
20 * @file util/crypto_hash.c
21 * @brief SHA-512 #GNUNET_CRYPTO_hash() related functions
22 * @author Christian Grothoff
25 #include "gnunet_crypto_lib.h"
26 #include "gnunet_strings_lib.h"
27 #include "benchmark.h"
30 #define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-hash", __VA_ARGS__)
32 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-crypto-hash", syscall, filename)
35 * Hash block of given size.
37 * @param block the data to #GNUNET_CRYPTO_hash, length is given as a second argument
38 * @param size the length of the data to #GNUNET_CRYPTO_hash in @a block
39 * @param ret pointer to where to write the hashcode
42 GNUNET_CRYPTO_hash (const void *block,
44 struct GNUNET_HashCode *ret)
46 BENCHMARK_START (hash);
47 gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
52 /* ***************** binary-ASCII encoding *************** */
56 * Convert GNUNET_CRYPTO_hash to ASCII encoding. The ASCII encoding is rather
57 * GNUnet specific. It was chosen such that it only uses characters
58 * in [0-9A-V], can be produced without complex arithmetics and uses a
59 * small number of characters. The GNUnet encoding uses 103
60 * characters plus a null terminator.
62 * @param block the hash code
63 * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
64 * safely cast to char*, a '\\0' termination is set).
67 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block,
68 struct GNUNET_CRYPTO_HashAsciiEncoded *result)
72 np = GNUNET_STRINGS_data_to_string ((const unsigned char *) block,
73 sizeof (struct GNUNET_HashCode),
75 sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
76 GNUNET_assert (NULL != np);
82 * Convert ASCII encoding back to hash code.
84 * @param enc the encoding
85 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
86 * @param result where to store the hash code
87 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
90 GNUNET_CRYPTO_hash_from_string2 (const char *enc,
92 struct GNUNET_HashCode *result)
94 char upper_enc[enclen];
95 char *up_ptr = upper_enc;
97 GNUNET_STRINGS_utf8_toupper (enc, up_ptr);
99 return GNUNET_STRINGS_string_to_data (upper_enc, enclen,
100 (unsigned char*) result,
101 sizeof (struct GNUNET_HashCode));
108 * Compute the distance between 2 hashcodes. The computation must be
109 * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
110 * somewhat consistent. And of course, the result should be a positive
113 * @param a some hash code
114 * @param b some hash code
115 * @return a positive number which is a measure for
116 * hashcode proximity.
119 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a,
120 const struct GNUNET_HashCode *b)
122 unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
123 unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
130 * Create a random hash code.
132 * @param mode desired quality level
133 * @param result hash code that is randomized
136 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
137 struct GNUNET_HashCode *result)
141 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--)
142 result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
147 * compute result(delta) = b - a
149 * @param a some hash code
150 * @param b some hash code
151 * @param result set to b - a
154 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a,
155 const struct GNUNET_HashCode *b,
156 struct GNUNET_HashCode *result)
160 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
161 result->bits[i] = b->bits[i] - a->bits[i];
166 * compute result(b) = a + delta
168 * @param a some hash code
169 * @param delta some hash code
170 * @param result set to a + delta
173 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode * a,
174 const struct GNUNET_HashCode * delta, struct GNUNET_HashCode * result)
178 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
179 result->bits[i] = delta->bits[i] + a->bits[i];
184 * compute result = a ^ b
186 * @param a some hash code
187 * @param b some hash code
188 * @param result set to a ^ b
191 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a,
192 const struct GNUNET_HashCode *b,
193 struct GNUNET_HashCode *result)
197 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
198 result->bits[i] = a->bits[i] ^ b->bits[i];
203 * Convert a hashcode into a key.
205 * @param hc hash code that serves to generate the key
206 * @param skey set to a valid session key
207 * @param iv set to a valid initialization vector
210 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode *hc,
211 struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
212 struct GNUNET_CRYPTO_SymmetricInitializationVector *iv)
214 GNUNET_assert (GNUNET_YES ==
215 GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
216 "Hash key derivation", strlen ("Hash key derivation"),
217 hc, sizeof (struct GNUNET_HashCode),
219 GNUNET_assert (GNUNET_YES ==
220 GNUNET_CRYPTO_kdf (iv, sizeof (struct GNUNET_CRYPTO_SymmetricInitializationVector),
221 "Initialization vector derivation", strlen ("Initialization vector derivation"),
222 hc, sizeof (struct GNUNET_HashCode),
228 * Obtain a bit from a hashcode.
229 * @param code the GNUNET_CRYPTO_hash to index bit-wise
230 * @param bit index into the hashcode, [0...511]
231 * @return Bit \a bit from hashcode \a code, -1 for invalid index
234 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode * code, unsigned int bit)
236 GNUNET_assert (bit < 8 * sizeof (struct GNUNET_HashCode));
237 return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
242 * Determine how many low order bits match in two
243 * `struct GNUNET_HashCode`s. i.e. - 010011 and 011111 share
244 * the first two lowest order bits, and therefore the
245 * return value is two (NOT XOR distance, nor how many
246 * bits match absolutely!).
248 * @param first the first hashcode
249 * @param second the hashcode to compare first to
251 * @return the number of bits that match
254 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode * first,
255 const struct GNUNET_HashCode * second)
259 for (i = 0; i < sizeof (struct GNUNET_HashCode) * 8; i++)
260 if (GNUNET_CRYPTO_hash_get_bit (first, i) !=
261 GNUNET_CRYPTO_hash_get_bit (second, i))
263 return sizeof (struct GNUNET_HashCode) * 8;
268 * Compare function for HashCodes, producing a total ordering
271 * @param h1 some hash code
272 * @param h2 some hash code
273 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
276 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
277 const struct GNUNET_HashCode *h2)
283 i1 = (unsigned int *) h1;
284 i2 = (unsigned int *) h2;
285 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--)
297 * Find out which of the two `struct GNUNET_HashCode`s is closer to target
298 * in the XOR metric (Kademlia).
300 * @param h1 some hash code
301 * @param h2 some hash code
302 * @param target some hash code
303 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
306 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
307 const struct GNUNET_HashCode *h2,
308 const struct GNUNET_HashCode *target)
314 for (i = sizeof (struct GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
316 d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
317 d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
328 * @brief Derive an authentication key
329 * @param key authentication key
330 * @param rkey root key
332 * @param salt_len size of the @a salt
333 * @param ... pair of void * & size_t for context chunks, terminated by NULL
336 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
337 const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
338 const void *salt, size_t salt_len, ...)
342 va_start (argp, salt_len);
343 GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
349 * @brief Derive an authentication key
350 * @param key authentication key
351 * @param rkey root key
353 * @param salt_len size of the @a salt
354 * @param argp pair of void * & size_t for context chunks, terminated by NULL
357 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
358 const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
359 const void *salt, size_t salt_len,
362 GNUNET_CRYPTO_kdf_v (key->key, sizeof (key->key),
364 rkey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
370 * Calculate HMAC of a message (RFC 2104)
371 * TODO: Shouldn' this be the standard hmac function and
372 * the above be renamed?
374 * @param key secret key
375 * @param key_len secret key length
376 * @param plaintext input plaintext
377 * @param plaintext_len length of @a plaintext
378 * @param hmac where to store the hmac
381 GNUNET_CRYPTO_hmac_raw (const void *key, size_t key_len,
382 const void *plaintext, size_t plaintext_len,
383 struct GNUNET_HashCode *hmac)
386 static gcry_md_hd_t md;
387 const unsigned char *mc;
392 GNUNET_assert (GPG_ERR_NO_ERROR ==
393 gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
399 gcry_md_setkey (md, key, key_len);
400 gcry_md_write (md, plaintext, plaintext_len);
401 mc = gcry_md_read (md, GCRY_MD_SHA512);
402 GNUNET_assert (NULL != mc);
403 GNUNET_memcpy (hmac->bits, mc, sizeof (hmac->bits));
408 * Calculate HMAC of a message (RFC 2104)
410 * @param key secret key
411 * @param plaintext input plaintext
412 * @param plaintext_len length of @a plaintext
413 * @param hmac where to store the hmac
416 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
417 const void *plaintext, size_t plaintext_len,
418 struct GNUNET_HashCode *hmac)
420 GNUNET_CRYPTO_hmac_raw ((void*) key->key, sizeof (key->key),
421 plaintext, plaintext_len,
427 * Context for cummulative hashing.
429 struct GNUNET_HashContext
432 * Internal state of the hash function.
439 * Start incremental hashing operation.
441 * @return context for incremental hash computation
443 struct GNUNET_HashContext *
444 GNUNET_CRYPTO_hash_context_start ()
446 struct GNUNET_HashContext *hc;
448 BENCHMARK_START (hash_context_start);
450 hc = GNUNET_new (struct GNUNET_HashContext);
452 gcry_md_open (&hc->hd,
456 BENCHMARK_END (hash_context_start);
463 * Add data to be hashed.
465 * @param hc cummulative hash context
466 * @param buf data to add
467 * @param size number of bytes in @a buf
470 GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
474 BENCHMARK_START (hash_context_read);
475 gcry_md_write (hc->hd, buf, size);
476 BENCHMARK_END (hash_context_read);
481 * Finish the hash computation.
483 * @param hc hash context to use
484 * @param r_hash where to write the latest / final hash code
487 GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
488 struct GNUNET_HashCode *r_hash)
490 const void *res = gcry_md_read (hc->hd, 0);
492 BENCHMARK_START (hash_context_finish);
494 GNUNET_assert (NULL != res);
496 GNUNET_memcpy (r_hash,
498 sizeof (struct GNUNET_HashCode));
499 GNUNET_CRYPTO_hash_context_abort (hc);
500 BENCHMARK_END (hash_context_finish);
505 * Abort hashing, do not bother calculating final result.
507 * @param hc hash context to destroy
510 GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc)
512 gcry_md_close (hc->hd);
517 /* end of crypto_hash.c */