crypto_hash.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /*
  2. This file is part of GNUnet.
  3. Copyright (C) 2001-2013 GNUnet e.V.
  4. GNUnet is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU Affero General Public License as published
  6. by the Free Software Foundation, either version 3 of the License,
  7. or (at your option) any later version.
  8. GNUnet is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Affero General Public License for more details.
  12. You should have received a copy of the GNU Affero General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. SPDX-License-Identifier: AGPL3.0-or-later
  15. */
  16. /**
  17. * @file util/crypto_hash.c
  18. * @brief SHA-512 #GNUNET_CRYPTO_hash() related functions
  19. * @author Christian Grothoff
  20. */
  21. #include "platform.h"
  22. #include "gnunet_crypto_lib.h"
  23. #include "gnunet_strings_lib.h"
  24. #include "benchmark.h"
  25. #include <gcrypt.h>
  26. #define LOG(kind, ...) GNUNET_log_from (kind, "util-crypto-hash", __VA_ARGS__)
  27. #define LOG_STRERROR_FILE(kind, syscall, \
  28. filename) GNUNET_log_from_strerror_file (kind, \
  29. "util-crypto-hash", \
  30. syscall, \
  31. filename)
  32. /**
  33. * Hash block of given size.
  34. *
  35. * @param block the data to #GNUNET_CRYPTO_hash, length is given as a second argument
  36. * @param size the length of the data to #GNUNET_CRYPTO_hash in @a block
  37. * @param ret pointer to where to write the hashcode
  38. */
  39. void
  40. GNUNET_CRYPTO_hash (const void *block,
  41. size_t size,
  42. struct GNUNET_HashCode *ret)
  43. {
  44. BENCHMARK_START (hash);
  45. gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
  46. BENCHMARK_END (hash);
  47. }
  48. /* ***************** binary-ASCII encoding *************** */
  49. /**
  50. * Convert GNUNET_CRYPTO_hash to ASCII encoding. The ASCII encoding is rather
  51. * GNUnet specific. It was chosen such that it only uses characters
  52. * in [0-9A-V], can be produced without complex arithmetics and uses a
  53. * small number of characters. The GNUnet encoding uses 103
  54. * characters plus a null terminator.
  55. *
  56. * @param block the hash code
  57. * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
  58. * safely cast to char*, a '\\0' termination is set).
  59. */
  60. void
  61. GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block,
  62. struct GNUNET_CRYPTO_HashAsciiEncoded *result)
  63. {
  64. char *np;
  65. np = GNUNET_STRINGS_data_to_string ((const unsigned char *) block,
  66. sizeof(struct GNUNET_HashCode),
  67. (char *) result,
  68. sizeof(struct
  69. GNUNET_CRYPTO_HashAsciiEncoded)
  70. - 1);
  71. GNUNET_assert (NULL != np);
  72. *np = '\0';
  73. }
  74. /**
  75. * Convert ASCII encoding back to hash code.
  76. *
  77. * @param enc the encoding
  78. * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
  79. * @param result where to store the hash code
  80. * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
  81. */
  82. int
  83. GNUNET_CRYPTO_hash_from_string2 (const char *enc,
  84. size_t enclen,
  85. struct GNUNET_HashCode *result)
  86. {
  87. char upper_enc[enclen];
  88. char *up_ptr = upper_enc;
  89. GNUNET_STRINGS_utf8_toupper (enc, up_ptr);
  90. return GNUNET_STRINGS_string_to_data (upper_enc, enclen,
  91. (unsigned char*) result,
  92. sizeof(struct GNUNET_HashCode));
  93. }
  94. /**
  95. * @ingroup hash
  96. *
  97. * Compute the distance between 2 hashcodes. The computation must be
  98. * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
  99. * somewhat consistent. And of course, the result should be a positive
  100. * number.
  101. *
  102. * @param a some hash code
  103. * @param b some hash code
  104. * @return a positive number which is a measure for
  105. * hashcode proximity.
  106. */
  107. unsigned int
  108. GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a,
  109. const struct GNUNET_HashCode *b)
  110. {
  111. unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
  112. unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
  113. return(x1 * x2);
  114. }
  115. /**
  116. * Create a random hash code.
  117. *
  118. * @param mode desired quality level
  119. * @param result hash code that is randomized
  120. */
  121. void
  122. GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
  123. struct GNUNET_HashCode *result)
  124. {
  125. int i;
  126. for (i = (sizeof(struct GNUNET_HashCode) / sizeof(uint32_t)) - 1; i >= 0; i--)
  127. result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX);
  128. }
  129. /**
  130. * compute result(delta) = b - a
  131. *
  132. * @param a some hash code
  133. * @param b some hash code
  134. * @param result set to b - a
  135. */
  136. void
  137. GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a,
  138. const struct GNUNET_HashCode *b,
  139. struct GNUNET_HashCode *result)
  140. {
  141. int i;
  142. for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
  143. i--)
  144. result->bits[i] = b->bits[i] - a->bits[i];
  145. }
  146. /**
  147. * compute result(b) = a + delta
  148. *
  149. * @param a some hash code
  150. * @param delta some hash code
  151. * @param result set to a + delta
  152. */
  153. void
  154. GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode *a,
  155. const struct GNUNET_HashCode *delta, struct
  156. GNUNET_HashCode *result)
  157. {
  158. int i;
  159. for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
  160. i--)
  161. result->bits[i] = delta->bits[i] + a->bits[i];
  162. }
  163. /**
  164. * compute result = a ^ b
  165. *
  166. * @param a some hash code
  167. * @param b some hash code
  168. * @param result set to a ^ b
  169. */
  170. void
  171. GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a,
  172. const struct GNUNET_HashCode *b,
  173. struct GNUNET_HashCode *result)
  174. {
  175. int i;
  176. for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
  177. i--)
  178. result->bits[i] = a->bits[i] ^ b->bits[i];
  179. }
  180. /**
  181. * Convert a hashcode into a key.
  182. *
  183. * @param hc hash code that serves to generate the key
  184. * @param skey set to a valid session key
  185. * @param iv set to a valid initialization vector
  186. */
  187. void
  188. GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode *hc,
  189. struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
  190. struct
  191. GNUNET_CRYPTO_SymmetricInitializationVector *iv)
  192. {
  193. GNUNET_assert (GNUNET_YES ==
  194. GNUNET_CRYPTO_kdf (skey, sizeof(struct
  195. GNUNET_CRYPTO_SymmetricSessionKey),
  196. "Hash key derivation", strlen (
  197. "Hash key derivation"),
  198. hc, sizeof(struct GNUNET_HashCode),
  199. NULL, 0));
  200. GNUNET_assert (GNUNET_YES ==
  201. GNUNET_CRYPTO_kdf (iv, sizeof(struct
  202. GNUNET_CRYPTO_SymmetricInitializationVector),
  203. "Initialization vector derivation", strlen (
  204. "Initialization vector derivation"),
  205. hc, sizeof(struct GNUNET_HashCode),
  206. NULL, 0));
  207. }
  208. /**
  209. * Obtain a bit from a hashcode.
  210. * @param code the GNUNET_CRYPTO_hash to index bit-wise
  211. * @param bit index into the hashcode, [0...511]
  212. * @return Bit \a bit from hashcode \a code, -1 for invalid index
  213. */
  214. int
  215. GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode *code, unsigned int
  216. bit)
  217. {
  218. GNUNET_assert (bit < 8 * sizeof(struct GNUNET_HashCode));
  219. return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
  220. }
  221. /**
  222. * Determine how many low order bits match in two
  223. * `struct GNUNET_HashCode`s. i.e. - 010011 and 011111 share
  224. * the first two lowest order bits, and therefore the
  225. * return value is two (NOT XOR distance, nor how many
  226. * bits match absolutely!).
  227. *
  228. * @param first the first hashcode
  229. * @param second the hashcode to compare first to
  230. *
  231. * @return the number of bits that match
  232. */
  233. unsigned int
  234. GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first,
  235. const struct GNUNET_HashCode *second)
  236. {
  237. unsigned int i;
  238. for (i = 0; i < sizeof(struct GNUNET_HashCode) * 8; i++)
  239. if (GNUNET_CRYPTO_hash_get_bit (first, i) !=
  240. GNUNET_CRYPTO_hash_get_bit (second, i))
  241. return i;
  242. return sizeof(struct GNUNET_HashCode) * 8;
  243. }
  244. /**
  245. * Compare function for HashCodes, producing a total ordering
  246. * of all hashcodes.
  247. *
  248. * @param h1 some hash code
  249. * @param h2 some hash code
  250. * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
  251. */
  252. int
  253. GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
  254. const struct GNUNET_HashCode *h2)
  255. {
  256. unsigned int *i1;
  257. unsigned int *i2;
  258. int i;
  259. i1 = (unsigned int *) h1;
  260. i2 = (unsigned int *) h2;
  261. for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0;
  262. i--)
  263. {
  264. if (i1[i] > i2[i])
  265. return 1;
  266. if (i1[i] < i2[i])
  267. return -1;
  268. }
  269. return 0;
  270. }
  271. /**
  272. * Find out which of the two `struct GNUNET_HashCode`s is closer to target
  273. * in the XOR metric (Kademlia).
  274. *
  275. * @param h1 some hash code
  276. * @param h2 some hash code
  277. * @param target some hash code
  278. * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
  279. */
  280. int
  281. GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
  282. const struct GNUNET_HashCode *h2,
  283. const struct GNUNET_HashCode *target)
  284. {
  285. int i;
  286. unsigned int d1;
  287. unsigned int d2;
  288. for (i = sizeof(struct GNUNET_HashCode) / sizeof(unsigned int) - 1; i >= 0;
  289. i--)
  290. {
  291. d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
  292. d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
  293. if (d1 > d2)
  294. return 1;
  295. else if (d1 < d2)
  296. return -1;
  297. }
  298. return 0;
  299. }
  300. /**
  301. * @brief Derive an authentication key
  302. * @param key authentication key
  303. * @param rkey root key
  304. * @param salt salt
  305. * @param salt_len size of the @a salt
  306. * @param ... pair of void * & size_t for context chunks, terminated by NULL
  307. */
  308. void
  309. GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
  310. const struct
  311. GNUNET_CRYPTO_SymmetricSessionKey *rkey,
  312. const void *salt, size_t salt_len, ...)
  313. {
  314. va_list argp;
  315. va_start (argp, salt_len);
  316. GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp);
  317. va_end (argp);
  318. }
  319. /**
  320. * @brief Derive an authentication key
  321. * @param key authentication key
  322. * @param rkey root key
  323. * @param salt salt
  324. * @param salt_len size of the @a salt
  325. * @param argp pair of void * & size_t for context chunks, terminated by NULL
  326. */
  327. void
  328. GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
  329. const struct
  330. GNUNET_CRYPTO_SymmetricSessionKey *rkey,
  331. const void *salt, size_t salt_len,
  332. va_list argp)
  333. {
  334. GNUNET_CRYPTO_kdf_v (key->key, sizeof(key->key),
  335. salt, salt_len,
  336. rkey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey),
  337. argp);
  338. }
  339. /**
  340. * Calculate HMAC of a message (RFC 2104)
  341. * TODO: Shouldn' this be the standard hmac function and
  342. * the above be renamed?
  343. *
  344. * @param key secret key
  345. * @param key_len secret key length
  346. * @param plaintext input plaintext
  347. * @param plaintext_len length of @a plaintext
  348. * @param hmac where to store the hmac
  349. */
  350. void
  351. GNUNET_CRYPTO_hmac_raw (const void *key, size_t key_len,
  352. const void *plaintext, size_t plaintext_len,
  353. struct GNUNET_HashCode *hmac)
  354. {
  355. static int once;
  356. static gcry_md_hd_t md;
  357. const unsigned char *mc;
  358. if (! once)
  359. {
  360. once = 1;
  361. GNUNET_assert (GPG_ERR_NO_ERROR ==
  362. gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
  363. }
  364. else
  365. {
  366. gcry_md_reset (md);
  367. }
  368. gcry_md_setkey (md, key, key_len);
  369. gcry_md_write (md, plaintext, plaintext_len);
  370. mc = gcry_md_read (md, GCRY_MD_SHA512);
  371. GNUNET_assert (NULL != mc);
  372. GNUNET_memcpy (hmac->bits, mc, sizeof(hmac->bits));
  373. }
  374. /**
  375. * Calculate HMAC of a message (RFC 2104)
  376. *
  377. * @param key secret key
  378. * @param plaintext input plaintext
  379. * @param plaintext_len length of @a plaintext
  380. * @param hmac where to store the hmac
  381. */
  382. void
  383. GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
  384. const void *plaintext, size_t plaintext_len,
  385. struct GNUNET_HashCode *hmac)
  386. {
  387. GNUNET_CRYPTO_hmac_raw ((void*) key->key, sizeof(key->key),
  388. plaintext, plaintext_len,
  389. hmac);
  390. }
  391. /**
  392. * Context for cummulative hashing.
  393. */
  394. struct GNUNET_HashContext
  395. {
  396. /**
  397. * Internal state of the hash function.
  398. */
  399. gcry_md_hd_t hd;
  400. };
  401. /**
  402. * Start incremental hashing operation.
  403. *
  404. * @return context for incremental hash computation
  405. */
  406. struct GNUNET_HashContext *
  407. GNUNET_CRYPTO_hash_context_start ()
  408. {
  409. struct GNUNET_HashContext *hc;
  410. BENCHMARK_START (hash_context_start);
  411. hc = GNUNET_new (struct GNUNET_HashContext);
  412. GNUNET_assert (0 ==
  413. gcry_md_open (&hc->hd,
  414. GCRY_MD_SHA512,
  415. 0));
  416. BENCHMARK_END (hash_context_start);
  417. return hc;
  418. }
  419. /**
  420. * Add data to be hashed.
  421. *
  422. * @param hc cummulative hash context
  423. * @param buf data to add
  424. * @param size number of bytes in @a buf
  425. */
  426. void
  427. GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
  428. const void *buf,
  429. size_t size)
  430. {
  431. BENCHMARK_START (hash_context_read);
  432. gcry_md_write (hc->hd, buf, size);
  433. BENCHMARK_END (hash_context_read);
  434. }
  435. /**
  436. * Finish the hash computation.
  437. *
  438. * @param hc hash context to use
  439. * @param r_hash where to write the latest / final hash code
  440. */
  441. void
  442. GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
  443. struct GNUNET_HashCode *r_hash)
  444. {
  445. const void *res = gcry_md_read (hc->hd, 0);
  446. BENCHMARK_START (hash_context_finish);
  447. GNUNET_assert (NULL != res);
  448. if (NULL != r_hash)
  449. GNUNET_memcpy (r_hash,
  450. res,
  451. sizeof(struct GNUNET_HashCode));
  452. GNUNET_CRYPTO_hash_context_abort (hc);
  453. BENCHMARK_END (hash_context_finish);
  454. }
  455. /**
  456. * Abort hashing, do not bother calculating final result.
  457. *
  458. * @param hc hash context to destroy
  459. */
  460. void
  461. GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc)
  462. {
  463. gcry_md_close (hc->hd);
  464. GNUNET_free (hc);
  465. }
  466. /* end of crypto_hash.c */