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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file util/crypto_hash.c
23 * @brief SHA-512 #GNUNET_CRYPTO_hash() related functions
24 * @author Christian Grothoff
27 #include "gnunet_crypto_lib.h"
28 #include "gnunet_strings_lib.h"
29 #include "benchmark.h"
32 #define LOG(kind, ...) GNUNET_log_from (kind, "util-crypto-hash", __VA_ARGS__)
34 #define LOG_STRERROR_FILE(kind, syscall, \
35 filename) GNUNET_log_from_strerror_file (kind, \
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 in @a block
45 * @param ret pointer to where to write the hashcode
48 GNUNET_CRYPTO_hash (const void *block,
50 struct GNUNET_HashCode *ret)
52 BENCHMARK_START (hash);
53 gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
58 /* ***************** binary-ASCII encoding *************** */
62 * Convert GNUNET_CRYPTO_hash to ASCII encoding. The ASCII encoding is rather
63 * GNUnet specific. It was chosen such that it only uses characters
64 * in [0-9A-V], can be produced without complex arithmetics and uses a
65 * small number of characters. The GNUnet encoding uses 103
66 * characters plus a null terminator.
68 * @param block the hash code
69 * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
70 * safely cast to char*, a '\\0' termination is set).
73 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block,
74 struct GNUNET_CRYPTO_HashAsciiEncoded *result)
78 np = GNUNET_STRINGS_data_to_string ((const unsigned char *) block,
79 sizeof(struct GNUNET_HashCode),
82 GNUNET_CRYPTO_HashAsciiEncoded)
84 GNUNET_assert (NULL != np);
90 * Convert ASCII encoding back to hash code.
92 * @param enc the encoding
93 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
94 * @param result where to store the hash code
95 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
98 GNUNET_CRYPTO_hash_from_string2 (const char *enc,
100 struct GNUNET_HashCode *result)
102 char upper_enc[enclen];
103 char *up_ptr = upper_enc;
105 GNUNET_STRINGS_utf8_toupper (enc, up_ptr);
107 return GNUNET_STRINGS_string_to_data (upper_enc, enclen,
108 (unsigned char*) result,
109 sizeof(struct GNUNET_HashCode));
116 * Compute the distance between 2 hashcodes. The computation must be
117 * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
118 * somewhat consistent. And of course, the result should be a positive
121 * @param a some hash code
122 * @param b some hash code
123 * @return a positive number which is a measure for
124 * hashcode proximity.
127 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a,
128 const struct GNUNET_HashCode *b)
130 unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
131 unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
138 * Create a random hash code.
140 * @param mode desired quality level
141 * @param result hash code that is randomized
144 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
145 struct GNUNET_HashCode *result)
149 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(uint32_t)) - 1; i >= 0; i--)
150 result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
155 * compute result(delta) = b - a
157 * @param a some hash code
158 * @param b some hash code
159 * @param result set to b - a
162 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a,
163 const struct GNUNET_HashCode *b,
164 struct GNUNET_HashCode *result)
168 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
170 result->bits[i] = b->bits[i] - a->bits[i];
175 * compute result(b) = a + delta
177 * @param a some hash code
178 * @param delta some hash code
179 * @param result set to a + delta
182 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode *a,
183 const struct GNUNET_HashCode *delta, struct
184 GNUNET_HashCode *result)
188 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
190 result->bits[i] = delta->bits[i] + a->bits[i];
195 * compute result = a ^ b
197 * @param a some hash code
198 * @param b some hash code
199 * @param result set to a ^ b
202 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a,
203 const struct GNUNET_HashCode *b,
204 struct GNUNET_HashCode *result)
208 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
210 result->bits[i] = a->bits[i] ^ b->bits[i];
215 * Convert a hashcode into a key.
217 * @param hc hash code that serves to generate the key
218 * @param skey set to a valid session key
219 * @param iv set to a valid initialization vector
222 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode *hc,
223 struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
225 GNUNET_CRYPTO_SymmetricInitializationVector *iv)
227 GNUNET_assert (GNUNET_YES ==
228 GNUNET_CRYPTO_kdf (skey, sizeof(struct
229 GNUNET_CRYPTO_SymmetricSessionKey),
230 "Hash key derivation", strlen (
231 "Hash key derivation"),
232 hc, sizeof(struct GNUNET_HashCode),
234 GNUNET_assert (GNUNET_YES ==
235 GNUNET_CRYPTO_kdf (iv, sizeof(struct
236 GNUNET_CRYPTO_SymmetricInitializationVector),
237 "Initialization vector derivation", strlen (
238 "Initialization vector derivation"),
239 hc, sizeof(struct GNUNET_HashCode),
245 * Obtain a bit from a hashcode.
246 * @param code the GNUNET_CRYPTO_hash to index bit-wise
247 * @param bit index into the hashcode, [0...511]
248 * @return Bit \a bit from hashcode \a code, -1 for invalid index
251 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode *code, unsigned int
254 GNUNET_assert (bit < 8 * sizeof(struct GNUNET_HashCode));
255 return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
260 * Determine how many low order bits match in two
261 * `struct GNUNET_HashCode`s. i.e. - 010011 and 011111 share
262 * the first two lowest order bits, and therefore the
263 * return value is two (NOT XOR distance, nor how many
264 * bits match absolutely!).
266 * @param first the first hashcode
267 * @param second the hashcode to compare first to
269 * @return the number of bits that match
272 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first,
273 const struct GNUNET_HashCode *second)
277 for (i = 0; i < sizeof(struct GNUNET_HashCode) * 8; i++)
278 if (GNUNET_CRYPTO_hash_get_bit (first, i) !=
279 GNUNET_CRYPTO_hash_get_bit (second, i))
281 return sizeof(struct GNUNET_HashCode) * 8;
286 * Compare function for HashCodes, producing a total ordering
289 * @param h1 some hash code
290 * @param h2 some hash code
291 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
294 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
295 const struct GNUNET_HashCode *h2)
301 i1 = (unsigned int *) h1;
302 i2 = (unsigned int *) h2;
303 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
316 * Find out which of the two `struct GNUNET_HashCode`s is closer to target
317 * in the XOR metric (Kademlia).
319 * @param h1 some hash code
320 * @param h2 some hash code
321 * @param target some hash code
322 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
325 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
326 const struct GNUNET_HashCode *h2,
327 const struct GNUNET_HashCode *target)
333 for (i = sizeof(struct GNUNET_HashCode) / sizeof(unsigned int) - 1; i >= 0;
336 d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
337 d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
348 * @brief Derive an authentication key
349 * @param key authentication key
350 * @param rkey root key
352 * @param salt_len size of the @a salt
353 * @param ... pair of void * & size_t for context chunks, terminated by NULL
356 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
358 GNUNET_CRYPTO_SymmetricSessionKey *rkey,
359 const void *salt, size_t salt_len, ...)
363 va_start (argp, salt_len);
364 GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
370 * @brief Derive an authentication key
371 * @param key authentication key
372 * @param rkey root key
374 * @param salt_len size of the @a salt
375 * @param argp pair of void * & size_t for context chunks, terminated by NULL
378 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
380 GNUNET_CRYPTO_SymmetricSessionKey *rkey,
381 const void *salt, size_t salt_len,
384 GNUNET_CRYPTO_kdf_v (key->key, sizeof(key->key),
386 rkey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey),
392 * Calculate HMAC of a message (RFC 2104)
393 * TODO: Shouldn' this be the standard hmac function and
394 * the above be renamed?
396 * @param key secret key
397 * @param key_len secret key length
398 * @param plaintext input plaintext
399 * @param plaintext_len length of @a plaintext
400 * @param hmac where to store the hmac
403 GNUNET_CRYPTO_hmac_raw (const void *key, size_t key_len,
404 const void *plaintext, size_t plaintext_len,
405 struct GNUNET_HashCode *hmac)
408 static gcry_md_hd_t md;
409 const unsigned char *mc;
414 GNUNET_assert (GPG_ERR_NO_ERROR ==
415 gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
421 gcry_md_setkey (md, key, key_len);
422 gcry_md_write (md, plaintext, plaintext_len);
423 mc = gcry_md_read (md, GCRY_MD_SHA512);
424 GNUNET_assert (NULL != mc);
425 GNUNET_memcpy (hmac->bits, mc, sizeof(hmac->bits));
430 * Calculate HMAC of a message (RFC 2104)
432 * @param key secret key
433 * @param plaintext input plaintext
434 * @param plaintext_len length of @a plaintext
435 * @param hmac where to store the hmac
438 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
439 const void *plaintext, size_t plaintext_len,
440 struct GNUNET_HashCode *hmac)
442 GNUNET_CRYPTO_hmac_raw ((void*) key->key, sizeof(key->key),
443 plaintext, plaintext_len,
449 * Context for cummulative hashing.
451 struct GNUNET_HashContext
454 * Internal state of the hash function.
461 * Start incremental hashing operation.
463 * @return context for incremental hash computation
465 struct GNUNET_HashContext *
466 GNUNET_CRYPTO_hash_context_start ()
468 struct GNUNET_HashContext *hc;
470 BENCHMARK_START (hash_context_start);
472 hc = GNUNET_new (struct GNUNET_HashContext);
474 gcry_md_open (&hc->hd,
478 BENCHMARK_END (hash_context_start);
485 * Add data to be hashed.
487 * @param hc cummulative hash context
488 * @param buf data to add
489 * @param size number of bytes in @a buf
492 GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
496 BENCHMARK_START (hash_context_read);
497 gcry_md_write (hc->hd, buf, size);
498 BENCHMARK_END (hash_context_read);
503 * Finish the hash computation.
505 * @param hc hash context to use
506 * @param r_hash where to write the latest / final hash code
509 GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
510 struct GNUNET_HashCode *r_hash)
512 const void *res = gcry_md_read (hc->hd, 0);
514 BENCHMARK_START (hash_context_finish);
516 GNUNET_assert (NULL != res);
518 GNUNET_memcpy (r_hash,
520 sizeof(struct GNUNET_HashCode));
521 GNUNET_CRYPTO_hash_context_abort (hc);
522 BENCHMARK_END (hash_context_finish);
527 * Abort hashing, do not bother calculating final result.
529 * @param hc hash context to destroy
532 GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc)
534 gcry_md_close (hc->hd);
539 /* end of crypto_hash.c */