crypto_hash.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <stddef.h>
  2. #include <stdint.h>
  3. #include "crypto_internal.h"
  4. #include "sha256.h"
  5. #include "crypto.h"
  6. /**
  7. * crypto_hash_data_key(key, keylen, data, len, buf):
  8. * Hash the provided ${data} with the provided HMAC-SHA256 ${key}.
  9. */
  10. void
  11. crypto_hash_data_key(const uint8_t * key, size_t keylen,
  12. const uint8_t * data, size_t len, uint8_t buf[32])
  13. {
  14. /* Use crypto_hash_data_key_2 to do the work. */
  15. crypto_hash_data_key_2(key, keylen, data, len, NULL, 0, buf);
  16. }
  17. /**
  18. * crypto_hash_data_key_2(key, keylen, data0, len0, data1, len1, buf):
  19. * Hash the concatenation of two buffers with the provided HMAC-SHA256 ${key}.
  20. */
  21. void
  22. crypto_hash_data_key_2(const uint8_t * key, size_t keylen,
  23. const uint8_t * data0, size_t len0,
  24. const uint8_t * data1, size_t len1, uint8_t buf[32])
  25. {
  26. HMAC_SHA256_CTX hctx;
  27. /* Do the hashing. */
  28. HMAC_SHA256_Init(&hctx, key, keylen);
  29. HMAC_SHA256_Update(&hctx, data0, len0);
  30. HMAC_SHA256_Update(&hctx, data1, len1);
  31. HMAC_SHA256_Final(buf, &hctx);
  32. }
  33. /**
  34. * crypto_hash_data(key, data, len, buf):
  35. * Hash the provided ${data} with the HMAC-SHA256 ${key} specified; or if
  36. * ${key} == CRYPTO_KEY_HMAC_SHA256, just SHA256 the data.
  37. */
  38. int
  39. crypto_hash_data(int key, const uint8_t * data, size_t len, uint8_t buf[32])
  40. {
  41. /* Use crypto_hash_data_2 to do the work. */
  42. return (crypto_hash_data_2(key, data, len, NULL, 0, buf));
  43. }
  44. /**
  45. * crypto_hash_data_2(key, data0, len0, data1, len1, buf):
  46. * Hash the concatenation of two buffers, as in crypto_hash_data.
  47. */
  48. int
  49. crypto_hash_data_2(int key, const uint8_t * data0, size_t len0,
  50. const uint8_t * data1, size_t len1, uint8_t buf[32])
  51. {
  52. HMAC_SHA256_CTX hctx;
  53. SHA256_CTX ctx;
  54. struct crypto_hmac_key * hkey;
  55. if (key == CRYPTO_KEY_HMAC_SHA256) {
  56. /* Hash the data. */
  57. SHA256_Init(&ctx);
  58. SHA256_Update(&ctx, data0, len0);
  59. SHA256_Update(&ctx, data1, len1);
  60. SHA256_Final(buf, &ctx);
  61. } else {
  62. if ((hkey = crypto_keys_lookup_HMAC(key)) == NULL)
  63. goto err0;
  64. /* Do the HMAC. */
  65. HMAC_SHA256_Init(&hctx, hkey->key, hkey->len);
  66. HMAC_SHA256_Update(&hctx, data0, len0);
  67. HMAC_SHA256_Update(&hctx, data1, len1);
  68. HMAC_SHA256_Final(buf, &hctx);
  69. }
  70. /* Success! */
  71. return (0);
  72. err0:
  73. /* Failure! */
  74. return (-1);
  75. }