hmac_common.h 1.9 KB

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