21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Otherwise, you can use the HMAC implementation provided with this recipe in<br />

combination with any cryptographic hash function you have handy.<br />

Discussion<br />

Be sure to look at our generic recommendations for using a MAC<br />

(Recipe 6.9).<br />

Here’s an example of using OpenSSL’s incremental interface to hash two messages<br />

using SHA1:<br />

#include <br />

#include <br />

void spc_incremental_hmac(unsigned char *key, size_t keylen) {<br />

int i;<br />

HMAC_CTX ctx;<br />

unsigned int len;<br />

unsigned char out[20];<br />

HMAC_Init(&ctx, key, keylen, EVP_sha1( ));<br />

HMAC_Update(&ctx, "fred", 4);<br />

HMAC_Final(&ctx, out, &len);<br />

for (i = 0; i < len; i++) printf("%02x", out[i]);<br />

printf("\n");<br />

HMAC_Init(&ctx, 0, 0, 0);<br />

HMAC_Update(&ctx, "fred", 4);<br />

HMAC_Final(&ctx, out, &len);<br />

for (i = 0; i < len; i++) printf("%02x", out[i]);<br />

printf("\n");<br />

HMAC_cleanup(&ctx); /* Remove key from memory */<br />

}<br />

To reset the HMAC context object, we call HMAC_Init( ), passing in zeros (NULLs) in<br />

place of the key, key length, and digest type to use. The NULL argument when initializing<br />

in OpenSSLgenerally means “I’m not supplying this value right now; use what<br />

you already have.”<br />

The following example shows an implementation of the same code provided for<br />

OpenSSL, this time using CryptoAPI (with the exception of resetting the context,<br />

because CryptoAPI actually requires a new one to be created). This implementation<br />

requires the use of the code in Recipe 5.26 to convert raw key data into an HCRYPTKEY<br />

object as required by CryptCreateHash( ). Note the difference in the arguments<br />

required between spc_incremental_hmac( ) as implemented for OpenSSL, and<br />

SpcIncrementalHMAC( ) as implemented for CryptoAPI. The latter requires an additional<br />

argument that specifies the encryption algorithm for the key. Although the<br />

information is never really used, CryptoAPI insists on tying an encryption algorithm<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

Using HMAC | 277

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!