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.

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

return 1;<br />

}<br />

Finalizing CBC-mode decryption is done with spc_cbc_decrypt_final( ), whose listing<br />

follows. This function will return 1 if there are no problems or 0 if the total input<br />

length is not a multiple of the block size or if padding is on and the padding is incorrect.<br />

If the call is successful and padding is on, the function will write into the output<br />

buffer anywhere from 0 to SPC_BLOCK_SZ bytes. If padding is off, a successful function<br />

will always write SPC_BLOCK_SZ bytes into the output buffer.<br />

As with spc_cbc_encrypt_final( ), this function will securely erase the contents of<br />

the context object before returning.<br />

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

unsigned int i;<br />

unsigned char pad;<br />

if (ctx->ix != SPC_BLOCK_SZ) {<br />

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

/* If there was no input, and there's no padding, then everything is OK. */<br />

spc_memset(&(ctx->ks), 0, sizeof(SPC_KEY_SCHED));<br />

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

return (!ctx->ix && !ctx->pad);<br />

}<br />

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

SPC_DO_DECRYPT(&(ctx->ks), ctx->ctbuf, out);<br />

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

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

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

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

return 1;<br />

}<br />

SPC_DO_DECRYPT(&(ctx->ks), ctx->ctbuf, ctx->ctbuf);<br />

spc_memset(&(ctx->ks), 0, sizeof(SPC_KEY_SCHED));<br />

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

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

pad = ctx->ctbuf[SPC_BLOCK_SZ - 1];<br />

if (pad > SPC_BLOCK_SZ) {<br />

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

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

return 0;<br />

}<br />

for (i = 1; i < pad; i++) {<br />

if (ctx->ctbuf[SPC_BLOCK_SZ - 1 - i] != pad) {<br />

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

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

return 0;<br />

}<br />

}<br />

for (i = 0; i < SPC_BLOCK_SZ - pad; i++)<br />

Using a Generic CBC Mode Implementation | 185<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!