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.

Both of these functions output the same number of bytes as were input, unless a<br />

memory allocation error occurs, in which case 0 is returned. The decryption routine<br />

is exactly the same as the encryption routine and is implemented by macro.<br />

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

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

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

#include <br />

#include <br />

unsigned char *spc_ofb_encrypt(unsigned char *key, size_t kl, unsigned char *nonce,<br />

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

SPC_OFB_CTX ctx;<br />

unsigned char *out;<br />

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

spc_ofb_init(&ctx, key, kl, nonce);<br />

spc_ofb_update(&ctx, in, il, out);<br />

spc_ofb_final(&ctx);<br />

return out;<br />

}<br />

#define spc_ofb_decrypt spc_ofb_encrypt<br />

Note that the previous code depends on the SPC_OFB_CTX data type and the incremental<br />

OFB interface, both discussed in the following sections.<br />

The incremental API<br />

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

typedef struct {<br />

SPC_KEY_SCHED ks;<br />

int ix;<br />

unsigned char nonce[SPC_BLOCK_SZ];<br />

} SPC_OFB_CTX;<br />

The ks field is an expanded version of the cipher key (block ciphers generally use a<br />

single key to derive multiple keys for internal use). The ix field is used to determine<br />

how much of the last block of keystream we have buffered (i.e., that hasn’t been<br />

used yet). The nonce field is really the buffer in which we store the current block of<br />

the keystream.<br />

To begin encrypting or decrypting, we need to initialize the mode. Initialization is<br />

the same operation for both encryption and decryption:<br />

void spc_ofb_init(SPC_OFB_CTX *ctx, unsigned char *key, size_t kl, unsigned char<br />

*nonce) {<br />

SPC_ENCRYPT_INIT(&(ctx->ks), key, kl);<br />

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