hmac_common.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <string.h>
  2. #include "sha256.h"
  3. #include "memxor.h"
  4. #define IPAD 0x36
  5. #define OPAD 0x5c
  6. /* Concatenate two preprocessor tokens. */
  7. #define _GLHMAC_CONCAT_(prefix, suffix) prefix##suffix
  8. #define _GLHMAC_CONCAT(prefix, suffix) _GLHMAC_CONCAT_(prefix, suffix)
  9. #define HMAC_ALG _GLHMAC_CONCAT(sha, GL_HMAC_NAME)
  10. #define GL_HMAC_CTX _GLHMAC_CONCAT(HMAC_ALG, _ctx)
  11. #define GL_HMAC_FN _GLHMAC_CONCAT(hmac_, HMAC_ALG)
  12. #define GL_HMAC_FN_INIT _GLHMAC_CONCAT(HMAC_ALG, _init_ctx)
  13. #define GL_HMAC_FN_BLOC _GLHMAC_CONCAT(HMAC_ALG, _process_block)
  14. #define GL_HMAC_FN_PROC _GLHMAC_CONCAT(HMAC_ALG, _process_bytes)
  15. #define GL_HMAC_FN_FINI _GLHMAC_CONCAT(HMAC_ALG, _finish_ctx)
  16. static void
  17. hmac_hash(const void* key, size_t keylen, const void* in, size_t inlen, int pad, void* resbuf) {
  18. struct GL_HMAC_CTX hmac_ctx;
  19. char block[GL_HMAC_BLOCKSIZE];
  20. memset(block, pad, sizeof block);
  21. memxor(block, key, keylen);
  22. GL_HMAC_FN_INIT(&hmac_ctx);
  23. GL_HMAC_FN_BLOC(block, sizeof block, &hmac_ctx);
  24. GL_HMAC_FN_PROC(in, inlen, &hmac_ctx);
  25. GL_HMAC_FN_FINI(&hmac_ctx, resbuf);
  26. }
  27. int GL_HMAC_FN(const void* key, size_t keylen, const void* in, size_t inlen, void* resbuf) {
  28. char optkeybuf[GL_HMAC_HASHSIZE];
  29. char innerhash[GL_HMAC_HASHSIZE];
  30. /* Ensure key size is <= block size. */
  31. if(keylen > GL_HMAC_BLOCKSIZE) {
  32. struct GL_HMAC_CTX keyhash;
  33. GL_HMAC_FN_INIT(&keyhash);
  34. GL_HMAC_FN_PROC(key, keylen, &keyhash);
  35. GL_HMAC_FN_FINI(&keyhash, optkeybuf);
  36. key = optkeybuf;
  37. /* zero padding of the key to the block size
  38. is implicit in the memxor. */
  39. keylen = sizeof optkeybuf;
  40. }
  41. /* Compute INNERHASH from KEY and IN. */
  42. hmac_hash(key, keylen, in, inlen, IPAD, innerhash);
  43. /* Compute result from KEY and INNERHASH. */
  44. hmac_hash(key, keylen, innerhash, sizeof innerhash, OPAD, resbuf);
  45. return 0;
  46. }