hmac_common.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #if GL_HMAC_NAME == 5
  10. #define HMAC_ALG md5
  11. #else
  12. #define HMAC_ALG _GLHMAC_CONCAT(sha, GL_HMAC_NAME)
  13. #endif
  14. #define GL_HMAC_CTX _GLHMAC_CONCAT(HMAC_ALG, _ctx)
  15. #define GL_HMAC_FN _GLHMAC_CONCAT(hmac_, HMAC_ALG)
  16. #define GL_HMAC_FN_INIT _GLHMAC_CONCAT(HMAC_ALG, _init_ctx)
  17. #define GL_HMAC_FN_BLOC _GLHMAC_CONCAT(HMAC_ALG, _process_block)
  18. #define GL_HMAC_FN_PROC _GLHMAC_CONCAT(HMAC_ALG, _process_bytes)
  19. #define GL_HMAC_FN_FINI _GLHMAC_CONCAT(HMAC_ALG, _finish_ctx)
  20. static void
  21. hmac_hash(const void* key, size_t keylen, const void* in, size_t inlen, int pad, void* resbuf) {
  22. struct GL_HMAC_CTX hmac_ctx;
  23. char block[GL_HMAC_BLOCKSIZE];
  24. memset(block, pad, sizeof block);
  25. memxor(block, key, keylen);
  26. GL_HMAC_FN_INIT(&hmac_ctx);
  27. GL_HMAC_FN_BLOC(block, sizeof block, &hmac_ctx);
  28. GL_HMAC_FN_PROC(in, inlen, &hmac_ctx);
  29. GL_HMAC_FN_FINI(&hmac_ctx, resbuf);
  30. }
  31. int GL_HMAC_FN(const void* key, size_t keylen, const void* in, size_t inlen, void* resbuf) {
  32. char optkeybuf[GL_HMAC_HASHSIZE];
  33. char innerhash[GL_HMAC_HASHSIZE];
  34. /* Ensure key size is <= block size. */
  35. if(keylen > GL_HMAC_BLOCKSIZE) {
  36. struct GL_HMAC_CTX keyhash;
  37. GL_HMAC_FN_INIT(&keyhash);
  38. GL_HMAC_FN_PROC(key, keylen, &keyhash);
  39. GL_HMAC_FN_FINI(&keyhash, optkeybuf);
  40. key = optkeybuf;
  41. /* zero padding of the key to the block size
  42. is implicit in the memxor. */
  43. keylen = sizeof optkeybuf;
  44. }
  45. /* Compute INNERHASH from KEY and IN. */
  46. hmac_hash(key, keylen, in, inlen, IPAD, innerhash);
  47. /* Compute result from KEY and INNERHASH. */
  48. hmac_hash(key, keylen, innerhash, sizeof innerhash, OPAD, resbuf);
  49. return 0;
  50. }