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.

Often, you’ll want to generate a set of keys, such as an encryption key and a MAC<br />

key. (See Recipe 4.11 for a complete discussion of key derivation.)<br />

Key exchange with Diffie-Hellman isn’t secure unless you have some<br />

secure way of authenticating the other end. Generally, you should digitally<br />

sign messages in this protocol with DSA or RSA, and be sure that<br />

both sides securely authenticate the signature—for example, through a<br />

public key infrastructure.<br />

Once a key or keys are established, the two parties try to communicate. If both sides<br />

are using message integrity checks, they’ll quickly know whether or not the exchange<br />

was successful (if it’s not, nothing will validate on decryption).<br />

If you don’t want to use an existing API, here’s an example of generating a random<br />

secret and computing the value to send to the other party (we use the OpenSSLarbitrary<br />

precision math library):<br />

#include <br />

typedef struct {<br />

BIGNUM *n;<br />

BIGNUM *g; /* use a BIGNUM even though g is usually small. */<br />

BIGNUM *private_value;<br />

BIGNUM *public_value;<br />

} DH_CTX;<br />

/* This function assumes that all BIGNUMs are already allocated, and that n and g<br />

* have already been chosen and properly initialized. After this function<br />

* completes successfully, use BN_bn2bin( ) on ctx->public_value to get a binary<br />

* representation you can send over a network. See Recipe 7.4 for more info on<br />

* BNbinary conversions.<br />

*/<br />

int DH_generate_keys(DH_CTX *ctx) {<br />

BN_CTX *tmp_ctx;<br />

if (!(tmp_ctx = BN_CTX_new( ))) return 0;<br />

if (!BN_rand_range(ctx->private_value, ctx->n)) {<br />

BN_CTX_free(tmp_ctx);<br />

return 0;<br />

}<br />

if (!BN_mod_exp(ctx->public_value, ctx->g, ctx->private_value, ctx->n, tmp_ctx)) {<br />

BN_CTX_free(tmp_ctx);<br />

return 0;<br />

}<br />

BN_CTX_free(tmp_ctx);<br />

return 1;<br />

}<br />

When one side receives the Diffie-Hellman message from the other, it can compute<br />

the shared secret from the DH_CTX object and the message as follows:<br />

BIGNUM *DH_compute_secret(DH_CTX *ctx, BIGNUM *received) {<br />

BIGNUM *secret;<br />

Using Basic Diffie-Hellman Key Agreement | 435<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!