예제 #1
0
		# 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)
		s.sendall(bytes(msg,'utf-8'))
		status = 0	# To terminate loop at server.
	
	# 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 main():
	"""Driver function for the project"""
	args = sys.argv
	if len(args) != 2:
예제 #2
0
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
예제 #3
0
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("")
예제 #4
0
            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.
                decryptedChallenge = simplified_AES.decrypt(encryptedChallenge)
                #print("plaintext decrypted", type(decryptedChallenge)) //test
                msg = nonceVerification(challenge,decryptedChallenge)# Make function call to compare the nonce sent with that received

                conn.sendall(bytes(msg,'utf-8'))
    conn.close()
    

def DHdecrypt(C, symmetricKey, priv, p):
    simplified_AES.keyExp(symmetricKey)
    plaintext = simplified_AES.decrypt(C)
    return plaintext
def decryptMsg(C, symmetricKey, priv, p):
    """Decrypt a cipher C given parameters above"""
    simplified_AES.keyExp(symmetricKey)
    plaintext = simplified_AES.decrypt(C)
    return plaintext