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.

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_ctr_encrypt(unsigned char *key, size_t kl, unsigned char *nonce,<br />

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

SPC_CTR_CTX ctx;<br />

unsigned char *out;<br />

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

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

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

spc_ctr_final(&ctx);<br />

return out;<br />

}<br />

#define spc_ctr_decrypt spc_ctr_encrypt<br />

Note that this code depends on the SPC_CTR_CTX data type and the incremental CTR<br />

interface, both discussed in the following sections. In particular, the nonce size varies<br />

depending on the value of the SPC_CTR_BYTES macro (introduced in the next subsection).<br />

The incremental API<br />

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

typedef struct {<br />

SPC_KEY_SCHED ks;<br />

int ix;<br />

unsigned char ctr[SPC_BLOCK_SZ];<br />

unsigned char ksm[SPC_BLOCK_SZ];<br />

} SPC_CTR_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 ctr block holds the plaintext used to generate keystream blocks. Buffered<br />

keystream is held in ksm.<br />

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

the same operation for both encryption and decryption, and it depends on a statically<br />

defined value SPC_CTR_BYTES, which is used to compute the nonce size.<br />

#define SPC_CTR_BYTES 6<br />

Using a Generic CTR Mode Implementation | 199<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!