def test_pydh_keygen(): d1 = pyDH.DiffieHellman() d2 = pyDH.DiffieHellman() d1_pubkey = d1.gen_public_key() d2_pubkey = d2.gen_public_key() d1_sharedkey = d1.gen_shared_key(d2_pubkey) d2_sharedkey = d2.gen_shared_key(d1_pubkey) assert d1_sharedkey == d2_sharedkey
def msg_peer(peer_port, header, msg, isFile): peer_ip = socket.gethostname() peer_info = (peer_ip, int(peer_port)) server_peer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_peer.connect(peer_info) #key for symmetric key encryption if isFile == False: msgtype = "text" server_peer.send(msgtype.encode()) #Encrypting Message DH1 = pyDH.DiffieHellman(username) DH1_publickey = DH1.gen_public_key() server_peer.send(bytes(str(DH1_publickey), 'utf-8')) F_publickey = server_peer.recv(1024).decode("utf-8") DH1_secretkey = DH1.gen_shared_key(int(F_publickey)) msg = pad(msg) cipher = DES3.new(str(DH1_secretkey)[0:24], DES3.MODE_ECB) encrypted_msg = cipher.encrypt(msg.encode("utf-8")) server_peer.send(encrypted_msg) else: msgtype = "file" server_peer.send(msgtype.encode()) server_peer.send(header) DH1 = pyDH.DiffieHellman(username) DH1_publickey = DH1.gen_public_key() server_peer.send(bytes(str(DH1_publickey), 'utf-8')) F_publickey = server_peer.recv(1024).decode("utf-8") DH1_secretkey = DH1.gen_shared_key(int(F_publickey)) cipher = DES3.new(str(DH1_secretkey)[0:24], DES3.MODE_ECB) try: fin = open(msg, "rb") content = fin.read(1024) content = pad_file(content) while content: content = cipher.encrypt(content) server_peer.send(content) content = fin.read(1024) if (content): content = pad_file(content) fin.close() except FileNotFoundError: content = 'unsuccessfull recieve :(\n' #msg_peer(portno,header,content,isFile) print("File not found on device...") server_peer.send(content) # server_peer.send(msg) server_peer.close()
def __init__(self, conn): self.DH = pyDH.DiffieHellman(group=14) self.DH_generator = self.DH.g self.DH_prime = self.DH.p self.DH_private = self.DH.get_private_key() self.DH_public = self.DH.gen_public_key() self.conn = conn
def handle_dh_contribution(self, meta_payload): """ Attempt to create symmetric key with partner's DH contribution. Message validity is checked in calling function (recv_dh_contribution) Two scenarios: (1) I initiated a connection: My DH fields should NOT be empty since I generated DH parameters. Create symmetric key with received partner's DH contribution (2) I received a connection: My DH fields should be empty. Generate my DH temp_priv_key and temp_pub_key with the received DH parameters. Create symmetric key with received partner's DH contribution. :param meta_payload: bson (decrypted and decoded) :return True if successful symmetric key was generated, False otherwise """ try: partner_temp_pub = int(meta_payload['payload']['dh_contribution']) if self.dh is None: self.dh = pyDH.DiffieHellman() self.symmetric_key = AESGCM( bytes.fromhex(self.dh.gen_shared_key(partner_temp_pub))) return True except Exception as e: print(e) return False
def login(socket): try: username = raw_input("Please Enter Username\n") send_message_to_server('REQ_TO_BE_AUTHENTICATED', username, "", socket) message_from_server, username = respond_to_server_cookie( socket, username) # compute g Client part of DH key and send it to server password = raw_input("Please Enter the password\n") d1 = pyDH.DiffieHellman(5) d1_pubkey = d1.gen_public_key() encrypted_password = encrypt_with_asymmetric_key( s_public_key, password) nonce = os.urandom(16) password_message_dict = { 'password': encrypted_password, 'DH-KEY-C': d1_pubkey, 'Nonce': nonce } send_message_to_server('PASSWORD', username, password_message_dict, socket) server_dh_key = wait_to_be_authenticated(socket, username, d1_pubkey, nonce) session_key = d1.gen_shared_key(server_dh_key) return (socket, username, session_key, nonce) except: print "Error while logging in\n" return socket
def create_group_request(self, name): """ Request format: (ID, E(k_temp, ("/create_group", "name of the group" ,ticket))) Response format: E(k_temp, (group_id,"name of the group")) The dictionary self.group_members is updated with the the list self.group_members[group_id] = [self.id] After successful group creation a dpyDH.DiffieHellmanh is saved in self.groups as {<grp_id>: private_key} this key will be used for df key exchange. After DH key exchange the final key is saved in self.group_keys dictionary """ self.s_CHAT = socket.socket() self.s_CHAT.connect((self.chat_server_ip, self.chat_server_port)) inner_packet = ("/create_group", name, self.ticket) inner_packet_enc = self.encrypt(self.K_temp, inner_packet) outer_packet = (self.id, inner_packet_enc) self.s_CHAT.send(pickle.dumps(outer_packet)) response = self.s_CHAT.recv(4096) response_dec = self.decrypt(self.K_temp, response) print("Group with id:", response_dec[0], "and name:", response_dec[1], "is created") grp_id = int(response_dec[0]) self.group_members[grp_id] = [self.id] self.groups[grp_id] = pyDH.DiffieHellman() self.disconnect()
def gen_key_set(): """ Generating public and private keys for DH :return: private_key, public_key """ private_key = pyDH.DiffieHellman() public_key = private_key.gen_public_key() return private_key, public_key
def get_handshake_shared(self): print("- Testing get_handshake_shared... ", end="") c = Crypt("") dh = pyDH.DiffieHellman(GROUP) c_pub = c.gen_handshake_pub() assert c.get_handshake_shared( dh.gen_public_key()) == dh.gen_shared_key( c.gen_handshake_pub()) print("Passed")
def client_contribution(): """ Makes DH-object for client to generate shared key :return: client: DF object (for client) :return: client_pubkey (for server) """ client = pyDH.DiffieHellman() client_contribution = client.gen_public_key() return client, client_contribution
def diffieHellmanKeyExchangeCalculations(serverDHPublicKey): # Generating session key sessionKey = pyDH.DiffieHellman(5).gen_shared_key(serverDHPublicKey) print("SESS") print(sessionKey) # Hashing the session key to be a AES 256-bit session key AESSessionKey = sha256(sessionKey.encode()).digest() # Returning the value of AES Session Key return AESSessionKey
def key_exchange(self): c = pyDH.DiffieHellman() #client s = pyDH.DiffieHellman() #server self.C_PUBKEY = c.gen_public_key() #global variable self.S_PUBKEY = s.gen_public_key() #global variable #client sends their public key to server self.s.send(str(self.C_PUBKEY).encode("ISO-8859-1")) c_pubkey = self.s.recv(SEND_BUFFER_SIZE) #server sends their public key to client self.s.send(str(self.S_PUBKEY).encode("ISO-8859-1")) s_pubkey = self.s.recv(SEND_BUFFER_SIZE) #generate shared keys using what they received from each other self.C_SHAREDKEY = c.gen_shared_key(int(s_pubkey.decode("ISO-8859-1"))) self.S_SHAREDKEY = s.gen_shared_key(int(c_pubkey.decode("ISO-8859-1")))
def g_file_admin_request(ownerid, password): import rpyc c = rpyc.connect('localhost',50001) with open('.wrapCloud/userid/local/userid','w') as f: userid = f.read() import pyDHwith d1 = pyDH.DiffieHellman() key = d1.gen_public_key() [nonce,keyy] = c.root.file_admin_request(userid, hashlib.sha256(password).digest(),key) shared_key = d1.gen_shared_key(key) return [nonce,share_key]
def exchange_shared_key(self, broker, reply_topic, other_pub=None): dh = pyDH.DiffieHellman(16) if other_pub != None: publish.single(reply_topic, dh.gen_public_key, hostname=broker) return dh.gen_shared_key(other_pub) else: publish.single(reply_topic, dh.gen_public_key, hostname=broker) o_pub = subscribe.simple(reply_topic, hostname=broker) return dh.gen_shared_key(o_pub)
def server_contribution(clients_contribution): """ Makes DH-object for server to generate shared key (given client_contribution) :param clients_contribution :return: shared key (for server) :return: server_contribution (for client) """ server = pyDH.DiffieHellman() server_contribution = server.gen_public_key() shared_key = server.gen_shared_key(clients_contribution) return shared_key, server_contribution
def __init__(self): global dh, dh_pubkey dh = pyDH.DiffieHellman() dh_pubkey = dh.gen_public_key() rl0 = Regular_Listener("0.0.0.0", 444) rl0.start() self.PORTLIST = [25, 21, 80] listeners = [TCP_Listener("0.0.0.0", port) for port in self.PORTLIST] for listener in listeners: listener.start()
def __init__(self): try: self.dh = pyDH.DiffieHellman() self.private_key = self.dh.get_private_key() self.public_key = self.dh.gen_public_key() self.shared_key = None self.init_shared_key() except ValueError as e: print("Cannot initialized") return
def connect(self, ip, port): super().connect(ip, port) self.__dh = pyDH.DiffieHellman() self.__public = self.__dh.gen_public_key() super().send(str(self.__public)) peer_key = int(super().recvfrom()) self.__shared = self.__dh.gen_shared_key(peer_key).encode() self.__shared = base64.urlsafe_b64encode(self.__shared) self.__encrypter = Fernet(self.__shared)
def diffiehellman(conn): me = pyDH.DiffieHellman() my_pubkey = me.gen_public_key() # print(my_pubkey) conn.send(long_to_bytes(my_pubkey)) their_pubkey = bytes_to_long(conn.recv(4096)) sharedkey = me.gen_shared_key(their_pubkey) # print(sharedkey.encode()) # sharedkey = SHA256.new(sharedkey.encode()).digest() return sharedkey
def __init__(self, name): threading.Thread.__init__(self) self.name = name self.sockIn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sockOut = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.exitOR = None self.isConnected = False self.recvCell = None # generate DH instance self.dh = pyDH.DiffieHellman(5) self.pubKey = self.dh.gen_public_key() self.sharedKey = []
def share_key(self, root): invokerUid = os.getuid() d2 = pyDH.DiffieHellman() d2_key = d2.gen_public_key() self._unprivilegedProcessPipeEnd.send(d2_key) d1_key = self._unprivilegedProcessPipeEnd.recv() shared_key = d2.gen_shared_key(d1_key) g = GroupService(self._unprivilegedProcessPipeEnd, shared_key, root) from rpyc.utils.server import ThreadedServer t = ThreadedServer(g, port=50001) t.start()
def get_pwd_key(self): print("- Testing get_pwd_key... ", end="") c = Crypt("test_password") dh = pyDH.DiffieHellman(GROUP) dh_pub = dh.gen_public_key() c_pub = c.gen_handshake_pub() priv_key = b2a_base64(unhexlify(dh.gen_shared_key(c_pub))) assert priv_key == b2a_base64( unhexlify(c.get_handshake_shared(dh_pub))) assert c._pwd_key == Fernet(priv_key).decrypt( c.get_handshake_pwd_key(dh_pub)) print("Passed")
def recvfrom_noblock(self): result = super().recvfrom_noblock() if result != None and self.__peer == None: self.__peer = int(result) self.__dh = pyDH.DiffieHellman() self.__public = self.__dh.gen_public_key() self.__shared = int(self.__dh.gen_shared_key( self.__peer)).to_bytes(32, 'big') self.__encrypter = Fernet(self.__shared) return None return result
def __init__(self, pwd): """ pwd: string password """ self._dh = pyDH.DiffieHellman(GROUP) self._pwd_key = Fernet.generate_key() self._sess_key = Fernet.generate_key() self._sess_crypt = Fernet(self._sess_key) self._pwd_hash = Fernet(self._pwd_key).encrypt(bytes(pwd, "utf-8")) # used when the password, and diffie-hellman private keys are updated self._dh_lock = threading.Lock() self._pwd_lock = threading.Lock()
def exposed_file_admin_request(self, admin_id, password, keyy): # send the nonce to be used while file upload password = hashlib.sha256(str(password)).digest() if self.authenticated_users[admin_id] != password: return 'wrong password' d2 = pyDH.DiffieHellman() key = d2.gen_public_key() try: shared_key = d2.gen_shared_key(keyy) except: return 'use appropriate keys' nonce = os.urandom(12) self.admin_keys[admin_id] = shared_key self.nonce[admin_id] = nonce return [nonce, key]
def __init__(self, IP): self.dh = pyDH.DiffieHellman() self.dh_pubkey = self.dh.gen_public_key() self.CNC = IP self.CNC_regular_port = 444 self.PORTLIST = [25, 21, 80] self.RECEIVER_DH_PUB_KEY = None self.send_msg(1, self.dh_pubkey.to_bytes(256, 'big')) msg_type, result = TCP_Listener.get_next_message() if msg_type == 1: self.RECEIVER_DH_PUB_KEY = result else: exit() self.dh_sharedkey = self.dh.gen_shared_key(self.RECEIVER_DH_PUB_KEY) print(self.dh_sharedkey) time.sleep(0.1)
def deffie(c): d1_pubkey = c.recv(1024) d1_pubkey = pickle.loads(d1_pubkey) d1_pubkey = d1_pubkey.pubkey print(d1_pubkey) # d1_pubkey.decode("utf-8") d2 = pyDH.DiffieHellman() d2_pubkey = d2.gen_public_key() d2_pubkey = str(d2_pubkey) c.send(d2_pubkey.encode()) d1_pubkey = int(d1_pubkey) d2_sharedkey = d2.gen_shared_key(d1_pubkey) print(d2_sharedkey) return d2_sharedkey
def send_dh_contribution(self): """ Send my Diffie-Hellman contribution to my partner. Two scenarios: (1) I initiated a connection: I am generating DH parameters and sending my DH contribution (2) I received a connection: I received DH parameters and I'm sending my DH contribution Payload includes my temporary DH "public key" (basically my DH contribution) and DH parameters if initiating connection. Payload is added to the meta_payload bson, which contains metadata about the payload. The meta_payload is dumped, encoded, signed and added to the message bson. The generated signature is added to the message bson. The message is dumped and encoded then sent to the partner. """ payload = dict() if self.dh is None: self.dh = pyDH.DiffieHellman() payload['dh_contribution'] = str(self.dh.gen_public_key()) meta_payload = dict() meta_payload['type'] = "dh_contribution" nonce = self.rng(8) meta_payload['new_nonce'] = nonce self.sent_nonce = nonce meta_payload['prev_nonce'] = self.partner_nonce meta_payload['payload'] = payload meta_payload['timestamp'] = int(time.time()) message = dict() message["meta_payload"] = bson.dumps(meta_payload) sig = self.priv_key.sign( message["meta_payload"], padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) message["signature"] = sig message_bytes = bson.dumps(message) self.s.sendall(message_bytes) self.advance_state()
def connect_to_peer(args, connection_packet): print "connecting to peer" global Peer_Nonce global DH_PRIV global DH_PUB # {Kab || Ns ||TGT(bob)}bmk || {Na}Kab pack = connection_packet['connection'] name = pack['peer'][0] addr = pack['peer'][1]['ADDRESS'] PEER_LIST[name] = {'ADDRESS': addr} # print name # print addr # print addr[0] # print addr[1] new_peer_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) new_peer_socket.settimeout(2) # connect to peer server try: new_peer_socket.connect((addr[0], addr[1])) except: print 'Unable to connect' #sys.exit() print "passing on packet" Peer_Nonce = random.randint(0, 65535) forwarded_message = {'return_to_server': pack['peer_packet']} forwarded_message['peer'] = args.user forwarded_message['Na'] = Peer_Nonce #der format DH_PRIV = pyDH.DiffieHellman() DH_PUB = DH_PRIV.gen_public_key() forwarded_message['g^a mod p'] = DH_PUB encryption_prep = pickle.dumps(forwarded_message).encode( 'base64', 'strict') pickle_barrel = pickle.dumps({ 'peer': encryption_prep }).encode('base64', 'strict') new_peer_socket.send(pickle_barrel) SOCKET_LIST.append(new_peer_socket) PEER_SOCKETS[name] = new_peer_socket
def key_exchange1(request: DNSQR, identify: bytes, bytes_victim_dh_pubkey: bytes): """ Start key exchanging with the connected victim: generate the public & shared key, encrypting & decrypting functions. send the public key to victim. :param request: the DNSQR paket from victim :param identify: victim identify number :param bytes_victim_dh_pubkey: victim public key """ victim_dh_pubkey: int = int.from_bytes(bytes_victim_dh_pubkey, 'little') dh = pyDH.DiffieHellman() pubkey: int = dh.gen_public_key() shared_key: bytes = dh.gen_shared_key(victim_dh_pubkey).encode() server_pubkey_response = build_response(identify, SERVER_COMMANDS['keyExchange2'], pubkey.to_bytes(256, 'little')) send_response(request, server_pubkey_response) connected_victims[identify] = [shared_key]
def clientFunction(clientsocket): sharedKeyGlobal = [] fileNameGloabal = [] keyToEncrypt = [] cipher_encrypt = [] d1 = pyDH.DiffieHellman() print(f"Connection from {address} has been established") client_handle(clientsocket, address, sharedKeyGlobal, fileNameGloabal, keyToEncrypt, cipher_encrypt, d1) while True: full_msg = '' msg = clientsocket.recv(1022) if len(msg) <= 0: break full_msg += msg.decode("utf-8") print(full_msg) opCodeVerify = int(full_msg[4:6]) opCodeAction(opCodeVerify, full_msg, clientsocket, sharedKeyGlobal, fileNameGloabal, keyToEncrypt, cipher_encrypt, d1) print(opCodeVerify) clientsocket.close()