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.

Using a MAC in CTR mode is easy. As illustrated in Figure 6-7, key it, then use it to<br />

“MAC” a nonce concatenated with a counter. XOR the results with the plaintext.<br />

Figure 6-7. Encrypting with a MAC in counter mode<br />

For example, here’s a function that encrypts a stream of data using the HMAC-SHA1<br />

implementation from Recipe 6.10:<br />

#include <br />

#include <br />

#define NONCE_LEN 16<br />

#define CTR_LEN 16<br />

#define MAC_OUT_SZ 20<br />

unsigned char *spc_MAC_encrypt(unsigned char *in, size_t len, unsigned char *key,<br />

int keylen, unsigned char *nonce) {<br />

/* We're using a 128-bit nonce and a 128-bit counter, packed into one variable */<br />

int i;<br />

size_t blks;<br />

SPC_HMAC_CTX ctx;<br />

unsigned char ctr[NONCE_LEN + CTR_LEN];<br />

unsigned char keystream[MAC_OUT_SZ];<br />

unsigned char *out;<br />

if (!(out = (unsigned char *)malloc(len))) abort( );<br />

SPC_HMAC_Init(&ctx, key, keylen);<br />

memcpy(ctr, nonce, NONCE_LEN);<br />

memset(ctr + NONCE_LEN, 0, CTR_LEN);<br />

blks = len / MAC_OUT_SZ;<br />

while (blks--) {<br />

SPC_HMAC_Reset(&ctx);<br />

SPC_HMAC_Update(&ctx, ctr, sizeof(ctr));<br />

SPC_HMAC_Final(out, &ctx);<br />

i = NONCE_LEN + CTR_LEN;<br />

/* Increment the counter. */<br />

while (i-- != NONCE_LEN)<br />

if (++ctr[i]) break;<br />

for (i = 0; i < MAC_OUT_SZ; i++) *out++ = *in++ ^ keystream[i];<br />

}<br />

if (len % MAC_OUT_SZ) {<br />

302 | Chapter 6: Hashes and Message Authentication<br />

P 1<br />

Start<br />

MAC K<br />

C 1<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

P 11<br />

Start +10<br />

E K<br />

. . . . . .<br />

C 11

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!