Exemple #1
0
def Main(port):
    host = "127.0.0.1"

    #Links the socket to the ip and port to allow connection to it
    mySocket = socket.socket()
    mySocket.bind((host, port))

    print("Waiting for connection...")
    mySocket.listen(1)
    conn, addr = mySocket.accept()
    print("Connection from: " + str(addr))
    while True:
        data = conn.recv(1024).decode()

        #Conditionals to decide when to kill the server
        if not data:
            break
        if data == 'q':
            print("Client has ended the session.")
            break

        print("Encrypted text received: " + str(data))

        #Decrypts the encrypted text from the user
        encryptedList = DH.splitBinary(data)
        decryptedBinary = DH.runDecryption(encryptedList)
        output = DH.rebuildString(decryptedBinary)
        output = DH.text_from_bits(output)

        print("Decrypted text: " + output + "\n")

        #Now it is the server's turn to send an encrypted message to the user!
        inputString = input("Enter the message you wish to encrypt:\n -> ")

        #If the server wants to quit, type q to break the loop
        if inputString == "q":
            conn.send('q'.encode())
            break
        else:
            #Converting inital string to binary
            inputString = DH.text_to_bits(inputString)

            #Takes the binary representation of our text, splits it into 8 bit chunks, and encrypts it
            inputList = DH.splitBinary(inputString)
            encryptedBinary = DH.runEncryption(inputList)
            message = DH.rebuildString(encryptedBinary)

            #Sends the encrypted text back to the user
            conn.send(message.encode())

    conn.close()
Exemple #2
0
def needhamSchroeder(conn, connectionInfo):
    aName = connectionInfo[:4]
    bName = connectionInfo[4:8]
    if getUserByID(bName) == -1 or aName == bName:
        conn.send("Invalid ID.".encode())
        return
    conn.send("valid".encode())

    #pulling the user information out of the talkto request
    #converting id's to binary and padding them to be length
    aID = desHelper.text_to_bits(
        getUserByID(aName)[0] + ':' + str(getUserByID(aName)[1]))
    bID = desHelper.text_to_bits(
        getUserByID(bName)[0] + ':' + str(getUserByID(bName)[1]))
    nonce1 = connectionInfo[8:]

    #Create a new nonce to prevent replay attacks
    nonce2 = bin(random.randint(0, 1023))[2:].zfill(10)

    #Generates a 10-bit session key
    sessionKey = bin(generateKey())[2:].zfill(10)

    #Creates the "envelope" that contains the Session Key and A's ID
    #This is encrypted with B's key
    bEnvelope = desHelper.runEncryption(sessionKey + aID + nonce2,
                                        connections[getUserByID(bName)][2])

    #Creates the main "package" that contains the session key, B's id, the nonce, and the envelope
    #This is encrypted with A's key
    aPackage = desHelper.runEncryption(sessionKey + bID + nonce2 + bEnvelope,
                                       connections[getUserByID(aName)][2])

    #Sending the encrypted package to A
    conn.send(aPackage.encode())
    print("NS-Safe package sent.")
    sender = getUserByID(aName)
    connections[getUserByID(bName)][1].send(
        ("INCOMING|" + sender[0] + ":" + "1234").encode())
Exemple #3
0
def connectToServer(host, port):
    mySocket = socket.socket()
    mySocket.connect((host, port))

    #Initializing my DES class, which will perform all major functions
    des = DES.toyDES()

    while True:
        inputString = input("\nEnter the message you wish to encrypt:\n -> ")

        #Exit the server if the command is 'q'
        if inputString == 'q':
            break

        #Converting inital string to binary
        inputString = DH.text_to_bits(inputString)

        #Takes the binary representation of our text, splits it into 8 bit chunks, and encrypts it
        inputList = DH.splitBinary(inputString)
        encryptedBinary = DH.runEncryption(inputList)
        message = DH.rebuildString(encryptedBinary)

        #Sends the encrypted text to the server
        mySocket.send(message.encode())

        print("Waiting for server response...")

        data = str(mySocket.recv(1024).decode())

        if data == 'q':
            print("Server has ended the session.")
            quit(1)

        print('Encrypted text received from server: ' + data)

        #Takes the encrypted binary and turns it back to plaintext
        output = DH.text_from_bits(
            DH.rebuildString(DH.runDecryption(DH.splitBinary(data))))

        print('Decrypted text: ' + output + "\n")

    mySocket.close()
Exemple #4
0
def needhamSchroeder(kdc):
    #Beginning by verifying requested ID is valid
    valid = kdc.recv(1024).decode("utf8")
    if valid != "valid":
        print("Invalid ID requested!")
    else:
        #First step of Needham Schroeder is skipped in this function, as it is handled
        #by inputting 'talkto'

        aPackage = kdc.recv(1024).decode("utf8")

        decodedA = DH.runDecryption(aPackage, KDC_SHARED_KEY)

        #gathering the sessionkey and other things from string
        sessionKey = decodedA[:10]
        bID = decodedA[10:130]
        bID = DH.text_from_bits(bID)
        Nonce2 = decodedA[130:140]

        #This is the still encrypted package with B's needed info inside
        bPacket = decodedA[140:]

        #Now setting up this client as the host of a connection with the client
        mySocket = socket.socket()
        try:
            mySocket.bind((_CHAT_IP,_PORT_NUMBER))
        except:
            print("Bind failed. Error : " + str(sys.exc_info()))
            sys.exit()

        #Waiting for the other to connect
        print("Waiting for connection...")
        mySocket.listen(1)
        conn, addr = mySocket.accept()
        print ("Connection from: " + str(addr))

        #Now that we are connected to B, we verify they are correct by sending them
        #their encrypted envelope.
        conn.send(bPacket.encode())

        testingNonce = conn.recv(1024).decode()
        nonce = DH.runDecryption(testingNonce, sessionKey)

        #Performing our arbitrary f(x) on the nonce, subtract 1 from nonce
        returningNonce = bin(int(nonce, 2)-1)[2:].zfill(8)
        encryptedReturn = DH.runEncryption(returningNonce, sessionKey)
        conn.send(encryptedReturn.encode())
        
        print("Sent verification to other user. Waiting for confirmation.")

        result = conn.recv(1024).decode()
        if result == "verified":
            print("Successful verification. Waiting for message...\n")
            '''
            This section is functionally identical to my homework 1 chatroom implementation
            Once the two are verified, they chat securely through this until one decides to quit
            This chat session uses the session key as it's encryption
            '''
            while True:
                data = conn.recv(1024).decode()

                #Conditionals to decide when to kill the server
                if not data:
                    break
                if data == 'q':
                    print("Client has ended the session.")
                    break

                #print ("Encrypted text received: " + str(data))

                #Decrypts the encrypted text from the user
                decryptedBinary = DH.runDecryption(data, sessionKey)
                output = DH.text_from_bits(decryptedBinary)

                print("\nDecrypted text: " + output)
            
                #Now it is the server's turn to send an encrypted message to the user!
                inputString = input("Enter the message you wish to encrypt:\n -> ")

                #If the server wants to quit, type q to break the loop
                if inputString == "q":
                    conn.send('q'.encode())
                    break
                else:
                    #Converting inital string to binary
                    inputString = DH.text_to_bits(inputString)

                    #Takes the binary representation of our text, splits it into 8 bit chunks, and encrypts it
                    message = DH.runEncryption(inputString, sessionKey)

                    #Sends the encrypted text back to the user
                    conn.send(message.encode())
            conn.close()
        #If Needham schroeder fails, then exit from the server entirely.
        else:
            print("Unable to verify. Exiting server.\n\n")
            conn.close()
            sys.exit()        

        print("\n\nWelcome back to the main server.")
        printInstructions()
        return
Exemple #5
0
def receiveConnection(host, port):
    mySocket = socket.socket()
    mySocket.connect((_CHAT_IP,_PORT_NUMBER))

    print("Connected to another user.")

    #Now we will receive the info from the other user to get the session key
    encryptedInfo = mySocket.recv(1024).decode("utf8")

    #We decrypt that package to gather our session key and the ID of A
    decrypted = DH.runDecryption(encryptedInfo, KDC_SHARED_KEY)

    #Only take the session key and id out, nonce is no longer useful
    sessionKey = decrypted[:10]
    aID = decrypted[10:142]

    #Generate a new nonce to test A with, expecting nonce-1 back
    testingNonce = generateTestNonce()
    encryptedNonce = DH.runEncryption(testingNonce, sessionKey)
    mySocket.send(encryptedNonce.encode())

    #Waiting for A to process
    aVal = mySocket.recv(1024).decode()
    result = DH.runDecryption(aVal, sessionKey)

    #Printing to the user what the other returned
    print("Expected result: ", int(testingNonce,2)-1)
    print("Result from user: "******"Needham-Schroeder complete. Other user verified. Opening secure chatroom.")
        mySocket.send("verified".encode())
        
        while True:
            inputString = input("\nEnter the message you wish to encrypt:\n -> ")

            #Exit the server if the command is 'q'
            if inputString == 'q':
                break

            #Converting inital string to binary
            inputString = DH.text_to_bits(inputString)

            #Takes the binary representation of our text, splits it into 8 bit chunks, and encrypts it
            message = DH.runEncryption(inputString, sessionKey)

            #Sends the encrypted text to the server
            mySocket.send(message.encode())

            print("Waiting for server response...")

            data = str(mySocket.recv(1024).decode())

            if data == 'q':
                print("Server has ended the session.")
                quit(1)

            #print ('Encrypted text received from server: ' + data)

            #Takes the encrypted binary and turns it back to plaintext
            output = DH.text_from_bits(DH.runDecryption(data, sessionKey))

            print ('\nDecrypted text: ' + output)
        mySocket.close()
    else:
        print("Unable to verifiy the indentity of the other user. Exiting server.\n")
        mySocket.send("no".encode())
        mySocket.close()
        sys.exit()