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.

*/<br />

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

while (ctx->ix < SPC_BLOCK_SZ) --il, ctx->iv[ctx->ix++] ^= *in++;<br />

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

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

((unsigned int *)out)[i] = ((unsigned int *)(ctx->iv))[i];<br />

out += SPC_BLOCK_SZ;<br />

}<br />

/* Operate on word-sized chunks, because it's easy to do so. You might gain a<br />

* couple of cycles per loop by unrolling and getting rid of i if you know your<br />

* word size a priori.<br />

*/<br />

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

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

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

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

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

((unsigned int *)out)[i] = ((unsigned int *)(ctx->iv))[i];<br />

out += SPC_BLOCK_SZ;<br />

in += SPC_BLOCK_SZ;<br />

il -= SPC_BLOCK_SZ;<br />

}<br />

/* Deal with leftovers... one byte at a time is fine. */<br />

for (i = 0; i < il; i++) ctx->iv[i] ^= in[i];<br />

ctx->ix = il;<br />

if (ol) *ol = out-start;<br />

return 1;<br />

}<br />

The following spc_cbc_encrypt_final( ) function outputs any remaining data and<br />

securely wipes the key material in the context, along with all the intermediate state.<br />

If padding is on, it will output one block. If padding is off, it won’t output anything.<br />

If padding is off and the total length of the input wasn’t a multiple of the block size,<br />

spc_cbc_encrypt_final( ) will return 0. Otherwise, it will always succeed.<br />

int spc_cbc_encrypt_final(SPC_CBC_CTX *ctx, unsigned char *out, size_t *ol) {<br />

int ret;<br />

unsigned char pad;<br />

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

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

while (ctx->ix < SPC_BLOCK_SZ) ctx->iv[ctx->ix++] ^= pad;<br />

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

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

if(ol) *ol = SPC_BLOCK_SZ;<br />

return 1;<br />

}<br />

if(ol) *ol = 0;<br />

ret = !(ctx->ix);<br />

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

return ret;<br />

}<br />

182 | 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!