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.

eturn 0;<br />

}<br />

Every hash function that OpenSSLsupports has a similar API. In addition, every<br />

such function has an “all-in-one” API that allows you to combine the work of calls<br />

for initialization, updating, and finalization, obviating the need for a context object:<br />

unsigned char *SHA1(unsigned char *in, unsigned long len, unsigned char *out);<br />

This function returns a pointer to the out argument.<br />

Both the incremental API and the all-in-one API are very standard, even beyond<br />

OpenSSL. The reference versions of most hash algorithms look incredibly similar. In<br />

fact, Microsoft’s CryptoAPI for Windows provides a very similar API. Any of the<br />

Microsoft CSPs provide implementations of MD2, MD5, and SHA1. The following<br />

code is the CryptoAPI version of the OpenSSL code presented previously:<br />

#include <br />

#include <br />

#include <br />

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

BYTE *pbData;<br />

DWORD cbData = sizeof(DWORD), cbHashSize, i;<br />

HCRYPTHASH hSHA1;<br />

HCRYPTPROV hProvider;<br />

unsigned char *s1 = "Testing";<br />

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

CryptAcquireContext(&hProvider, 0, MS_DEF_PROV, PROV_RSA_FULL, 0);<br />

CryptCreateHash(hProvider, CALG_SHA1, 0, 0, &hSHA1);<br />

CryptHashData(hSHA1, s1, strlen(s1), 0);<br />

CryptHashData(hSHA1, s2, strlen(s2), 0);<br />

CryptGetHashParam(hSHA1, HP_HASHSIZE, (BYTE *)&cbHashSize, &cbData, 0);<br />

pbData = (BYTE *)LocalAlloc(LMEM_FIXED, cbHashSize);<br />

CryptGetHashParam(hSHA1, HP_HASHVAL, pbData, &cbHashSize, 0);<br />

CryptDestroyHash(hSHA1);<br />

CryptReleaseContext(hProvider, 0);<br />

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

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

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

LocalFree(pbData);<br />

return 0;<br />

}<br />

The preferred API for accessing hash functions from OpenSSL, though, is the EVP<br />

API, which provides a generic API to all of the hash functions OpenSSLsupports.<br />

The following code does the same thing as the first example with the EVP interface<br />

instead of the SHA1 interface:<br />

#include <br />

#include <br />

264 | 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!