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] where 0 is the leftmost bit
248 * (bytes in code interpreted big endian)
249 * @return Bit \a bit from hashcode \a code, -1 for invalid index
252 GNUNET_CRYPTO_hash_get_bit_ltr (const struct GNUNET_HashCode *code,
255 GNUNET_assert (bit < 8 * sizeof(struct GNUNET_HashCode));
256 return (((unsigned char *) code)[bit >> 3] & (128 >> (bit & 7))) > 0;
260 * Obtain a bit from a hashcode.
261 * @param code the GNUNET_CRYPTO_hash to index bit-wise
262 * @param bit index into the hashcode, [0...511] where 0 is the rightmost bit
263 * (bytes in code interpreted little endian)
264 * @return Bit \a bit from hashcode \a code, -1 for invalid index
267 GNUNET_CRYPTO_hash_get_bit_rtl (const struct GNUNET_HashCode *code,
270 GNUNET_assert (bit < 8 * sizeof(struct GNUNET_HashCode));
271 return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
277 * Determine how many low order bits match in two
278 * `struct GNUNET_HashCode`s. i.e. - 010011 and 011111 share
279 * the first two lowest order bits, and therefore the
280 * return value is two (NOT XOR distance, nor how many
281 * bits match absolutely!).
283 * @param first the first hashcode
284 * @param second the hashcode to compare first to
286 * @return the number of bits that match
289 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first,
290 const struct GNUNET_HashCode *second)
294 for (i = 0; i < sizeof(struct GNUNET_HashCode) * 8; i++)
295 if (GNUNET_CRYPTO_hash_get_bit_rtl (first, i) !=
296 GNUNET_CRYPTO_hash_get_bit_rtl (second, i))
298 return sizeof(struct GNUNET_HashCode) * 8;
303 * Compare function for HashCodes, producing a total ordering
306 * @param h1 some hash code
307 * @param h2 some hash code
308 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
311 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
312 const struct GNUNET_HashCode *h2)
318 i1 = (unsigned int *) h1;
319 i2 = (unsigned int *) h2;
320 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
333 * Find out which of the two `struct GNUNET_HashCode`s is closer to target
334 * in the XOR metric (Kademlia).
336 * @param h1 some hash code
337 * @param h2 some hash code
338 * @param target some hash code
339 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
342 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
343 const struct GNUNET_HashCode *h2,
344 const struct GNUNET_HashCode *target)
350 for (i = sizeof(struct GNUNET_HashCode) / sizeof(unsigned int) - 1; i >= 0;
353 d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
354 d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
365 * @brief Derive an authentication key
366 * @param key authentication key
367 * @param rkey root key
369 * @param salt_len size of the @a salt
370 * @param ... pair of void * & size_t for context chunks, terminated by NULL
373 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
375 GNUNET_CRYPTO_SymmetricSessionKey *rkey,
376 const void *salt, size_t salt_len, ...)
380 va_start (argp, salt_len);
381 GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
387 * @brief Derive an authentication key
388 * @param key authentication key
389 * @param rkey root key
391 * @param salt_len size of the @a salt
392 * @param argp pair of void * & size_t for context chunks, terminated by NULL
395 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
397 GNUNET_CRYPTO_SymmetricSessionKey *rkey,
398 const void *salt, size_t salt_len,
401 GNUNET_CRYPTO_kdf_v (key->key, sizeof(key->key),
403 rkey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey),
409 * Calculate HMAC of a message (RFC 2104)
410 * TODO: Shouldn' this be the standard hmac function and
411 * the above be renamed?
413 * @param key secret key
414 * @param key_len secret key length
415 * @param plaintext input plaintext
416 * @param plaintext_len length of @a plaintext
417 * @param hmac where to store the hmac
420 GNUNET_CRYPTO_hmac_raw (const void *key, size_t key_len,
421 const void *plaintext, size_t plaintext_len,
422 struct GNUNET_HashCode *hmac)
425 static gcry_md_hd_t md;
426 const unsigned char *mc;
431 GNUNET_assert (GPG_ERR_NO_ERROR ==
432 gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
438 gcry_md_setkey (md, key, key_len);
439 gcry_md_write (md, plaintext, plaintext_len);
440 mc = gcry_md_read (md, GCRY_MD_SHA512);
441 GNUNET_assert (NULL != mc);
442 GNUNET_memcpy (hmac->bits, mc, sizeof(hmac->bits));
447 * Calculate HMAC of a message (RFC 2104)
449 * @param key secret key
450 * @param plaintext input plaintext
451 * @param plaintext_len length of @a plaintext
452 * @param hmac where to store the hmac
455 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
456 const void *plaintext, size_t plaintext_len,
457 struct GNUNET_HashCode *hmac)
459 GNUNET_CRYPTO_hmac_raw ((void *) key->key, sizeof(key->key),
460 plaintext, plaintext_len,
466 * Context for cummulative hashing.
468 struct GNUNET_HashContext
471 * Internal state of the hash function.
478 * Start incremental hashing operation.
480 * @return context for incremental hash computation
482 struct GNUNET_HashContext *
483 GNUNET_CRYPTO_hash_context_start ()
485 struct GNUNET_HashContext *hc;
487 BENCHMARK_START (hash_context_start);
489 hc = GNUNET_new (struct GNUNET_HashContext);
491 gcry_md_open (&hc->hd,
495 BENCHMARK_END (hash_context_start);
502 * Add data to be hashed.
504 * @param hc cummulative hash context
505 * @param buf data to add
506 * @param size number of bytes in @a buf
509 GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
513 BENCHMARK_START (hash_context_read);
514 gcry_md_write (hc->hd, buf, size);
515 BENCHMARK_END (hash_context_read);
520 * Finish the hash computation.
522 * @param hc hash context to use
523 * @param r_hash where to write the latest / final hash code
526 GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
527 struct GNUNET_HashCode *r_hash)
529 const void *res = gcry_md_read (hc->hd, 0);
531 BENCHMARK_START (hash_context_finish);
533 GNUNET_assert (NULL != res);
535 GNUNET_memcpy (r_hash,
537 sizeof(struct GNUNET_HashCode));
538 GNUNET_CRYPTO_hash_context_abort (hc);
539 BENCHMARK_END (hash_context_finish);
544 * Abort hashing, do not bother calculating final result.
546 * @param hc hash context to destroy
549 GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc)
551 gcry_md_close (hc->hd);
556 /* end of crypto_hash.c */