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.

5.9 Using a Generic CTR Mode Implementation<br />

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

You want to use counter (CTR) mode and your library doesn’t provide an interface,<br />

or you want to use a more high-level interface than your library provides. Alternatively,<br />

you would like a portable CTR interface, or you have only a block cipher<br />

implementation and you would like to use CTR mode.<br />

Solution<br />

CTR mode encrypts by generating keystream, then combining the keystream with<br />

the plaintext via XOR. This mode generates keystream one block at a time by<br />

encrypting plaintexts that are the same, except for an ever-changing counter, as<br />

shown in Figure 5-4. Generally, the counter value starts at zero and is incremented<br />

sequentially.<br />

Few libraries provide a CTR implementation, because it has only recently come into<br />

favor, despite the fact that it is a very old mode with great properties. We provide<br />

code implementing this mode in the following “Discussion” section.<br />

Discussion<br />

1st counter block<br />

P 1<br />

Figure 5-4. Counter (CTR) mode<br />

Start<br />

E K<br />

C 1<br />

You should probably use a higher-level abstraction, such as the one<br />

discussed in Recipe 5.16. Use a raw mode only when absolutely necessary,<br />

because there is a huge potential for introducing asecurity vulnerability<br />

by accident. If you still want to use CTR mode, be sure to use a<br />

message authentication code with it.<br />

CTR mode is a stream-based mode. Encryption occurs by XOR’ing the keystream<br />

bytes with the plaintext bytes. The keystream is generated one block at a time by<br />

Using a Generic CTR Mode Implementation | 197<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

P 11<br />

Start +10<br />

E K<br />

. . . . . .<br />

C 11<br />

10th counter block<br />

= XOR

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!