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.

if (!(vfy = (unsigned char *)malloc(dlen))) return 0;<br />

EVP_DigestFinal(&ctx, vfy, &outlen);<br />

in += dlen;<br />

for (i = 0; i < dlen; i++)<br />

if (vfy[i] != toverify[i + dlen]) {<br />

free(vfy);<br />

return 0;<br />

}<br />

free(vfy);<br />

return 1;<br />

}<br />

The first function, spc_create_nonced_digest( ), automatically selects a nonce from<br />

the OpenSSLrandom number generator and returns twice the digest size in output,<br />

where the first digest-sized block is the nonce and the second is the hash. The second<br />

function, spc_verify_nonced_digest( ), takes data consisting of a nonce concatenated<br />

with a hash value, and returns 1 if the hash validates, and 0 otherwise.<br />

Two macros can make extracting the nonce and the hash easier:<br />

#include <br />

#include <br />

#include <br />

/* Here, l is the output length of spc_create_nonced_digest( ) */<br />

#define spc_extract_nonce(l, s) (s)<br />

#define spc_extract_digest(l, s) ((s)+((l) / 2))<br />

Here’s a sample program using this API:<br />

int main(int argc, char *argv[ ]) {<br />

unsigned int i, ol;<br />

unsigned char *s = "Testing hashes with nonces.";<br />

unsigned char *dgst, *nonce, *ret;<br />

ret = spc_create_nonced_digest(EVP_sha1( ), s, strlen(s), &ol);<br />

nonce = spc_extract_nonce(ol, ret);<br />

dgst = spc_extract_digest(ol, ret);<br />

printf("Nonce = ");<br />

for(i = 0; i < ol / 2; i++)<br />

printf("%02x", nonce[i]);<br />

printf("\nSHA1-Nonced(Nonce, \"%s\") = \n\t", s);<br />

for(i = 0; i < ol / 2; i++)<br />

printf("%02x", dgst[i]);<br />

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

if (spc_verify_nonced_digest(EVP_sha1( ), s, strlen(s), ret))<br />

printf("Recalculation verified integrity.\n");<br />

else<br />

printf("Recalculation FAILED to match.\n");<br />

return 0;<br />

}<br />

See Also<br />

Recipe 6.7<br />

Using a Nonce to Protect Against Birthday Attacks | 273<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!