Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket, Crypto, hashlib, string, base64
- from Crypto import Random
- from Crypto.Cipher import AES
- from Crypto.Random import random
- #Diffie-Hellman in python
- modulus = 8669
- base = 3300 #These are small because otherwise I had problems with identical keys
- def server(ip, port):
- s = socket.socket()
- s.bind((ip,port)) #Listen for client
- s.listen(1)
- print("Listening...")
- client, addr = s.accept() #Accept a client
- print("Creating key pair...")
- privateKey = sum([ord(x) for x in Random.new().read(100)]) #Get 100 random bytes and sum them to get private key
- publicKey = pow(base, privateKey, modulus) #Calculate (base^private)%modulus to get public key
- print("Private key: "+str(privateKey))
- print("Public key: "+str(publicKey))
- clientKey = client.recv(2048) #Get public key from client
- client.sendall(str(publicKey)) #Send own public key
- print("Calculating shared secret...")
- sharedSecret = pow(int(clientKey), privateKey, modulus) #calculate (public^private)%modulus to get shared secret
- print("Common secret is: "+str(sharedSecret))
- print("Calculating shared encryption key...")
- key = hashlib.sha256(str(sharedSecret)).hexdigest()[:32] #Hash the shared secret and use the first 32 bytes as key
- eoe = ''.join([chr((ord(x)+8)%256) for x in key[::2]]) #Take every other element and add 8 to it
- key = ''.join([x for t in zip(key, eoe) for x in t]) #Interleave key and eoe
- print("Calculating initialization vector...")
- IV = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(16)]) #Generate the IV
- print("Sending IV to client...")
- client.sendall(IV) #Send IV to client
- print("Key: "+str(key))
- print("IV: "+str(IV))
- aesobj = AES.new(key, AES.MODE_CFB, IV) #Create AES object using key and IV
- return aesobj
- def client(ip, port):
- s = socket.socket()
- s.connect((ip, port)) #Connect to server
- privateKey = sum([ord(x) for x in Random.new().read(100)]) #100 random bytes
- publicKey = pow(base, privateKey, modulus)
- s.sendall(str(publicKey)) #Create key pair and send public key
- serverKey = s.recv(2048)
- sharedSecret = pow(int(serverKey), privateKey, modulus) #Calculate shared secret
- key = hashlib.sha256(str(sharedSecret)).hexdigest()[:32] #Hash the shared secret and use the first 32 bytes as key
- eoe = ''.join([chr((ord(x)+8)%256) for x in key[::2]]) #Take every other element and add 8 to it
- key = ''.join([x for t in zip(key, eoe) for x in t]) #Interleave key and eoe
- IV = s.recv(256) #Get IV and create AES object
- aesobj = AES.new(key, AES.MODE_CFB, IV)
- return aesobj
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement