Need example of HMAC SHA

Werner Koch wk at
Sun Aug 7 14:07:02 CEST 2005

On Fri, 5 Aug 2005 12:34:01 -0700 (PDT), Heather Shaw said:

> I am a newbie to the gnupg software and am needing to
> utilize the HMAC/SHA features of the libcrypt package.
> Does someone have a quick & dirty example of this. 
> Most of the examples I have found use the AES cipher
> and in looking through the documentation, I have been
> confused on how to implement the HMAC/SHA.  I am
> trying to just encrypt/decrypt a basic string. 

The HMAC construction requires a hash algorithnm and not a cipher
algorithm.  Some code snippets:

Create a hash context:

	  err = gcry_md_open (&ctx->send_mac, ctx->mac_algo,
	  if (!err)
	    err = gcry_md_setkey (ctx->send_mac,
				  gsti_bstr_data (ctx->kex.mac_f),
				  gsti_bstr_length (ctx->kex.mac_f));

mac_algo might be GCRY_MD_SHA1.  Then hash the data and finally:

static size_t
generate_mac (gsti_ctx_t ctx, struct packet_buffer_s *pkt, u32 seqno)
  gcry_md_hd_t md;
  byte buf[4];
  byte *p = pkt->packet_buffer;
  size_t n = 5 + pkt->payload_len + pkt->padding_len;

  if (!ctx->send_mac)
    return 0;			/* no MAC requested */

  if (gcry_md_copy (&md, ctx->send_mac))
    return 0;
  buf[0] = seqno >> 24;
  buf[1] = seqno >> 16;
  buf[2] = seqno >> 8;
  buf[3] = seqno;
  gcry_md_write (md, buf, 4);
  gcry_md_write (md, p, n);
  gcry_md_final (md);
  memcpy (p + n, gcry_md_read (md, 0), ctx->mac_len);
  gcry_md_close (md);
  return ctx->mac_len;

That example is from an Secure Shell library (GSTI).



More information about the Gnupg-devel mailing list