def authenticate_as_client(self, session_socket): # authenticates an external server connected via session_socket iv = self.receive_iv(session_socket) master_encrypter = Encrypter(self.master_key, iv) m = Messenger(session_socket, master_encrypter, self.continueHandler) client_challenge = genStr(CHALLENGE_LENGTH) client_challenge_hash = str(create_key(client_challenge)) hash_len = len(client_challenge_hash) secretA = generateAorB() publicA = pow(g, secretA, p) m.send(client_challenge + str(publicA)) response = m.recv() while not response: response = m.recv() if response[:hash_len] != client_challenge_hash: m.close() raise Exception('client could not authenticate') server_challenge_hash = str(create_key(response[hash_len:hash_len + CHALLENGE_LENGTH])) m.send(server_challenge_hash) public_b = int(response[hash_len + CHALLENGE_LENGTH:]) self.log.info('g^b mod p is {}'.format(public_b)) session_key = create_key(str(pow(public_b, secretA, p))) self.log.info('Session key generated by the client is {}'.format(session_key)) session_encrypter = Encrypter(session_key, iv) session_m = Messenger(session_socket, session_encrypter, self.continueHandler) self._messenger = session_m
def authenticate_as_server(self, session_socket): # authenticates an external client connected via session_socket iv = self.generate_and_send_iv(session_socket) # the server should generate a random iv master_encrypter = Encrypter(self.master_key, iv) m_messenger = Messenger(session_socket, master_encrypter, self.continueHandler) secret_b = generateAorB() public_b = str(pow(g, secret_b, p)) server_challenge = genStr(CHALLENGE_LENGTH) server_challenge_hash = str(create_key(server_challenge)) response = m_messenger.recv() while not response: response = m_messenger.recv() client_challenge = response[:CHALLENGE_LENGTH] client_challenge_hash = str(create_key(client_challenge)) public_a = response[CHALLENGE_LENGTH:] self.log.info('publicA is {}'.format(public_a)) m_messenger.send(client_challenge_hash + server_challenge + public_b) session_key = create_key(str(pow(int(public_a), secret_b, p))) self.log.info('session key is {}'.format(session_key)) response = m_messenger.recv() while not response: response = m_messenger.recv() if response != server_challenge_hash: self.log.warn('Client could not be authenticated. Session will be terminated!') m_messenger.close() else: print('Server Authentication Successful!!!') session_encrypter = Encrypter(session_key, iv) self._messenger = Messenger(session_socket, session_encrypter, self.continueHandler)