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_ofb_update( ) outputs.<br />

Here’s our implementation of spc_ofb_update( ):<br />

int spc_ofb_update(SPC_OFB_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->nonce[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->nonce, ctx->nonce);<br />

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

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

il -= SPC_BLOCK_SZ;<br />

in += SPC_BLOCK_SZ;<br />

out += SPC_BLOCK_SZ;<br />

}<br />

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

for (i = 0; i < il; i++) *out++ = *in++ ^ ctx->nonce[ctx->ix++];<br />

return 1;<br />

}<br />

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

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

int spc_ofb_final(SPC_OFB_CTX *ctx) {<br />

spc_memset(&ctx, 0, sizeof(SPC_OFB_CTX));<br />

return 1;<br />

}<br />

See Also<br />

Recipes 4.9, 5.4, 5.5, 5.16, 13.2<br />

196 | Chapter 5: Symmetric Encryption<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!