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.

One very safe way to use a cryptographic hash function in a cryptographic pseudorandom<br />

number generator is to use HMAC in counter mode, as discussed in Recipe<br />

6.10. Here we implement a generator based on the HMAC-SHA1 implementation<br />

from Recipe 6.10. You should be able to adapt this code easily to any HMAC implementation<br />

you want to use.<br />

/* NOTE: This code should be augmented to reseed after each request<br />

/* for pseudo-random data, as discussed in Recipe 11.6<br />

/*<br />

#ifndef WIN32<br />

#include <br />

#include <br />

#else<br />

#include <br />

#endif<br />

/* If MAC operations fail, you passed in a bad key size or you are using a hardware<br />

* API that failed. In that case, be sure to perform error checking.<br />

*/<br />

#define MAC_OUT_SZ 20<br />

typedef struct {<br />

SPC_HMAC_CTX ctx;<br />

unsigned char ctr[MAC_OUT_SZ];<br />

unsigned char lo[MAC_OUT_SZ]; /* Leftover block of output */<br />

int ix; /* index into lo. */<br />

} SPC_MPRNG_CTX;<br />

#ifndef WIN32<br />

static pthread_mutex_t spc_mprng_mutex = PTHREAD_MUTEX_INITIALIZER;<br />

#define SPC_MPRNG_LOCK( ) pthread_mutex_lock(&spc_mprng_mutex)<br />

#define SPC_MPRNG_UNLOCK( ) pthread_mutex_unlock(&spc_mprng_mutex)<br />

#else<br />

static HANDLE hSpcMPRNGMutex;<br />

#define SPC_MPRNG_LOCK( ) WaitForSingleObject(hSpcMPRNGMutex, INFINITE)<br />

#define SPC_MPRNG_UNLOCK( ) ReleaseMutex(hSpcMPRNGMutex)<br />

#endif<br />

static void spc_increment_mcounter(SPC_MPRNG_CTX *prng) {<br />

int i = MAC_OUT_SZ;<br />

}<br />

while (i--)<br />

if (++prng->ctr[i])<br />

return;<br />

void spc_mprng_init(SPC_MPRNG_CTX *prng, unsigned char *seed, int l) {<br />

SPC_MPRNG_LOCK( );<br />

SPC_HMAC_Init(&(prng->ctx), seed, l);<br />

memset(prng->ctr, 0, MAC_OUT_SZ);<br />

prng->ix = 0;<br />

Using an Application-Level Generator | 589<br />

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

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!