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, filename) GNUNET_log_from_strerror_file(kind, "util-crypto-hash", syscall, filename)
37 * Hash block of given size.
39 * @param block the data to #GNUNET_CRYPTO_hash, length is given as a second argument
40 * @param size the length of the data to #GNUNET_CRYPTO_hash in @a block
41 * @param ret pointer to where to write the hashcode
44 GNUNET_CRYPTO_hash(const void *block,
46 struct GNUNET_HashCode *ret)
48 BENCHMARK_START(hash);
49 gcry_md_hash_buffer(GCRY_MD_SHA512, ret, block, size);
54 /* ***************** binary-ASCII encoding *************** */
58 * Convert GNUNET_CRYPTO_hash to ASCII encoding. The ASCII encoding is rather
59 * GNUnet specific. It was chosen such that it only uses characters
60 * in [0-9A-V], can be produced without complex arithmetics and uses a
61 * small number of characters. The GNUnet encoding uses 103
62 * characters plus a null terminator.
64 * @param block the hash code
65 * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
66 * safely cast to char*, a '\\0' termination is set).
69 GNUNET_CRYPTO_hash_to_enc(const struct GNUNET_HashCode *block,
70 struct GNUNET_CRYPTO_HashAsciiEncoded *result)
74 np = GNUNET_STRINGS_data_to_string((const unsigned char *)block,
75 sizeof(struct GNUNET_HashCode),
77 sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
78 GNUNET_assert(NULL != np);
84 * Convert ASCII encoding back to hash code.
86 * @param enc the encoding
87 * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
88 * @param result where to store the hash code
89 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
92 GNUNET_CRYPTO_hash_from_string2(const char *enc,
94 struct GNUNET_HashCode *result)
96 char upper_enc[enclen];
97 char *up_ptr = upper_enc;
99 GNUNET_STRINGS_utf8_toupper(enc, up_ptr);
101 return GNUNET_STRINGS_string_to_data(upper_enc, enclen,
102 (unsigned char*)result,
103 sizeof(struct GNUNET_HashCode));
110 * Compute the distance between 2 hashcodes. The computation must be
111 * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
112 * somewhat consistent. And of course, the result should be a positive
115 * @param a some hash code
116 * @param b some hash code
117 * @return a positive number which is a measure for
118 * hashcode proximity.
121 GNUNET_CRYPTO_hash_distance_u32(const struct GNUNET_HashCode *a,
122 const struct GNUNET_HashCode *b)
124 unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
125 unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
132 * Create a random hash code.
134 * @param mode desired quality level
135 * @param result hash code that is randomized
138 GNUNET_CRYPTO_hash_create_random(enum GNUNET_CRYPTO_Quality mode,
139 struct GNUNET_HashCode *result)
143 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(uint32_t)) - 1; i >= 0; i--)
144 result->bits[i] = GNUNET_CRYPTO_random_u32(mode, UINT32_MAX);
149 * compute result(delta) = b - a
151 * @param a some hash code
152 * @param b some hash code
153 * @param result set to b - a
156 GNUNET_CRYPTO_hash_difference(const struct GNUNET_HashCode *a,
157 const struct GNUNET_HashCode *b,
158 struct GNUNET_HashCode *result)
162 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0; i--)
163 result->bits[i] = b->bits[i] - a->bits[i];
168 * compute result(b) = a + delta
170 * @param a some hash code
171 * @param delta some hash code
172 * @param result set to a + delta
175 GNUNET_CRYPTO_hash_sum(const struct GNUNET_HashCode * a,
176 const struct GNUNET_HashCode * delta, struct GNUNET_HashCode * result)
180 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0; i--)
181 result->bits[i] = delta->bits[i] + a->bits[i];
186 * compute result = a ^ b
188 * @param a some hash code
189 * @param b some hash code
190 * @param result set to a ^ b
193 GNUNET_CRYPTO_hash_xor(const struct GNUNET_HashCode *a,
194 const struct GNUNET_HashCode *b,
195 struct GNUNET_HashCode *result)
199 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0; i--)
200 result->bits[i] = a->bits[i] ^ b->bits[i];
205 * Convert a hashcode into a key.
207 * @param hc hash code that serves to generate the key
208 * @param skey set to a valid session key
209 * @param iv set to a valid initialization vector
212 GNUNET_CRYPTO_hash_to_aes_key(const struct GNUNET_HashCode *hc,
213 struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
214 struct GNUNET_CRYPTO_SymmetricInitializationVector *iv)
216 GNUNET_assert(GNUNET_YES ==
217 GNUNET_CRYPTO_kdf(skey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey),
218 "Hash key derivation", strlen("Hash key derivation"),
219 hc, sizeof(struct GNUNET_HashCode),
221 GNUNET_assert(GNUNET_YES ==
222 GNUNET_CRYPTO_kdf(iv, sizeof(struct GNUNET_CRYPTO_SymmetricInitializationVector),
223 "Initialization vector derivation", strlen("Initialization vector derivation"),
224 hc, sizeof(struct GNUNET_HashCode),
230 * Obtain a bit from a hashcode.
231 * @param code the GNUNET_CRYPTO_hash to index bit-wise
232 * @param bit index into the hashcode, [0...511]
233 * @return Bit \a bit from hashcode \a code, -1 for invalid index
236 GNUNET_CRYPTO_hash_get_bit(const struct GNUNET_HashCode * code, unsigned int bit)
238 GNUNET_assert(bit < 8 * sizeof(struct GNUNET_HashCode));
239 return (((unsigned char *)code)[bit >> 3] & (1 << (bit & 7))) > 0;
244 * Determine how many low order bits match in two
245 * `struct GNUNET_HashCode`s. i.e. - 010011 and 011111 share
246 * the first two lowest order bits, and therefore the
247 * return value is two (NOT XOR distance, nor how many
248 * bits match absolutely!).
250 * @param first the first hashcode
251 * @param second the hashcode to compare first to
253 * @return the number of bits that match
256 GNUNET_CRYPTO_hash_matching_bits(const struct GNUNET_HashCode * first,
257 const struct GNUNET_HashCode * second)
261 for (i = 0; i < sizeof(struct GNUNET_HashCode) * 8; i++)
262 if (GNUNET_CRYPTO_hash_get_bit(first, i) !=
263 GNUNET_CRYPTO_hash_get_bit(second, i))
265 return sizeof(struct GNUNET_HashCode) * 8;
270 * Compare function for HashCodes, producing a total ordering
273 * @param h1 some hash code
274 * @param h2 some hash code
275 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
278 GNUNET_CRYPTO_hash_cmp(const struct GNUNET_HashCode *h1,
279 const struct GNUNET_HashCode *h2)
285 i1 = (unsigned int *)h1;
286 i2 = (unsigned int *)h2;
287 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0; i--)
299 * Find out which of the two `struct GNUNET_HashCode`s is closer to target
300 * in the XOR metric (Kademlia).
302 * @param h1 some hash code
303 * @param h2 some hash code
304 * @param target some hash code
305 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
308 GNUNET_CRYPTO_hash_xorcmp(const struct GNUNET_HashCode *h1,
309 const struct GNUNET_HashCode *h2,
310 const struct GNUNET_HashCode *target)
316 for (i = sizeof(struct GNUNET_HashCode) / sizeof(unsigned int) - 1; i >= 0; i--)
318 d1 = ((unsigned int *)h1)[i] ^ ((unsigned int *)target)[i];
319 d2 = ((unsigned int *)h2)[i] ^ ((unsigned int *)target)[i];
330 * @brief Derive an authentication key
331 * @param key authentication key
332 * @param rkey root key
334 * @param salt_len size of the @a salt
335 * @param ... pair of void * & size_t for context chunks, terminated by NULL
338 GNUNET_CRYPTO_hmac_derive_key(struct GNUNET_CRYPTO_AuthKey *key,
339 const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
340 const void *salt, size_t salt_len, ...)
344 va_start(argp, salt_len);
345 GNUNET_CRYPTO_hmac_derive_key_v(key, rkey, salt, salt_len, argp);
351 * @brief Derive an authentication key
352 * @param key authentication key
353 * @param rkey root key
355 * @param salt_len size of the @a salt
356 * @param argp pair of void * & size_t for context chunks, terminated by NULL
359 GNUNET_CRYPTO_hmac_derive_key_v(struct GNUNET_CRYPTO_AuthKey *key,
360 const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
361 const void *salt, size_t salt_len,
364 GNUNET_CRYPTO_kdf_v(key->key, sizeof(key->key),
366 rkey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey),
372 * Calculate HMAC of a message (RFC 2104)
373 * TODO: Shouldn' this be the standard hmac function and
374 * the above be renamed?
376 * @param key secret key
377 * @param key_len secret key length
378 * @param plaintext input plaintext
379 * @param plaintext_len length of @a plaintext
380 * @param hmac where to store the hmac
383 GNUNET_CRYPTO_hmac_raw(const void *key, size_t key_len,
384 const void *plaintext, size_t plaintext_len,
385 struct GNUNET_HashCode *hmac)
388 static gcry_md_hd_t md;
389 const unsigned char *mc;
394 GNUNET_assert(GPG_ERR_NO_ERROR ==
395 gcry_md_open(&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
401 gcry_md_setkey(md, key, key_len);
402 gcry_md_write(md, plaintext, plaintext_len);
403 mc = gcry_md_read(md, GCRY_MD_SHA512);
404 GNUNET_assert(NULL != mc);
405 GNUNET_memcpy(hmac->bits, mc, sizeof(hmac->bits));
410 * Calculate HMAC of a message (RFC 2104)
412 * @param key secret key
413 * @param plaintext input plaintext
414 * @param plaintext_len length of @a plaintext
415 * @param hmac where to store the hmac
418 GNUNET_CRYPTO_hmac(const struct GNUNET_CRYPTO_AuthKey *key,
419 const void *plaintext, size_t plaintext_len,
420 struct GNUNET_HashCode *hmac)
422 GNUNET_CRYPTO_hmac_raw((void*)key->key, sizeof(key->key),
423 plaintext, plaintext_len,
429 * Context for cummulative hashing.
431 struct GNUNET_HashContext {
433 * Internal state of the hash function.
440 * Start incremental hashing operation.
442 * @return context for incremental hash computation
444 struct GNUNET_HashContext *
445 GNUNET_CRYPTO_hash_context_start()
447 struct GNUNET_HashContext *hc;
449 BENCHMARK_START(hash_context_start);
451 hc = GNUNET_new(struct GNUNET_HashContext);
453 gcry_md_open(&hc->hd,
457 BENCHMARK_END(hash_context_start);
464 * Add data to be hashed.
466 * @param hc cummulative hash context
467 * @param buf data to add
468 * @param size number of bytes in @a buf
471 GNUNET_CRYPTO_hash_context_read(struct GNUNET_HashContext *hc,
475 BENCHMARK_START(hash_context_read);
476 gcry_md_write(hc->hd, buf, size);
477 BENCHMARK_END(hash_context_read);
482 * Finish the hash computation.
484 * @param hc hash context to use
485 * @param r_hash where to write the latest / final hash code
488 GNUNET_CRYPTO_hash_context_finish(struct GNUNET_HashContext *hc,
489 struct GNUNET_HashCode *r_hash)
491 const void *res = gcry_md_read(hc->hd, 0);
493 BENCHMARK_START(hash_context_finish);
495 GNUNET_assert(NULL != res);
497 GNUNET_memcpy(r_hash,
499 sizeof(struct GNUNET_HashCode));
500 GNUNET_CRYPTO_hash_context_abort(hc);
501 BENCHMARK_END(hash_context_finish);
506 * Abort hashing, do not bother calculating final result.
508 * @param hc hash context to destroy
511 GNUNET_CRYPTO_hash_context_abort(struct GNUNET_HashContext *hc)
513 gcry_md_close(hc->hd);
518 /* end of crypto_hash.c */