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.

typedef struct {<br />

SPC_KEY_SCHED ks;<br />

int ix;<br />

int pad;<br />

unsigned char iv[SPC_BLOCK_SZ];<br />

unsigned char ctbuf[SPC_BLOCK_SZ];<br />

} SPC_CBC_CTX;<br />

The ks field is an expanded version of the cipher key. The ix field is basically used to<br />

determine how much data is needed before we have processed data that is a multiple<br />

of the block length. The pad field specifies whether the API needs to add padding or<br />

should expect messages to be exactly block-aligned. The iv field is used to store the<br />

initialization vector for the next block of encryption. The ctbuf field is only used in<br />

decryption to cache ciphertext until we have enough to fill a block.<br />

Incremental initialization<br />

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

different for each mode. Here are the functions for initializing an SPC_CBC_CTX object:<br />

void spc_cbc_encrypt_init(SPC_CBC_CTX *ctx, unsigned char *key, size_t kl,<br />

unsigned char *iv) {<br />

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

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

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

ctx->ix = 0;<br />

ctx->pad = 1;<br />

}<br />

void spc_cbc_decrypt_init(SPC_CBC_CTX *ctx, unsigned char *key, size_t kl,<br />

unsigned char *iv) {<br />

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

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

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

ctx->ix = 0;<br />

ctx->pad = 1;<br />

}<br />

These functions are identical, except that they call the appropriate method for keying,<br />

which may be different depending on whether we’re encrypting or decrypting.<br />

Both of these functions erase the key that you pass in!<br />

Note that the initialization vector (IV) must be selected randomly. You should also<br />

avoid encrypting more than about 240 blocks of data using a single key. See Recipe 4.9<br />

for more on initialization vectors.<br />

Now we can add data as we get it using the spc_cbc_encrypt_update( ) and spc_cbc_<br />

decrypt_update( ) functions. These functions are particularly useful when a message<br />

comes in pieces. You’ll get the same results as if the message had come in all at once.<br />

When you wish to finish encrypting or decrypting, you call spc_cbc_encrypt_final( )<br />

or spc_cbc_decrypt_final( ), as appropriate.<br />

Using a Generic CBC Mode Implementation | 179<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!