HMAC with gcrypt

On my way towards a working RFC4226 implementation, I needed an HMAC implementation.  I originally started working on my own, but then I was going to need a working suite of hash functions.  Obviously I should use some well-known cryptographic libraries for these hash functions.  I found libgcrypt, part of GPG.  I didn't expect for some reason to find that HMAC was already implemented in this suite as well.

I decided to use their HMAC to have better integration with their hash functions and for assured functionality.  This turned out to be a good thing because it took lots ot tinkering to get my digest to match RFC 4231. Skipping the dirty work, here are the important functions (in order):

   gcry_check_version(GCRYPT_VERSION);
   gcry_control(GCRYCTL_SUSPEND_SECMEM_WARN);
   gcry_control(GCRYCTL_INIT_SECMEM, 1);
   gcry_control(GCRYCTL_RESUME_SECMEM_WARN);
   gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
   gcry_md_open(&hash_handle_, hash_type,
      GCRY_MD_FLAG_SECURE| GCRY_MD_FLAG_HMAC);
   gcry_md_setkey(hash_handle_, key, key_length);
   gcry_md_write(hash_handle_, message, length);
   gcry_md_read(hash_handle_, 0);

The hardest part was getting the key to be correct.  I take the hexadecimal description of the key, and convert it to an array of unsigned chars for safety (signedness is notorious for messing up values). This is all it takes (more or less) to get a working HMAC implementation.  I arraned things more nicely in preparation for the full-blown RFC 4226 code.

No comments: