21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

we ignore that because it will always be zero on failure or the size of the input buffer<br />

on success. Also note that PKCS #11–based calls tend to order their arguments differently<br />

from the way we do, and they will not generally wipe key material, as we do<br />

in our initialization and finalization routines.<br />

Because this API is developed with PKCS #11 in mind, it’s somewhat<br />

more low-level than it needs to be, and therefore is a bit difficult to use<br />

properly. First, you need to be sure the output buffer is big enough to<br />

hold the input; otherwise, you will have a buffer overflow. Second,<br />

you need to make sure the out argument always points to the first<br />

unused byte in the output buffer. Otherwise, you will keep overwriting<br />

the same data every time spc_ctr_update( ) outputs data.<br />

Here’s our implementation of spc_ctr_update( ), along with a helper function:<br />

static inline void ctr_increment(unsigned char *ctr) {<br />

unsigned char *x = ctr + SPC_CTR_BYTES;<br />

while (x-- != ctr) if (++(*x)) return;<br />

}<br />

int spc_ctr_update(SPC_CTR_CTX *ctx, unsigned char *in, size_t il, unsigned char<br />

*out) {<br />

int i;<br />

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

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

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

*out++ = *in++ ^ 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 />

for (i = 0; i < SPC_BLOCK_SZ / sizeof(int); i++)<br />

((int *)out)[i] ^= ((int *)in)[i];<br />

il -= SPC_BLOCK_SZ;<br />

in += SPC_BLOCK_SZ;<br />

out += SPC_BLOCK_SZ;<br />

}<br />

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

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

for (i = 0; i < il; i++)<br />

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

return 1;<br />

}<br />

To finalize either encryption or decryption, use the spc_ctr_final( ) call, which<br />

never needs to output anything, because CTR is a streaming mode:<br />

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