hmac-common.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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,
  22. const void *in, size_t inlen,
  23. int pad, void *resbuf)
  24. {
  25. struct GL_HMAC_CTX hmac_ctx;
  26. char block[GL_HMAC_BLOCKSIZE];
  27. memset (block, pad, sizeof block);
  28. memxor (block, key, keylen);
  29. GL_HMAC_FN_INIT (&hmac_ctx);
  30. GL_HMAC_FN_BLOC (block, sizeof block, &hmac_ctx);
  31. GL_HMAC_FN_PROC (in, inlen, &hmac_ctx);
  32. GL_HMAC_FN_FINI (&hmac_ctx, resbuf);
  33. }
  34. int
  35. GL_HMAC_FN (const void *key, size_t keylen,
  36. const void *in, size_t inlen, void *resbuf)
  37. {
  38. char optkeybuf[GL_HMAC_HASHSIZE];
  39. char innerhash[GL_HMAC_HASHSIZE];
  40. /* Ensure key size is <= block size. */
  41. if (keylen > GL_HMAC_BLOCKSIZE)
  42. {
  43. struct GL_HMAC_CTX keyhash;
  44. GL_HMAC_FN_INIT (&keyhash);
  45. GL_HMAC_FN_PROC (key, keylen, &keyhash);
  46. GL_HMAC_FN_FINI (&keyhash, optkeybuf);
  47. key = optkeybuf;
  48. /* zero padding of the key to the block size
  49. is implicit in the memxor. */
  50. keylen = sizeof optkeybuf;
  51. }
  52. /* Compute INNERHASH from KEY and IN. */
  53. hmac_hash (key, keylen, in, inlen, IPAD, innerhash);
  54. /* Compute result from KEY and INNERHASH. */
  55. hmac_hash (key, keylen, innerhash, sizeof innerhash, OPAD, resbuf);
  56. return 0;
  57. }