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.

See Also<br />

Implementations of SHA-256 and SHA-512 from Aaron Gifford: http://www.<br />

aarongifford.com/computers/sha.html<br />

Recipes 6.7, 6.8<br />

6.6 Hashing a Single String<br />

<strong>Problem</strong><br />

You have a single string of data that you would like to hash, and you don’t like the<br />

complexity of the incremental interface.<br />

Solution<br />

Use an “all-in-one” interface, if available, or write your own wrapper, as shown in<br />

the “Discussion” section.<br />

Discussion<br />

Hash functions are not secure by themselves—not for a password system,<br />

not for message authentication, not for anything! If you do need a<br />

hash function by itself, be sure to at least protect against length extension<br />

attacks, as described in Recipe 6.7.<br />

Complexity can certainly get you in trouble, and a simpler API can be better. While<br />

not every API provides a single function that can perform a cryptographic hash,<br />

many of them do. For example, OpenSSLprovides an all-in-one API for each of the<br />

message digest algorithms it supports:<br />

unsigned char *MD2(unsigned char *in, unsigned long n, unsigned char *md);<br />

unsigned char *MD4(unsigned char *in, unsigned long n, unsigned char *md);<br />

unsigned char *MD5(const unsigned char *in, unsigned long n, unsigned char *md);<br />

unsigned char *MDC2(const unsigned char *in, unsigned long n, unsigned char *md);<br />

unsigned char *RIPEMD160(const unsigned char *in, unsigned long n,<br />

unsigned char *md);<br />

unsigned char *SHA1(const unsigned char *in, unsigned long n, unsigned char *md);<br />

APIs in this style are commonly seen, even outside the context of OpenSSL. Note<br />

that these functions require you to pass in a buffer into which the digest is placed,<br />

but they also return a pointer to that same buffer.<br />

OpenSSLdoes not provide an all-in-one API for calculating message digests with the<br />

EVP interface. However, here’s a simple wrapper that even allocates its result with<br />

malloc( ):<br />

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

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

Hashing a Single String | 267

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

Saved successfully!

Ooh no, something went wrong!