def DHencrypt(plaintext, symmetricKey, p, gen): """Encrypts a message M given parameters above""" "Method was updated to use AES symetric decryption that was" "provided in the starter code as option of symetric encrytion using shared secret keys is generated." simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt(plaintext) # Running simplified AES. return ciphertext
def main(): """Driver function for the project""" serverHost = 'localhost' # The remote host serverPort = 9000 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((serverHost, serverPort)) msg = serverHello() s.sendall(bytes(msg,'utf-8')) # Sending bytes encoded in utf-8 format. data = s.recv(1024).decode('utf-8') strStatus = "105 Hello" if data and data.find(strStatus) < 0: print("Invalid data received. Closing") else: # Write appropriate code to parse received string and extract # the modulus and exponent for public key encryption. values = data[10:].split() n = int(values[0])# Modulus for public key encryption e = int(values[1]) # Exponent for public key encryption print("Server's public key: ("+ str(n)+","+str(e)+")") symmetricKey = computeSessionKey() print("Computed symmetricKey: ", symmetricKey) encSymmKey = RSAencrypt(symmetricKey, e, n) print("Encrypted symmetricKey: ", encSymmKey) msg = sendSessionKey(encSymmKey) s.sendall(bytes(msg,'utf-8')) data = s.recv(1024).decode('utf-8') strStatus = "113 Nonce" if data and data.find(strStatus) < 0: print("Invalid data received. Closing") else: # Write code to parse received string and extract encrypted nonce encNonce = int(data[10:]) # from the server. The nonce has been encrypted with the server's # private key. print("Encrypted nonce: "+ str(encNonce)) nonce = RSAdecrypt(encNonce, e, n) print("Decrypted nonce: "+ str(nonce)) """Setting up for Simplified AES encryption""" plaintext = nonce print("plaintext: ", plaintext) simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt(plaintext) # Running simplified AES. print("ciphertext: ", ciphertext) msg = sendTransformedNonce(ciphertext) s.sendall(bytes(msg,'utf-8')) data = s.recv(1024).decode('utf-8') if data: print(data) s.close()
def main(): """Driver function for the project""" HOST = 'localhost' # The remote host PORT = 13000 # The same port as used by the server c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.connect((HOST,PORT)) msg = serverHello() c.sendall(bytes(msg,'utf-8')) # Sending bytes encoded in utf-8 format. data = c.recv(1024).decode('utf-8') strStatus = "105 Hello" if data and data.find(strStatus) < 0: print("Invalid data received. Closing") else: # Write appropriate code to parse received string and extract # the modulus and exponent for public key encryption. splitd = data.split(" ") n = int(splitd[2])# Modulus for public key encryption e = int(splitd[3]) # Exponent for public key encryption print("Server's public key: ("+ str(n)+","+str(e)+")") symmetricKey = computeSessionKey() print("the generated symm key is ",symmetricKey) simplified_AES.keyExp(symmetricKey) encSymmKey = RSAencrypt(symmetricKey, e, n) print("encrypted symm key ",encSymmKey) msg = sendSessionKey(encSymmKey) c.sendall(bytes(msg,'utf-8')) data = c.recv(1024).decode('utf-8') strStatus = "113 Nonce" if data and data.find(strStatus) < 0: print("Invalid data received. Closing") else: # Write code to parse received string and extract encrypted nonce splitd = data.split(" ") encNonce = int(splitd[2]) # from the server. The nonce has been encrypted with the server's # private key. print("Encrypted nonce: "+ str(encNonce)) temp = RSAencrypt(encNonce, e, n) plaintext = temp print("Decrypted nonce: "+ str(temp)) """Setting up for Simplified AES encryption""" simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt(plaintext) # Running simplified AES. msg = sendTransformedNonce(ciphertext) c.sendall(bytes(msg,'utf-8')) data = c.recv(1024).decode('utf-8') if data: print(data) c.close()
def processMsgs(s, msg, state): """This function processes messages that are read through the socket. It returns a status, which is an integer indicating whether the operation was successful""" status = -2 rcvr_mod = int(state['modulus']) # Receiver's modulus for RSA rcvr_exp = int(state['pub_exp']) # Receiver's public exponent symmetricKey = int(state['SymmetricKey']) # shared symmetric key bids = int(state['Bids']) # bids = number of bids made DiceValues = state['Dice'] # DiceValues = values of dice dice = list(map(int,dice)) # Converting dice values to ints strTest = "101 Hello " if (strTest in msg and status==-2): RcvdStr = msg.split(' ') sndr_mod = int(RcvdStr[2]) # Modulus for public key encryption sndr_exp = int(RcvdStr[3]) # Exponent for public key encryption symmetricKey = computeSessionKey() ## Add code to handle the case where the symmetricKey is ## greater than the modulus. encSymmKey = ## Add code to encrypt the symmetric key. msg = sendSessionKey(encSymmKey) s.sendall(bytes(msg,'utf-8')) state['modulus'] = sndr_mod state['pub_exp'] = sndr_exp state['SymmetricKey'] = symmetricKey status = 1 strNonce = "120 Nonce" if (strNonce in msg and status==-2): RcvdStr = msg.split(' ') encNonce = int(RcvdStr[2]) nonce = ## Add code to decrypt nonce """Setting up for Simplified AES encryption""" plaintext = nonce simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt(plaintext) # Running simplified AES. msg = sendTransformedNonce(ciphertext) s.sendall(bytes(msg,'utf-8')) status = 1
def main(): """Driver function for the project""" serverHost = 'localhost' # The remote host serverPort = 9000 # The same port as used by the server print "Creating socket to communicate with remote host @ " + str( serverHost) + " over port " + str(serverPort) serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Connecting to remote host..." try: serverSocket.connect((serverHost, serverPort)) except socket.error as e: print "" print "Failed to establish connection to remote host with error:" print "\t" + str(e) print "Program will end now." return 1 print "Connected." print "" print "Sending hello message to remote host..." try: serverSocket.sendall(serverHello()) except socket.error: print "" print "Error sending data to remote host" return 1 print "Hello message sent." print "" print "Waiting on server to send its public key..." buff = serverSocket.recv(1024) if not buff: handleRemoteHostDisappear(serverSocket) return 0 strStatus = "105 Hello" if buff.find(strStatus) >= 0: print "Public key received." print "Parsing response..." data = buff.split(" ") n = int(data[2]) # Modulus for public key encryption e = int(data[3]) # Exponent for public key encryption print "Server's public key: (" + str(n) + ", " + str(e) + ")" print "" print "Generating this client's keys..." # I don't need to assume. I KNOW that these numbers will fall in the same ranges like in the server and be prime :P p_client = random.randint(907, 1014) while not isPrime(p_client): # keep going til we're prime p_client = random.randint(907, 1014) q_client = random.randint(53, 68) while not isPrime(q_client): q_client = random.randint(53, 68) n_client, e_client, d_client = genKeys(p_client, q_client) print "Client's public key: (" + str(n_client) + ", " + str( e_client) + ")" print "Sending public key to server..." try: serverSocket.sendall("110 PB " + str(n_client) + " " + str(e_client)) except socket.error: print "" print "Error sending data to server" return 1 print "Public key sent." print "" else: handleProtocolError(buff, serverSocket) return 0 print "Waiting on server's receipt ack..." buff = serverSocket.recv(1024) if not buff: handleRemoteHostDisappear(serverSocket) return 0 if buff == "111 ACK PB": print "Received receipt ack." print "" print "Generating session key..." symmetricKey = computeSessionKey() encSymmKey = RSAencrypt(symmetricKey, e, n) print "Session key generated." msg = sendSessionKey(encSymmKey) print "Pending message to server:" print "\t" + str(msg) print "Sending..." try: serverSocket.sendall(msg) except socket.error: print "" print "Error sending data to server" return 1 print "Session key sent." print "" else: handleProtocolError(buff, serverSocket) return 0 print "Waiting on server challenge..." buff = serverSocket.recv(1024) if not buff: handleRemoteHostDisappear(serverSocket) return 0 strStatus = "113 Nonce" if buff.find(strStatus) >= 0: print "Challenge received." encNonce = int(buff.split(" ")[2]) print "Encrypted nonce: " + str(encNonce) print "Decrypting nonce..." nonce = RSAdecrypt(encNonce, e, n) print "Decrypted nonce: " + str(nonce) print "" """Setting up for Simplified AES encryption""" plaintext = nonce simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt( plaintext) # Running simplified AES. msg = sendTransformedNonce(ciphertext) print "Pending message with challenge response:" print "\t" + str(msg) print "Sending..." try: serverSocket.sendall(msg) except socket.error: print "" print "Error sending data to server" return 1 print "Challenge response sent." print "" else: handleProtocolError(buff, serverSocket) return 0 print "Waiting on challenge outcome..." buff = serverSocket.recv(1024) if not buff: handleRemoteHostDisappear(serverSocket) return 0 else: print "Response received from server." print "\t" + "Response: " + str(buff) print "" print "Shutting down connection..." serverSocket.close() print "Closed this connection's local endpoint."
def main(): """Driver function for the project""" serverHost = 'localhost' # The remote host serverPort = 9000 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((serverHost, serverPort)) print("Connected to server..."); msg = serverHello() s.sendall(bytes(msg,'utf-8')) # Sending bytes encoded in utf-8 format. print("message "+msg+" sent"); data = s.recv(1024).decode('utf-8') print("Message "+str(data)+" received"); strStatus = "105 Hello" if data and data.find(strStatus) < 0: print("Invalid data received. Closing") else: # Write appropriate code to parse received string and extract # the modulus and exponent for public key encryption. tn=""; te=""; space=False; for k in data[10:]: if(k!=" " and not space):#gets n segment tn+=str(k); elif(k==" "): space=True; elif(space):#gets e segment te+=str(k); n = int(tn) # Modulus for public key encryption e = int(te)# Exponent for public key encryption print("Server's public key: ("+ str(n)+","+str(e)+")") symmetricKey = computeSessionKey() encSymmKey = RSAencrypt(symmetricKey, e, n) print("Sending symmetric key "+str(symmetricKey)+"..."); msg = sendSessionKey(encSymmKey) print("Key "+str(msg)+" sent."); s.sendall(bytes(msg,'utf-8')) data = s.recv(1024).decode('utf-8') print("Received "+str(data)+" from server"); strStatus = "113 Nonce" if data and data.find(strStatus) < 0: print("Invalid data received. Closing") else: # Write code to parse received string and extract encrypted nonce # from the server. The nonce has been encrypted with the server's # private key. encNonce=int(data[10:]); print("Encrypted nonce: "+ str(encNonce)) nonce = RSAdecrypt(encNonce, e, n) print("Decrypted nonce: "+ str(nonce)) """Setting up for Simplified AES encryption""" plaintext = nonce simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt(plaintext) # Running simplified AES. msg = sendTransformedNonce(ciphertext) s.sendall(bytes(msg,'utf-8')) print("Message "+ msg+" sent."); data = s.recv(1024).decode('utf-8') if data: print(data) s.close()
def main(): """Driver function for the project""" serverHost = 'localhost' # The remote host serverPort = 9000 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((serverHost, serverPort)) msg = serverHello() s.sendall(bytes(msg,'utf-8')) # Sending bytes encoded in utf-8 format. data = s.recv(1024).decode('utf-8') strStatus = "105 Hello" if data and data.find(strStatus) < 0: print("Invalid data received. Closing") else: # Write appropriate code to parse received string and extract # the modulus and exponent for public key encryption. n = int(data.split()[2]) # Modulus for public key encryption e = int(data.split()[3]) # Exponent for public key encryption print("Server's public key: ("+ str(n)+","+str(e)+")") symmetricKey = computeSessionKey() print ("Symmetric Key:" + str(symmetricKey)) encSymmKey = RSAencrypt(symmetricKey, e, n) print ("Encrypted Symmetric Key:"+ str(encSymmKey)) msg = sendSessionKey(encSymmKey) s.sendall(bytes(msg,'utf-8')) data = s.recv(1024).decode('utf-8') print (data) strStatus = "113 Nonce" if data and data.find(strStatus) < 0: print("Invalid data received. Closing") else: # Write code to parse received string and extract encrypted nonce # from the server. The nonce has been encrypted with the server's # private key. u=data[10:] print("Encrypted nonce: "+ u) encNonce=int(u)#converts the parsed Encrypted Nonce to int nonce = RSAdecrypt(encNonce, e, n) print("Decrypted nonce: "+ str(nonce)) """Setting up for Simplified AES encryption""" plaintext = nonce simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt(int(plaintext)) # Running simplified AES. msg = sendTransformedNonce(ciphertext) s.sendall(bytes(msg,'utf-8')) data = s.recv(1024).decode('utf-8') if data: print(data) print ("Enter prime numbers. One should be between 907 and 1013, and the other between 53 and 67") Clientp = int(input('Enter P : '))#request user input for p Clientq = int(input('Enter Q: '))#request user input for q while (not isprime(Clientp) or not isprime(Clientq)):#prompt user if value not prime if not isprime(Clientp):print ("first number was not prime!!!") if not isprime(Clientq):print ("Second number was not prime!!!") print("") Clientp = int(input("Please enter a prime number between 907 and 1013: ")) Clientq = int(input("Please enter a prime number between 53 and 67: ")) while (Clientp<907 or Clientp>1013) or (Clientq<53 or Clientq>67): # prompt user to re-enter prime if Clientp<907 or Clientp>1013 :print ("first number Must Be greater Than 907 and less than 1013!!!") if Clientq<53 or Clientq>67:print ("Second number Must Be greater Than 53 and less than 67!!!") print("") Clientp = int(input("Please enter a prime number between 907 and 1013: ")) Clientq = int(input("Please enter a prime number between 53 and 67: ")) clientN,clientE=genKeys(Clientp,Clientq)#uses the genKeys function to generate the public key msg="Client Public Key is :"+ str(clientN)+ " "+str(clientE) s.sendall(bytes(msg,'utf-8'))#sends client's public key to server s.close()
ServerDice = list(map(int,ServerDice)) # Converting dice values to ints strTest = "100 Hello" if strTest in msg and status == -2: msg = clientHelloResp(modulus, pub_exp) s.sendall(bytes(msg,'utf-8')) status = 1 strSessionKey = "110 SessionKey" if strSessionKey in msg and status == -2: RcvdStr = msg.split(' ') encSymmKey = int(RcvdStr[2]) SymmKey = ## Add code to decrypt symmetric key state['SymmetricKey'] = SymmKey # The next line generates the round keys for simplified AES simplified_AES.keyExp(SymmKey) challenge = generateNonce() # Add code to ensure that the challenge can always be encrypted # correctly with RSA. state['nonce'] = challenge msg = SessionKeyResp(RSAcrypt(challenge, priv_exp, modulus)) s.sendall(bytes(msg, 'utf-8')) status = 1 strSessionKeyResp = "130 " if strSessionKeyResp in msg and status == -2: RcvdStr = msg.split(' ') encryptedChallenge = int(RcvdStr[1]) # The next line runs AES decryption to retrieve the key. decryptedChallenge = simplified_AES.decrypt(encryptedChallenge) msg = nonceVerification(challenge, decryptedChallenge)
def processMsgs(s, msg, state): """This function processes messages that are read through the socket. It returns a status, which is an integer indicating whether the operation was successful""" status = -2 modulus = int(state['modulus']) # modulus = modulus for RSA pub_exp = int(state['pub_exp']) # pub_exp = public exponent priv_exp = int(state['priv_exp']) # priv_exp = secret key challenge = int(state['nonce']) # challenge = nonce sent to client SymmKey = int(state['SymmetricKey']) # SymmKey = shared symmetric key rolls = int(state['Rolls']) # rolls = number of dice rolls dice = state['Dice'] # Dice = values of dice dice = list(map(int, dice)) # Converting dice values to ints strTest = "100 Hello" if strTest in msg and status == -2: print("Message received: " + msg) msg = clientHelloResp(modulus, pub_exp) s.sendall(bytes(msg, 'utf-8')) status = 1 print("Message sent: ", msg) strSessionKey = "110 SessionKey" if strSessionKey in msg and status == -2: print("Message received: " + msg) RcvdStr = msg.split(' ') encSymmKey = int(RcvdStr[2]) SymmKey = RSAdecrypt(encSymmKey, priv_exp, modulus) ## Add code to decrypt symmetric key state['SymmetricKey'] = SymmKey # The next line generates the round keys for simplified AES simplified_AES.keyExp(SymmKey) challenge = generateNonce() # Add code to ensure that the challenge can always be encrypted # correctly with RSA. while (challenge > modulus ): # While loops executes if challenge is more than modulus. temp = generateNonce() # Generating a new nonce. challenge = temp # Setting challenge to the newly generated nonce. #Do this state['nonce'] = challenge msg = SessionKeyResp(RSAdecrypt(challenge, priv_exp, modulus)) s.sendall(bytes(msg, 'utf-8')) status = 1 print("Decrypted Symmetric Key: ", SymmKey) print("d: ", priv_exp) print("n: ", modulus) print("Challenge: ", challenge) print("Message sent: ", msg) strSessionKeyResp = "130 Transformed Nonce" if strSessionKeyResp in msg and status == -2: print("Message received: " + msg) RcvdStr = msg[22:] encryptedChallenge = int(RcvdStr) # The next line runs AES decryption to retrieve the key. decryptedChallenge = simplified_AES.decrypt(encryptedChallenge) msg = nonceVerification(challenge, decryptedChallenge) s.sendall(bytes(msg, 'utf-8')) status = 1 strDiceRollResp = "200 Roll Dice" if strDiceRollResp in msg and status == -2: print("Message received: " + msg) RcvdStr = msg[14:] if (len(RcvdStr) > 0): RcvdStrParams = RcvdStr.split(',') toRoll = list(map(int, RcvdStrParams)) rollDice(dice, toRoll) else: rollDice(dice) if (rolls < 3): status = 1 else: status = 0 rolls += 1 state['Dice'] = dice state['Rolls'] = rolls msg = RollDiceACK(dice) s.sendall(bytes(msg, 'utf-8')) # status can only be -2 if none of the other branches were followed if status == -2: print("Incoming message was not processed. \r\n Terminating") status = -1 return status
def handleConnection(p, q, n, e, d, conn, addr): # Protocol strHello = "100 Hello" strHelloResp = "105 Hello" strSessionKey = "112 SessionKey" strSessionKeyResp = "113 Nonce" strNonceResp = "130" print("Waiting to receive hello message from client...") buff = conn.recv(1024).decode("utf-8") if not buff: handleRemoteHostDisappear(conn) return if buff.find(strHello) >= 0: print("Received hello message.") msg = clientHelloResp(n, e) print("Pending response:") print("\t" + str(msg)) print("Sending...") try: conn.sendall(bytes(msg, "utf-8")) except socket.error: print("") print("Error sending data to client") sys.exit(1) print("Response sent.") print("") else: handleProtocolError(buff, conn) return print("Waiting to receive public key from client...") buff = conn.recv(1024).decode("utf-8") if not buff: handleRemoteHostDisappear(conn) return if buff.find( "110 PB" ) >= 0: # I'll pretend that this will somehow be useful. Hmmm... print("Public key received.") print("Parsing response...") data = buff.split(" ") n_remote_host = int(data[2]) # Modulus for public key encryption e_remote_host = int(data[3]) # Exponent for public key encryption print("Client's public key: (" + str(n_remote_host) + ", " + str(e_remote_host) + ")") print("Sending receipt ack...") try: conn.sendall(bytes("111 ACK PB", "utf-8")) except socket.error: print("") print("Error sending data to client") sys.exit(1) print("Receipt ack sent.") print("") else: handleProtocolError(buff, conn) return print("Waiting to retrieve session key from client...") buff = conn.recv(1024).decode("utf-8") if not buff: handleRemoteHostDisappear(conn) return if buff.find(strSessionKey) >= 0: print("Received session key.") encryptedSymmKey = int(buff.split(" ")[2]) print("Encrypted session key: " + str(encryptedSymmKey)) print("Decrypting session key...") SymmKey = RSAdecrypt(encryptedSymmKey, d, n) print("Decrypted session key: " + str(SymmKey)) print("Creating challenge....") # The next line generates the round keys for simplified AES simplified_AES.keyExp(SymmKey) challenge = generateNonce() while challenge >= n: # Nonce sometimes exceeds n and gives me 400 Error >:( challenge = generateNonce() print("Encrypted challenge: " + str(challenge)) print("Decrypting challenge/creating nonce...") msg = SessionKeyResp(RSAdecrypt(challenge, d, n)) print("Pending message with challenge for client:") print("\t" + str(msg)) print("Sending...") try: conn.sendall(bytes(msg, "utf-8")) except socket.error: print("") print("Error sending data to client") sys.exit(1) print("Challenge sent.") print("") else: handleProtocolError(buff, conn) return print("Waiting on challenge response from client...") buff = conn.recv(1024).decode("utf-8") if not buff: handleRemoteHostDisappear(conn) return if buff.find(strNonceResp) >= 0: print("Received challenge response.") encryptedChallenge = int(buff.split(" ")[1]) print("Encrypted challenge response: " + str(encryptedChallenge)) print("Decrypting...") # The next line runs AES decryption to retrieve the key. decryptedChallenge = simplified_AES.decrypt(encryptedChallenge) print("Decrypted challenge response: " + str(decryptedChallenge)) msg = nonceVerification(challenge, decryptedChallenge) print("Pending message to client:") print("\t" + str(msg)) print("Sending...") try: conn.sendall(bytes(msg, "utf-8")) except socket.error: print("") print("Error sending data to client") sys.exit(1) print("Message sent.") print("") else: handleProtocolError(buff, conn) return print("Closing connection...") conn.close() print("Connection closed.") print("")
data = conn.recv(1024).decode('utf-8') if data and data.find(strHello) >= 0: msg = clientHelloResp(n, e) conn.sendall(bytes(msg, 'utf-8')) data = conn.recv(1024).decode('utf-8') #print("encrypted symm key ",data) //test if data and data.find(strSessionKey) >= 0: # Add code to parse the received string and extract the symmetric key //test splitd = data.split(" ") encr_symm_key = int(splitd[2]) #print("encrypted symm key ",encr_symm_key) //test symmKey = RSAdecrypt(encr_symm_key,d,n)# Make appropriate function call to decrypt the symmetric key #print(symmKey," symm") # The next line generates the round keys for simplified AES simplified_AES.keyExp(symmKey) challenge = generateNonce() while challenge>n: challenge = generateNonce() print("the challenge is ",challenge) temp = RSAdecrypt(challenge, d, n) #print ("RSAed nonce",temp) //test msg = SessionKeyResp(temp) conn.sendall(bytes(msg,'utf-8')) data = conn.recv(1024).decode('utf-8') if data and data.find(strNonceResp) >= 0: # Add code to parse the received string and extract the nonce splitd = data.split(" ") encryptedChallenge = int(splitd[1]) #print("plaintext recieved",encryptedChallenge) //test # The next line runs AES decryption to retrieve the key.
def DHdecrypt(C, symmetricKey, priv, p): simplified_AES.keyExp(symmetricKey) plaintext = simplified_AES.decrypt(C) return plaintext
def encryptMsg(plaintext, symmetricKey, p, gen): """Encrypts a message M given parameters above""" simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt(plaintext) # Running simplified AES. return ciphertext
def decryptMsg(C, symmetricKey, priv, p): """Decrypt a cipher C given parameters above""" simplified_AES.keyExp(symmetricKey) plaintext = simplified_AES.decrypt(C) return plaintext
msg = clientHelloResp(n, e) conn.sendall(bytes(msg, "utf-8")) data = conn.recv(1024).decode("utf-8") print(data) if data and data.find(strSessionKey) >= 0: # Add code to parse the received string and extract the symmetric key a = data[15:] symmkey = int(a) # converts the parsed symmetric key to a integer print("D:" + str(d)) # print the value for d print("N:" + str(n)) # print the value for n print("E:" + str(e)) # print the value for e print("PhiN:" + str(phi)) # print the value for phi(N) SymmKey = RSAdecrypt(symmkey, d, n) # Make appropriate function call to decrypt the symmetric key print("Decrypted Symmetric Key:" + str(SymmKey)) # The next line generates the round keys for simplified AES simplified_AES.keyExp(int(SymmKey)) challenge = ( generateNonce() ) # the value returned from calling generateNonce() is assigned to the challenge variable print("Challenge:" + str(challenge)) # print generated nonce msg = SessionKeyResp(RSAdecrypt(challenge, d, n)) print("Encrypted Nonce:" + str(msg)) # printing of encrypted nonce conn.sendall(bytes(msg, "utf-8")) data = conn.recv(1024).decode("utf-8") if data and data.find(strNonceResp) >= 0: # Add code to parse the received string and extract the nonce encryptedChallenge = int(data[4:]) # The next line runs AES decryption to retrieve the key. decryptedNonce = simplified_AES.decrypt(encryptedChallenge) msg = nonceVerification( challenge, decryptedNonce
def processMsgs(s, msg, state): """This function processes messages that are read through the socket. It returns a status, which is an integer indicating whether the operation was successful""" status = -2 rcvr_mod = int(state['modulus']) # Receiver's modulus for RSA rcvr_exp = int(state['pub_exp']) # Receiver's public exponent symmetricKey = int(state['SymmetricKey']) # shared symmetric key rolls = int(state['Rolls']) # Number of dice rolls used strTest = "101 Hello " if (strTest in msg and status==-2): print("Message received: "+ msg) RcvdStr = msg.split(' ') rcvr_mod = int(RcvdStr[2]) # Modulus for public key encryption rcvr_exp = int(RcvdStr[3]) # Exponent for public key encryption print("Server's public key: ("+ str(rcvr_mod)+","+str(rcvr_exp)+")") symmetricKey = computeSessionKey() ## Add code to handle the case where the symmetricKey is ## greater than the modulus. while(symmetricKey > rcvr_mod): # While loop is executed if symmetric key is greater than the modulus. temp = computeSessionKey() # Generates new session key. symmetricKey = temp # Set symmetricKey to newly generated session key. encSymmKey = RSAencrypt(symmetricKey, rcvr_exp, rcvr_mod) ## Add code to encrypt the symmetric key. msg = sendSessionKey(encSymmKey) print(msg) s.sendall(bytes(msg,'utf-8')) state['modulus'] = rcvr_mod state['pub_exp'] = rcvr_exp state['SymmetricKey'] = symmetricKey status = 1 strNonce = "120 Nonce" if (strNonce in msg and status==-2): print("Message received: " + msg) RcvdStr = msg.split(' ') encNonce = int(RcvdStr[2]) nonce = RSAdecrypt(encNonce, rcvr_exp, rcvr_mod) ## Add code to decrypt nonce """Setting up for Simplified AES encryption""" plaintext = nonce simplified_AES.keyExp(symmetricKey) # Generating round keys for AES. ciphertext = simplified_AES.encrypt(plaintext) # Running simplified AES. msg = sendTransformedNonce(ciphertext) s.sendall(bytes(msg,'utf-8')) status = 1 strDiceRoll = "205 Roll Dice ACK" if (strDiceRoll in msg and status==-2): print("Message received: " + msg) DiceValues = msg[18:].split(',') if rolls < 2: WantstoRollMore = input("Do you wish to roll more dice? (y/n): ") if WantstoRollMore=='y': msg = RollDice() s.sendall(bytes(msg,'utf-8')) rolls += 1 status = 1 else: status = 0 else: status = 0 state['Rolls'] = rolls strSuccess = "250 OK" strFailure = "400 Error" if (strFailure in msg and status==-2): print("Message received: " + str(msg)) status = 0 # To terminate loop at client if (strSuccess in msg and status==-2): print("Cryptographic checks completed successfully") print(msg) if rolls ==0: msg = "200 Roll Dice" else: msg = RollDice() s.sendall(bytes(msg,'utf-8')) rolls += 1 status = 1 if status==-2: print("Incoming message was not processed. \r\n Terminating") status = -1 return status