Creating an HMAC
To compute an HMAC
- Get a pointer to the Microsoft Cryptographic Service Provider (CSP) by calling CryptAcquireContext.
- Create a handle to an HMAChash object by calling CryptCreateHash. Pass CALG_HMAC in the Algid parameter. Pass the handle of a symmetric key in the hKey parameter. This symmetric key is the key used to compute the HMAC.
- Specify the type of hash to be used by calling CryptSetHashParam with the dwParam parameter set to the value HP_HMAC_INFO. The pbData parameter must point to an initialized HMAC_INFO structure.
- Call CryptHashData to begin computing the HMAC of the data. The first call to CryptHashData causes the key value to be combined using the XOR operator with the inner string and the data. The result of the XOR operation is hashed, and then the target data for the HMAC (pointed to by the pbData parameter passed in the call to CryptHashData) is hashed. If necessary, subsequent calls to CryptHashData may then be made to finish the hashing of the target data.
- Call CryptGetHashParam with the dwParam parameter set to HP_HASHVAL. This call causes the inner hash to be finished and the outer string to be combined using XOR with the key. The result of the XOR operation is hashed, and then the result of the inner hash (completed in the previous step) is hashed. The outer hash is then finished and returned in the pbData parameter and the length in the dwDataLen parameter.
Note Do not use the same symmetric (session) key for both message encryption and Message Authentication Code (MAC) generation. Using the same key for both greatly increases the risk of messages being decoded by attackers.