Click here to Skip to main content
15,900,386 members
Articles / Desktop Programming / MFC
Article

Diffie-Hellman Key Exchange Example

Rate me:
Please Sign up or sign in to vote.
3.81/5 (30 votes)
14 Nov 2008CPOL2 min read 290.7K   9.6K   53   59
An example of how an encryption key can be shared by two users using the Diffie-Hellman key exchange approach.

Introduction

It's often required that a message be encrypted between two parties for secure communication. There are plenty of algorithms out there for encryption that are very secure, but their weakness lies in transporting the encryption key. The Diffie-Hellman key exchange protocol allows people to exchange keys in a manner that does not allow an eavesdropper to calculate the key in a fast manner.

This code demonstrates the use of this type of key exchange.

How to Use the Demo Project

To demonstrate the use of the key exchange, run two copies of the demo application. Set one to be the sender and the other to be a receiver.

The sender should generate the public keys, and the sender's interim key. Paste these values into the appropriate text boxes in the receiver application. The receiver should then click to generate his interim key, and copy this key into the "receiver's interim key" textbox on the sender application. Both applications should then be able to generate the same key by clicking "Generate Key".

Using the Source Code

The DiffieHellman class is simple to use and should be integrated in the following manner:

Make an instance of the class - (i.e. CDiffieHellman *DH = new CDiffieHellman;)

The sender application then does the following:

C++
__int64 n = 0;
__int64 g = 0;
__int64 SInterim = 0;
__int64 RInterim = 0;
__int64 key = 0; 

DH->CreateKeys(g,n);
DH->CreateSenderInterKey(SInterim);

//The sender now sends (n, g, and SInterim) to the receiving application
//This can be done unencrypted because they are public keys
//Now we wait until the reciever send us their interim key lets say RInterim

DH->CreateSenderEncryptionKey(key,RInterim);
//The shared encryption key is now the value of 'key'

The receiving application does the following:

C++
__int64 n = 0;
__int64 g = 0;
__int64 SInterim = 0;
__int64 RInterim = 0;
__int64 key = 0;

//Wait for the values of (n,g, and SInterim) to be sent here

DH->CreateRecipientInterKey(RInterim);

//Now send the RInterim key to the sender application

DH->CreateRecipientEncryptionKey(key,SInterim);
//The shared encryption key is now the value of 'key'

Extra Functions

There are some private member functions of the CDiffieHellman class that you may find useful, and please feel free to use them.

  • The GeneratePrime() function generates a large prime number.
  • The MillerRabin and IsItPrime functions can be used in conjunction to test primality.
  • The XtoYmodN is a function to raise x to the power of y in modulus n. Even though it sounds impossible for a computer to work out, say 150 million to the power of 150 million, this can be done in modulus n by using the power chaining method.

Further Help

Should you require any additional help, please do not hesitate to contact me. I would be interested in hearing your comments, suggestions and any questions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: What encryption library ? Pin
pb949414-Jan-04 1:56
pb949414-Jan-04 1:56 
GeneralRe: What encryption library ? Pin
Griffter UK14-Jan-04 2:33
Griffter UK14-Jan-04 2:33 
GeneralRe: What encryption library ? Pin
pb949414-Jan-04 3:28
pb949414-Jan-04 3:28 
GeneralRe: What encryption library ? Pin
Griffter UK14-Jan-04 3:44
Griffter UK14-Jan-04 3:44 
GeneralRe: What encryption library ? Pin
caractacus14-Jan-04 23:52
caractacus14-Jan-04 23:52 
QuestionWhat of small subgroup attacks? Pin
Adam Nelson9-Jan-04 6:03
Adam Nelson9-Jan-04 6:03 
AnswerRe: What of small subgroup attacks? Pin
Griffter UK10-Jan-04 23:29
Griffter UK10-Jan-04 23:29 
GeneralRe: What of small subgroup attacks? Pin
Adam Nelson11-Jan-04 4:55
Adam Nelson11-Jan-04 4:55 
MrLeeGriffiths wrote:
Thanks for the reply. You are correct in noting that the diffie-hellman key exchange can suffer from certain types of attacks if the numbers or chosen badly. In the code I have posted it only generates 64-bit primes, and keys. Obviously this is not of a sufficient size for good security, but it serves as a demonstration of how it could be employed, and besides for general applications; for instance if someone wrote their own messenger this level of security would be adequate.

I don't think 64-bit primes provide ANY security beyond the dangerous notional security that comes from "using encryption". Recall that the difficulty of brute-forcing x given g^x mod p distills to the computation of discrete logs in a finite field. There exist algorithms for this purpose which are sub-exponential; see the seminal work by Lenstra, Verheul [click the "PDF" link to view the document itself. Given the approximate algorithmic complexity of computing a discrete log over a finite field, a 64-bit prime is easily breakable on commodity hardware.


MrLeeGriffiths wrote:
There is further trouble with diffie-hellman key exchange in that it suffers the man-in-the-middle attack which can only be resolved by use of digital signatures for authenticity checking.

True, however this can be mitigated in a number of ways, depending upon the requirements and thread model of the application. For example, if both sides can pre-share their public keys with eachother, or the client knows the server's public key depending upon requirements, MiTM can be mitigated, albeit at increased management cost.


MrLeeGriffiths wrote:
I am looking into generating larger primes, and keys (i.e. 256-bit, and so on), but since the largest type you can have in c in __int64, I'd have to write my own number representation and calculation functions, do you have any suggestions of how this can be done?

I recently finished writing an arbitrary precision integer math library for my company [I assure you, I had valid reasons for not reusing existing libs], and having done that I can assure you that you'd be well-advised to find an open source bignum library instead Smile | :)

Libtommath is a decent bignum library written by the infamous crypto curmudgeon Tom St. Dennis of sci.crypt fame. MIRACL is a more comprehensive bignum library, which includes plenty of stuff you don't need for DH, but it is well-optimized and well-understood. Myriad other libs exist, including the bignum impl "bn" in the OpenSSL source tree (personally I don't like this one, as it's pretty well obfuscated, however it is good enough for the OpenSSL team...).


MrLeeGriffiths wrote:
When I find a way of representing and calculating in larger values, I will repost the code, and also add the "safe" prime checking, that way it should be of a good security level. I've read that 128-bit keys can be broken fairly trivially - do you know what of 256-bit or 512-bit (ignoring export controls for now!)?

I urge you to avoid the fallacy of comparing asymmetric cipher key sizes (DH, RSA, etc) with those of symmetric ciphers (DES, AES, etc). A 256-bit AES key is very secure; a 256-bit DH key is laughably insecure.

Having said that, Schneier and Ferguson (I also urge you to read and memorize Practical Cryptography, or failing that, Handbook of Applied Cryptography, which can be downloaded off the Web) recommend prime modulus lengths of at least 2048 bits. However, in practice, the key size you need depends upon what you are protecting; if you're using DH to exchange an 80-bit SKIPJACK key, or a 64-bit DES key, you may be able to get away with DH keys roughly equivalent in difficulty to an 80- or 64-bit symmetric key; if you're using AES-256, then equivalently-difficult DH will run about 15k bits, which obviously is untenable.

Recently I've done a bit of work with Elliptic Curve Cryptography, which is a family of asymmetric ciphers based on the mathematics of elliptic curves. Scalar multiplication of a point on a curve distills to the DLP, however without any known subexponential attack. Therefore, a 15k-bit DH key is (very, very roughly) equivalent in difficulty using known techniques as a 512-bit ECC key.

Practical Crypto doesn't have much to say about ECC; Certicom has a fair bit of ECC material (Scott Vanstone, a co-founder of Certicom, has done seminal work in the realm of EC and EC-based crypto), and the IEEE P1363 crypto std also has a decent bit of material.

Hope this helps.



Adam
GeneralRe: What of small subgroup attacks? Pin
mtlili25-Apr-04 9:16
mtlili25-Apr-04 9:16 
GeneralRe: What of small subgroup attacks? Pin
Griffter UK25-Apr-04 22:06
Griffter UK25-Apr-04 22:06 
GeneralRe: What of small subgroup attacks? Pin
mtlili26-Apr-04 9:02
mtlili26-Apr-04 9:02 
GeneralRe: What of small subgroup attacks? Pin
Griffter UK26-Apr-04 22:00
Griffter UK26-Apr-04 22:00 
GeneralRe: What of small subgroup attacks? Pin
Adam Nelson26-Apr-04 15:01
Adam Nelson26-Apr-04 15:01 
GeneralRe: What of small subgroup attacks? Pin
Jeffrey Walton18-Jul-08 10:00
Jeffrey Walton18-Jul-08 10:00 
GeneralRe: What of small subgroup attacks? Pin
Adam Nelson18-Jul-08 10:06
Adam Nelson18-Jul-08 10:06 
GeneralRe: What of small subgroup attacks? Pin
Marcus Carey16-Jan-07 5:20
Marcus Carey16-Jan-07 5:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.