开发者

How to calculate HMAC SHA on Windows?

I need to calculate HMAC SHA in my program on Windows. This program earlier used to run on linux where it used the openssl. Now I need to port it to Windows, but I am not sure if Windows platform SDK provides any means to calculate the HMAC SHA.

I cam across the following link on msdn, but I am not sure - http://msdn.microsoft.com/en-us/library/aa3开发者_开发知识库82453(v=VS.85).aspx.

Let me know what is the best way ahead for me. The existing program is in C.


You can use CryptImportKeyto get your key into the Windows Cryptographic Service Provider. Then follow the MSDN example HMAC code. The trick to getting your key into the CSP is to make a struct to hold 3 things: a BLOBHEADER, a DWORD for the length, and char[] for the key. I will presume you have the raw key data so it would look something like:

struct KeyData
{
  BLOBHEADER hdr;
  unsigned long keyLength;
  unsigned char key[128];
};

void ComputeHash()
{
  HCRYPTPROV cryptoProvider = 0;
  HCRYPTKEY cryptKey = 0;
  KeyData kd;
  kd.hdr.aiKeyAlg = CALG_RC2;
  kd.hdr.bType = PLAINTEXTKEYBLOB;
  kd.hdr.bVersion = CUR_BLOB_VERSION;
  kd.hdr.reserved = 0;
  kd.keyLength = 128;
  /* set your key data here */

  /* get a crypto provider - See the microsoft references 
     This example selects "Microsoft AES Cryptographic Provider"
     which supports SHA-256
  */
  CryptAcquireContext(&cryptoProvider, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);

  CryptImportKey(cryptoProvider, reinterpret_cast<BYTE*>(&kd), sizeof(kd),0, CRYPT_IPSEC_HMAC_KEY, &cryptKey);
  /* use cryptKey in the call to CryptCreateHash when you create your CALG_HMAC */
}

Make sure to replace the lengths with the actual length of your key.


If you have the key explicitly, it may be easier to program HMAC explicitly out of two invocations of the SHA primitive than to try to get make the key known to the Windows crypto API. HMAC itself is specified in RFC 2104, and Windows can do the SHA hashes for you with CryptCreateHash, CryptHashData and CryptGetHashParam.


IF you want to use the API included in the OS then the link you found is ok - more information see http://msdn.microsoft.com/en-us/library/aa380255%28v=vs.85%29.aspx

Or are you looking for some 3rd-party lib with some specific features ? if you are already familiar with with openssl, it is available for Windows too... see http://www.slproweb.com/products/Win32OpenSSL.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜