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.

Note that this code depends on the SPC_CFB_CTX data type and the incremental CFB<br />

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

The incremental API<br />

Let’s look at the SPC_CFB_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_CFB_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 keystream we have buffered. The nonce field is really the buffer in which<br />

we store the input to the next encryption, and it is the place where intermediate keystream<br />

bytes are stored.<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_cfb_init(SPC_CFB_CTX *ctx, unsigned char *key, size_t kl, unsigned char<br />

*nonce) {<br />

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

spc_memset(key,0, kl);<br />

memcpy(ctx->nonce, nonce, SPC_BLOCK_SZ);<br />

ctx->ix = 0;<br />

}<br />

Note again that we remove the key from memory during this operation.<br />

Never use the same nonce (often called an IV in this context; see Recipe 4.9) twice<br />

with a single key. To implement that recommendation effectively, never reuse a key.<br />

Alternatively, pick a random starting IV each time you key, and never output more<br />

than about 2 40 blocks using a single key.<br />

Now we can add data as we get it using the spc_cfb_encrypt_update( ) or spc_cfb_<br />

decrypt_update( ) function, as appropriate. These functions are particularly useful<br />

when a message may arrive in pieces. You’ll get the same results as if it all arrived at<br />

once. When you want to finish encrypting or decrypting, call spc_cfb_final( ).<br />

You’re responsible for making sure the proper init, update, and final<br />

calls are made, and that they do not happen out of order.<br />

Using a Generic CFB Mode Implementation | 189<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!