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 />

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

int i, ol;<br />

EVP_MD_CTX ctx;<br />

unsigned char result[EVP_MAX_MD_SIZE]; /* enough for any hash function */<br />

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

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

/* Note the extra parameter */<br />

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

EVP_DigestUpdate(&ctx, s1, strlen(s1));<br />

EVP_DigestUpdate(&ctx, s2, strlen(s2));<br />

/* Here, the context object is first. Notice the pointer to the output length */<br />

EVP_DigestFinal(&ctx, result, &ol);<br />

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

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

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

return 0;<br />

}<br />

Note particularly that EVP_DigestFinal( ) requires you to pass in a pointer to an integer,<br />

into which the output length is stored. You should use this value in your computations<br />

instead of hardcoding SHA1’s digest size, under the assumption that you<br />

might someday have to replace crypto algorithms in a hurry, in which case the digest<br />

size may change. For that reason, allocate EVP_MAX_MD_SIZE bytes for any buffer into<br />

which you store a message digest, even if some of that space may go unused.<br />

Alternatively, if you’d like to allocate a buffer of the correct size for output dynamically<br />

(which is a good idea if you’re space-constrained, because if SHA-512 is ever<br />

added to OpenSSL, EVP_MAX_MD_SIZE will become 512 bits), you can use the function<br />

EVP_MD_CTX_size( ), which takes a context object and returns the size of the digest.<br />

For example:<br />

#include <br />

#include <br />

#include <br />

#include <br />

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

int i, ol;<br />

EVP_MD_CTX ctx;<br />

unsigned char *result;<br />

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

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

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

EVP_DigestUpdate(&ctx, s1, strlen(s1));<br />

EVP_DigestUpdate(&ctx, s2, strlen(s2));<br />

if (!(result = (unsigned char *)malloc(EVP_MD_CTX_block_size(&ctx))))abort();<br />

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

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

Incrementally Hashing Data | 265

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

Saved successfully!

Ooh no, something went wrong!