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.

Libraries with cryptographic hash functions tend to support incremental operation<br />

using a standard structure. In fact, this structure is standardized for cryptographic<br />

hardware APIs in PKCS (Public Key Cryptography Standard) #11. There are four<br />

steps:<br />

1. Allocate a context object. The context object holds the internal state of the hash<br />

until data processing is complete. The type can be specific to the hash function,<br />

or it can be a single type that works for all hash functions in a library (such as<br />

the EVP_MD_CTX type in the OpenSSLlibrary or HCRYPTHASH in Microsoft’s CryptoAPI).<br />

2. Initialize the context object, resetting internal parameters of the hash function.<br />

Generally, this function takes no arguments other than a pointer to the context<br />

object, unless you’re using a generic API, in which case you will need to specify<br />

which hash algorithm to use.<br />

3. “Update” the context object by passing in data to be hashed and the associated<br />

length of that input. The results of the hash will be dependent on the order of<br />

the data you pass, but you can pass in all the partial data you wish. That is, calling<br />

the update routine with the string “he” then “llo” would produce the same<br />

results as calling it once with the string “hello”. The update function generally<br />

takes the context object, the data to process, and the associated length of that<br />

data as arguments.<br />

4. “Finalize” the context object and produce the message digest. Most APIs take as<br />

arguments the context object and a buffer into which the message digest is<br />

placed.<br />

The OpenSSLAPI has both a single generic interface to all its hash functions and a<br />

separate API for each hash function. Here’s an example using the SHA1 API:<br />

#include <br />

#include <br />

#include <br />

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

int i;<br />

SHA_CTX ctx;<br />

unsigned char result[SHA_DIGEST_LENGTH]; /* SHA1 has a 20-byte digest. */<br />

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

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

SHA1_Init(&ctx);<br />

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

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

/* Yes, the context object is last. */<br />

SHA1_Final(result, &ctx);<br />

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

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

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

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

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

Incrementally Hashing Data | 263

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

Saved successfully!

Ooh no, something went wrong!