import math import socket import sys import pyDHE HOST = "127.0.0.1" PORT = 12345 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() while True: connection, address = s.accept() with connection: print("Connected by ", address) alice = pyDHE.new(14) bob_pub_key_bytes = connection.recv(2048) bob_pub_key = int.from_bytes(bob_pub_key_bytes, sys.byteorder, signed=False) shared_key = alice.update(bob_pub_key) alice_pub_key = alice.getPublicKey() alice_pub_key_bytes = alice_pub_key.to_bytes(math.ceil(alice_pub_key.bit_length()/8), sys.byteorder, signed=False) connection.sendall(alice_pub_key_bytes) print(shared_key)
Now, as per the IETF RFC 3526, there are a set of values for g and p. And, each set of values is given an id. In the group id 14, g is 2 and p is a 2048-bit prime number that has a specific value. Please refer to the IETF RFC for details.
Please note that the server and the client can exchange bytes. So, we need to convert the bytes into an integer and use it for calculation.
The client can compute the same shared secret in the following way:
import math import socket import sys import pyDHE HOST = "127.0.0.1" PORT = 12345 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) bob = pyDHE.new(14) bob_pub_key = bob.getPublicKey() bob_pub_key_bytes = bob_pub_key.to_bytes(math.ceil(bob_pub_key.bit_length()/8), sys.byteorder, signed=False) s.sendall(bob_pub_key_bytes) alice_pub_key_bytes = s.recv(2048) alice_pub_key = int.from_bytes(alice_pub_key_bytes, sys.byteorder, signed=False) shared_key = bob.update(alice_pub_key) print(shared_key)
Here also, the client is receiving shared parameters from the server and using them to calculate the same shared secret. Interested readers, who want to know more about how to implement the Diffie-Hellman Key Exchange algorithm using Python without using any specific library, please refer to the following article: How to implement the Diffie-Hellman Key Exchange algorithm using Python?
I hope this helps. However, readers who want to know more about how different cryptographic algorithms work and how they are used in various secure network protocols can refer to the book “Cryptography And Public Key Infrastructure.”






0 Comments