21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

#include <br />

#include <br />

#include <br />

/* Returns 0 when malloc() fails. */<br />

unsigned char *spc_digest_message(EVP_MD *type, unsigned char *in,<br />

unsigned long n, unsigned int *outlen) {<br />

EVP_MD_CTX ctx;<br />

unsigned char *ret;<br />

EVP_DigestInit(&ctx, type);<br />

EVP_DigestUpdate(&ctx, in, n);<br />

if (!(ret = (unsigned char *)malloc(EVP_MD_CTX_size(&ctx))) return 0;<br />

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

return ret;<br />

}<br />

Here’s a simple example that uses the previous wrapper:<br />

#include <br />

#include <br />

#include <br />

#include <br />

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

int i;<br />

unsigned int ol;<br />

unsigned char *s = "Testing...1...2...3...";<br />

unsigned char *r;<br />

r = spc_digest_message(EVP_sha1( ), s, strlen(s), &ol);<br />

printf("SHA1(\"%s\") = ", s);<br />

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

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

free(r);<br />

return 0;<br />

}<br />

Such a wrapper can be adapted easily to any incremental hashing API, simply by<br />

changing the names of the functions and the underlying data type, and removing the<br />

first argument of the wrapper if it is not necessary. Here is the same wrapper implemented<br />

using Microsoft’s CryptoAPI:<br />

#include <br />

#include <br />

BYTE *SpcDigestMessage(ALG_ID Algid, BYTE *pbIn, DWORD cbIn, DWORD *cbOut) {<br />

BYTE *pbOut;<br />

DWORD cbData = sizeof(DWORD);<br />

HCRYPTHASH hHash;<br />

HCRYPTPROV hProvider;<br />

268 | Chapter 6: Hashes and Message Authentication<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!