21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

These two functions erase the key from memory before exiting. You<br />

may want to have them erase the plaintext as well.<br />

Here’s the implementation of the above interface:<br />

#include <br />

#include <br />

unsigned char *spc_cbc_encrypt(unsigned char *key, size_t kl, unsigned char *iv,<br />

unsigned char *in, size_t il, size_t *ol) {<br />

SPC_CBC_CTX ctx;<br />

size_t tmp;<br />

unsigned char *result;<br />

if (!(result = (unsigned char *)malloc(((il / SPC_BLOCK_SZ) * SPC_BLOCK_SZ) +<br />

SPC_BLOCK_SZ))) return 0;<br />

spc_cbc_encrypt_init(&ctx, key, kl, iv);<br />

spc_cbc_encrypt_update(&ctx, in, il, result, &tmp);<br />

spc_cbc_encrypt_final(&ctx, result+tmp, ol);<br />

*ol += tmp;<br />

return result;<br />

}<br />

unsigned char *spc_cbc_decrypt(unsigned char *key, size_t kl, unsigned char *iv,<br />

unsigned char *in, size_t il, size_t *ol) {<br />

int success;<br />

size_t tmp;<br />

SPC_CBC_CTX ctx;<br />

unsigned char *result;<br />

if (!(result = (unsigned char *)malloc(il))) return 0;<br />

spc_cbc_decrypt_init(&ctx, key, kl, iv);<br />

spc_cbc_decrypt_update(&ctx, in, il, result, &tmp);<br />

if (!(success = spc_cbc_decrypt_final(&ctx, result+tmp, ol))) {<br />

*ol = 0;<br />

spc_memset(result, 0, il);<br />

free(result);<br />

return 0;<br />

}<br />

*ol += tmp;<br />

result = (unsigned char *)realloc(result, *ol);<br />

return result;<br />

}<br />

Note that this code depends on the SPC_CBC_CTX data type, as well as the incremental<br />

CBC interface, neither of which we have yet discussed.<br />

SPC_CBC_CTX data type<br />

Let’s look at the SPC_CBC_CTX data type. It’s defined as:<br />

178 | Chapter 5: Symmetric Encryption<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!