0% found this document useful (0 votes)
16 views

Experiment-4

Uploaded by

mohammed.ansari
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Experiment-4

Uploaded by

mohammed.ansari
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Experiment - 4

Name: Ansari Mohammed Shanouf Valijan


Class: B.E. Computer Engineering, Semester - VII
UID: 2021300004
Batch: VII

Aim:
To implement the Diffie-Hellman key exchange algorithm.

Theory:

The Diffie-Hellman key exchange algorithm is a method for two parties to securely establish
a shared secret key over an insecure communication channel. Developed by Whitfield Diffie
and Martin Hellman in 1976, this algorithm laid the foundation for modern public-key
cryptography. The key idea behind the algorithm is that it allows two parties to agree on a
shared secret, which can then be used to encrypt and decrypt messages, even if an
eavesdropper can observe all communication between them. This shared key, once
established, forms the basis for secure symmetric encryption, making subsequent
communication confidential.
In the process of the Diffie-Hellman exchange, each party independently generates a private
key, which they keep secret. They also compute a public value derived from their private
key, which they share with the other party. The strength of the algorithm lies in the fact
that, even though both parties' public values are exchanged openly, an observer cannot
easily derive the private keys or the resulting shared secret. The process leverages
mathematical properties that are easy to compute in one direction but extremely difficult to
reverse without specific knowledge, such as factorizing large prime numbers or solving
discrete logarithms.

One of the major benefits of Diffie-Hellman is that it enables secure communication without
needing the parties to have previously exchanged secret information. This is a significant
advantage in environments where it’s impractical to meet in person or securely distribute
keys ahead of time. However, the algorithm is susceptible to man-in-the-middle attacks if
not combined with proper authentication methods, as an attacker could intercept and
modify the exchanged public keys. Therefore, Diffie-Hellman is often used alongside
additional mechanisms to verify the identities of the communicating parties, such as digital
signatures.

Over the years, the Diffie-Hellman key exchange has seen widespread use in a variety of
secure communication protocols, including SSL/TLS, VPNs, and other cryptographic systems.
While it remains effective, advances in quantum computing pose potential challenges to its
security, as quantum algorithms may one day be able to solve the mathematical problems it
relies on. To counter this, new post-quantum cryptography approaches are being explored.
Despite these challenges, Diffie-Hellman remains a fundamental algorithm in the history
and practice of cryptography.

Implementation:
In order to implement the Diffie-Hellman key exchange algorithm, two entities were taken
into consideration – sender and receiver. A server entity was also included as a way of
communication between the sender and the receiver. Following are the codes written for
each entity-

Connection server
import socket

s = socket.socket()
s.bind(('localhost', 9999))
s.listen(3)
print('\nConnection Server is up! @127.0.0.1:9999\n')

sender, addr = s.accept()


print('Sender connected successfully!')

receiver, addr = s.accept()


print('Receiver connected successfully!')

while True:
data = sender.recv(1024).decode()
if not data:
break
receiver.send(data.encode())
print('Relayed a message from sender to receiver...')

data = receiver.recv(1024).decode()
if not data:
break
sender.send(data.encode())
print('Relayed a message from receiver to sender...')

print('Closing the server...')

Sender
import socket
import sympy

commonkey = 0

def encrypt(plaintext, key):


encrypted_text = ''
for char in plaintext:
encrypted_char = chr((ord(char) - 97 + key) % 26 + 97)
encrypted_text += encrypted_char
return encrypted_text.upper()

c = socket.socket()
c.connect(('localhost', 9999))
print('\nConnected to the server!')

print('\n------------------------Available Options------------------------\n')
print('1. Fix a secret key using Diffie-Hellman Algorithm')
print('2. Send a message to the receiver')
print('3. Exit')
print('\n-----------------------------------------------------------------\n')

while True:
choice = int(input('Select an option ----> '))

if choice == 1:
prime = sympy.randprime(10**17, 10**18)
generator = sympy.primitive_root(prime)
print('Following specifics will be used for key exchange:')
print(f'Prime - {prime}, Generator - {generator}')
privatekey = input('Enter your secret key (less than the prime chosen) ---
> ')
intermediatekey = pow(generator, int(privatekey), prime)
c.send((str(prime)+' '+str(generator)+' '+str(intermediatekey)).encode())
print('The intermediary calculated key was shared with the receiver.
Waiting for response...')
receivedintermediate = int(c.recv(1024).decode())
commonkey = pow(receivedintermediate, int(privatekey), int(prime))
print(f'Common key as calculated: {commonkey}')
print('Same will be used for future encryptions!\n')

elif choice == 2:
message = input('Enter the message you wish to send ---> ')
encrypted = encrypt(message, commonkey)
c.send(encrypted.encode())
print('\nThe following encoded message (using common key) was sent to the
receiver:')
print(encrypted, '\n')

elif choice == 3:
print('Disconnecting....\n')
break

c.close()
print('Sender was disconnected....\n')

Receiver
import socket

commonkey = 0

def decrypt(ciphertext, key):


decrypted_text = ''
for char in ciphertext:
decrypted_char = chr((ord(char) - 65 - key) % 26 + 65)
decrypted_text += decrypted_char
return decrypted_text.lower()

c = socket.socket()
c.connect(('localhost', 9999))
print('\nConnected to the server!')

print('\n------------------------Available Options------------------------\n')
print('1. Wait to receive a key generation request from the sender')
print('2. Wait to receive a message from the sender')
print('3. Exit')
print('\n-----------------------------------------------------------------\n')
while True:
choice = int(input('Select an option ----> '))

if choice == 1:
print('Waiting for the sender to start the process...')
data = c.recv(1024).decode().split(' ')
print('Following specifics will be used for key exchange:')
print(f'Prime - {data[0]}, Generator - {data[1]}')
print('Intermediate key received from the sender!')
privatekey = int(input('Enter your secret key (less than the chosen prime)
---> '))
intermediatekey = pow(int(data[1]), privatekey, int(data[0]))
c.send(str(intermediatekey).encode())
print('Intermediate key from your end was sent to the sender!')
commonkey = pow(int(data[2]), privatekey, int(data[0]))
print(f'Common key as calculated: {commonkey}')
print('Same will be used for future encryptions!\n')

elif choice == 2:
print('Waiting for sender to send a message...')
encrypted = c.recv(1024).decode()
print('The encrypted message as received from the sender:')
print(encrypted, '\n')
print('The message as decoded using the common key:')
print(decrypt(encrypted, commonkey), '\n')

elif choice == 3:
print('Disconnecting....\n')
break

c.close()
print('Receiver was disconnected....\n')

Results:
Following are the screenshots of the entities under interaction-

On sender’s end
On receiver’s end
On server’s console

In brief, for the part of key exchange using Diffie-Hellman algorithm, a random prime
number was generated and its primitive root was found using SymPy library in python.
Further, common key as calculated was stored in both – the sender and the receiver entities
(but not on the server). Further, the key was used in encryption and decryption of messages
from sender to receiver using caeser cipher substitution technique.
Conclusion:
By performing this experiment, I was able to understand the steps involved in calculating a
common secret key without having to share it directly on the communication channel using
the Diffie-Hellman algorithm. I was able to simulate the process using three entities as
mentioned above and was able to successfully perform the key exchange and further
encryption-decryption of messages from sender to receiver. This experiment, thus, helped
me in intuiting the key exchange process between two entities without involving a third
party.

You might also like