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.

eturn the number of valid bytes in the final block of data, which could be anything<br />

from zero to one less than the block length.<br />

5.12 Precomputing Keystream in OFB, CTR, CCM,<br />

or CWC Modes (or with Stream Ciphers)<br />

<strong>Problem</strong><br />

You want to save computational resources when data is actually flowing over a network<br />

by precomputing keystream so that encryption or decryption will consist<br />

merely of XOR’ing data with the precomputed keystream.<br />

Solution<br />

If your API has a function that performs keystream generation, use that. Otherwise,<br />

call the encryption routine, passing in N bytes set to 0, where N is the number of<br />

bytes of keystream you wish to precompute.<br />

Discussion<br />

Most cryptographic APIs do not have an explicit way to precompute keystream for<br />

cipher modes where such precomputation makes sense. Fortunately, any byte XOR’d<br />

with zero returns the original byte. Therefore, to recover the keystream, we can<br />

“encrypt” a string of zeros. Then, when we have data that we really do wish to<br />

encrypt, we need only XOR that data with the stored keystream.<br />

If you have the source for the encryption algorithm, you can remove the final XOR<br />

operation to create a keystream-generating function. For example, the spc_ctr_<br />

update( ) function from Recipe 5.9 can be adapted easily into the following keystream<br />

generator:<br />

int spc_ctr_keystream(SPC_CTR_CTX *ctx, size_t il, unsigned char *out) {<br />

int i;<br />

if (ctx->ix) {<br />

while (ctx->ix) {<br />

if (!il--) return 1;<br />

*out++ = ctx->ksm[ctx->ix++];<br />

ctx->ix %= SPC_BLOCK_SZ;<br />

}<br />

}<br />

if (!il) return 1;<br />

while (il >= SPC_BLOCK_SZ) {<br />

SPC_DO_ENCRYPT(&(ctx->ks), ctx->ctr, out);<br />

ctr_increment(ctx->ctr);<br />

il -= SPC_BLOCK_SZ;<br />

Precomputing Keystream in OFB, CTR, CCM, or CWC Modes (or with Stream Ciphers) | 207<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!