[Back] Diffie-Hellman is used in key exchange. Bob and Alice agree on two values (g and p), where p is a prime number. Next Bob and Alice generate two random numbers (a and b), and exchange values. Unfortunately it is prone to a man-in-the-middle attack, and where Eve generates two keys, one to communicate with Bob, and the other for Alice:

## Diffie-Hellman (Man-in-the-middle) |

## Method

In this case, no matter what value Eve gets, she will return a value to both Bob and Alice, based on her random number.

For example if g=15 and p=1011, and Alice uses a random value of 5. For her key, Alice will calculate:

\(A = 15^5 \mod 1011 = 114\)

If Bob takes a random value of 9. Bob will calculate:

\(B = 15^9 \mod 1011 = 462\)

Eve changes Alice's value in the tunnel to give:

\(114^7 \mod 1011 = 402 \)

So, Alice receives a value of 402. She calculates a key of:

\(Key_{Alice} = 402^5 \mod 1011 = 636\)

Bob receive a value of 426 and calculate his key of:

\(Key_{Bob} = 462^9 \mod 1011 = 483\)

This is, of course, wrong, as the Diffie-Hellman method should give the same value. But Eve is the man-in-the-middle, so she has two keys, and basically deciphers the message, and re-encrypts.

## Sample code

The following gives some sample code for the DF calculation:

import random import base64 import hashlib import sys g=15 p=1011 a= 5 b = 9 eve = 7 message=21 A=(g**a) % p B=(g**b) % p Eve1 = (A**eve) % p Eve2 = (B**eve) % p Key1= (Eve1**a) % p Key2= (Eve2**b) % p print 'g: ',g,' (a shared value), n: ',p, ' (a prime number)' print '\n== Random value generation ===' print '\nAlice calculates:' print 'a (Alice random): ',a print 'Alice value (A): ',A,' (g^a) mod p' print '\nBob calculates:' print 'b (Bob random): ',b print 'Bob value (B): ',B,' (g^b) mod p' print '\n==Alice sends value to Eve ===' print 'Eve takes Alice\'s value and calculates: ',Eve1 print 'Alice gets Eve\'s value and calculates key of: ',Key1 print '\n==Bob sends value to Eve ===' print 'Eve takes Bob\'s value and calculates: ',Eve2 print 'Bob gets Eve\'s value and calculates key of: ',Key2