def __init__(self, ip, port):
     try:
         flag = True
         pukeyFile = open('User/public_key.pem', 'rb')
         prkeyFile = open('User/private_key.pem', 'rb')
         self.pukey = pukeyFile.read()
         self.prkey = prkeyFile.read()
         pukeyFile.close()
         prkeyFile.close()
         #generating DH keys
         prDHKey = random.randint(100, 1000)
         #Setting up socket
         server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         server.connect((ip, int(port)))
         server.send("User")
         brokerPbKey = exchangePublicKey(server, self.pukey)
         if brokerPbKey:
             print "User - Broker Key exchange successful"
             #Diffie-Hellman Key Exchange Starts here
             sendData(getDHkey(prDHKey), server, brokerPbKey)
             data = decryptMsg(server.recv(1024), self.prkey)
             brokerSessionKey = getSessionKey(data, prDHKey)
             brokerSessionKey = getHash(brokerSessionKey)
             print "DH Authentication successful"
             while flag:
                 flag = connectBroker(server, brokerSessionKey, self.prkey,
                                      prDHKey)
         else:
             print "Issue in broker key"
     except Exception as e:
         print e
Example #2
0
 def __init__(self):
     try:
         pukeyFile = open('Broker/public_key.pem', 'rb')
         prkeyFile = open('Broker/private_key.pem', 'rb')
         self.pukey = pukeyFile.read()
         self.prkey = prkeyFile.read()
         pukeyFile.close()
         prkeyFile.close()
         server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         port = int(raw_input("Enter port to start broker server: "))
         server.bind(('', port))
         print "socket binded to %s" % (port)
         threads = []
         while True:
             server.listen(4)
             print "socket is listening"
             # Establish connection with client.
             client, addr = server.accept()
             print 'Got connection from', addr
             clienttype = client.recv(4096)
             print clienttype
             if clienttype == "User":
                 clienttype = ""
                 print "User Connected"
                 userPbKey = exchangeUserRSAPbKey(client, self.pukey)
                 if userPbKey:
                     #Diffie-Hellman Key Exchange Starts here
                     data = decryptMsg(client.recv(1024), self.prkey)
                     sendData(getDHkey(prDHkey), client, userPbKey)
                     userBrokerSessionKey = getSessionKey(data, prDHkey)
                     userBrokerSessionKey = getHash(userBrokerSessionKey)
                     twrv = threadCustom.CustomThread(
                         target=onUserConnect,
                         args=(client, userBrokerSessionKey, userPbKey,
                               self.pukey, self.prkey))
                     twrv.start()
                     threads.append(twrv)
         for t in threads:
             t.join()
     except Exception as e:
         client.close()
def onBrokerConnect(client, addr, sellerId):
    try:
        key = generateRSAkey()
        pukey = key.publickey().exportKey()
        brokerPbKey = exchangeRSAPbKey(client, pukey)
        prDHkey = random.randint(100, 1000)
        if brokerPbKey:
            print "Received Seller Public key"
            #Diffie-Hellman Key Exchange Starts here
            data = decryptMsg(client.recv(1024), key)
            sendData(getDHkey(prDHkey), client, brokerPbKey)
            nounceHash = getHash(getSessionKey(data, prDHkey))
            brokerNounceHash = decryptMsg(client.recv(1024), key)
            if brokerNounceHash == nounceHash:
                sendData("ACK", client, brokerPbKey)
                data = client.recv(2048)
                if data and "Error" not in data:
                    #DH Authentication Successful and Now can transmit messages
                    userPbKey = data
                    print "Received User key in Seller"
                    print userPbKey
                    client.send("ACK")
                    data = decryptMsg(client.recv(1024), key)
                    prDHkey = random.randint(5, 10)
                    sessionKey = getSessionKey(data, prDHkey)
                    nounceHash = getHash(sessionKey)
                    sendData(
                        str(getDHkey(prDHkey)) + "~" + str(nounceHash), client,
                        userPbKey)
                    data = client.recv(1024)
                    ack = AESCipher(sessionKey).decrypt(data)
                    if ack == "NOUNCE VERIFIED":
                        print "Seller Authentication by User completed"
                        broucher = """Below are the paintings available to buy
                            Sr no.            Model                     Price
                            1)                Mona Lisa                 $970
                            2)                The Starry Night          $880
                            3)                The Night Watch           $920
                            4)                Impression, Sunrise       $810"""
                        encryptMsg = AESCipher(sessionKey).encrypt(broucher)
                        client.send(encryptMsg)
                        data = client.recv(1024)
                        userinp = AESCipher(sessionKey).decrypt(data)
                        userinp = int(userinp)
                        price = 0
                        if userinp == 1:
                            price = 970
                        elif userinp == 2:
                            price = 880
                        elif userinp == 3:
                            price = 920
                        elif userinp == 4:
                            price = 810
                        data = AESCipher(sessionKey).encrypt(
                            str(price) + ";" + str(sellerId))
                        client.send(data)
                        data = decryptMsg(client.recv(1024), key)
                        if ("Paid " + str(price)) in data:
                            jpgdata = ''
                            inf = open('sellerImg/' + str(userinp) + '.jpg',
                                       'rb')
                            jpgdata = base64.b64encode(inf.read())
                            size = len(jpgdata)
                            client.send(
                                AESCipher(sessionKey).encrypt("SIZE %s" %
                                                              size))
                            ackSize = AESCipher(sessionKey).decrypt(
                                client.recv(1024))
                            if str(ackSize) == "GOT SIZE":
                                encryptMsg = AESCipher(sessionKey).encrypt(
                                    jpgdata)
                                client.send(encryptMsg)
                            inf.close()
                            client.close()
                        else:
                            print "Transaction Aborted"
                            client.close()
                    else:
                        print "Seller Authentication by user failed"
                        client.close()
                else:
                    print "Nounce didn't match between user and brokers"
                    client.close()
            else:
                print "Nounce exchange failed"
                client.close()
    except Exception as e:
        client.close()
        print "Unable to process user message in broker"
        print e
    return None
Example #4
0
def onUserConnect(client, userBrokerSessionKey, userPbKey, pukey, prkey):
    brokerFlag = True
    while brokerFlag:
        sellerFlag = True
        ipadd = decryptAESData(client, userBrokerSessionKey)
        #DH Authentication Successful and Now can transmit messages
        #Now get Seller Ip address from the user and connect to the Seller
        print ipadd
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        port = int(ipadd.split(":")[1])
        server.connect((ipadd.split(":")[0], port))
        server.send("Broker")
        sellerPbKey = exchangeSellerRSAPbKey(server, pukey)
        print "Seller Pb Key received"
        print sellerPbKey
        if sellerPbKey:
            #Diffie-Hellman Key Exchange Starts here
            sendData(getDHkey(prDHkey), server, sellerPbKey)
            print "Broker - Seller Key Exchange successful"
            print "DH exchange starts"
            data = decryptMsg(server.recv(1024), prkey)
            sellerNounce = getHash(getSessionKey(data, prDHkey))
            print "DH Authentication successful"
            client.send(sellerPbKey)
            #client.send(sellerPbKey)
            userSellerPbKey = client.recv(1024)
            server.send(userSellerPbKey)
            print userSellerPbKey
            sellerDhKey = server.recv(2048)
            client.send(sellerDhKey)
            userDhkey = client.recv(1024)
            server.send(userDhkey)
            while sellerFlag:
                broucher = recv_msg(server)
                send_msg(client, broucher)
                userinp = recv_msg(client)
                send_msg(server, userinp)
                price = recv_msg(server)
                send_msg(client, price)
                data = decryptAESData(client, userBrokerSessionKey)
                dbTransact = data.split("~")[0]
                sign = data.split("~")[1]
                date = str(
                    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                if "No Purchase" not in data and verifySign(
                        dbTransact, userPbKey, sign):
                    print "User authenticated Seller"
                    price = dbTransact.split(";")[0]
                    if price:
                        confFile = open("paymentDB/payment.csv", "a")
                        data = str(
                            getHash(pukey) + ";" + dbTransact + ";" + date +
                            ";" + sign + ";" + sellerPbKey)
                        confFile.write(data.replace(";", ","))
                        confFile.write("\n")
                        confFile.close()
                        sendAESData("Paid " + str(price), server, sellerNounce)
                        img = recv_msg(server)
                        send_msg(client, img)
                        repeatq = recv_msg(server)
                        send_msg(client, repeatq)
                        data = decryptAESData(client, userBrokerSessionKey)
                        sendAESData(data.split(":B")[1], server, sellerNounce)
                        print data.split(":B")[0]
                        if data.split(":B")[0] == "broker":
                            print "Ending connection with seller"
                            sellerFlag = False
                        elif data.split(":B")[0] == "quit":
                            sellerFlag = False
                            brokerFlag = False
                        else:
                            print "Continuing connection with seller"
                else:
                    print "Purchase Aborted."
                    server.close()
                    client.close()
    return None
Example #5
0
 def __init__(self,ip,port,userId):
     try:
         self.id = userId
         key = generateRSAkey()
         self.pukey = key.publickey().exportKey()
         self.prkey = key.exportKey()
         #generating DH keys
         prDHKey = random.randint(100,1000)
         self.sessionKey = ""
         #Setting up socket
         server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
         server.connect((ip,int(port)))
         server.send("User")
         brokerPbKey = exchangePublicKey(server, self.pukey)
         if brokerPbKey:
             print "User - Broker Key exchange successful"
             #Diffie-Hellman Key Exchange Starts here
             sendData(getDHkey(prDHKey), server, brokerPbKey)
             data = decryptMsg(server.recv(1024), key)
             brokerSessionKey = getSessionKey(data, prDHKey)
             sendData(getHash(brokerSessionKey), server, brokerPbKey)
             ack = decryptMsg(server.recv(1024), key)
             if ack == "ACK":
                 print "DH Authentication successful"
                 inp = raw_input("Enter the Seller IP address & port (format:-ipaddress:port): ")
                 sendData(inp, server, brokerPbKey)
                 sellerPbKey = ""
                 sellerPbKey = server.recv(2048)
                 print "Received Seller key in User"
                 print sellerPbKey
                 server.send("ACK")
                 prDHKey = random.randint(100,1000)
                 sendData(getDHkey(prDHKey), server, sellerPbKey)
                 sellerNounce = decryptMsg(server.recv(2048), key)
                 nounce = getSessionKey(sellerNounce.split("~")[0], prDHKey)
                 if getHash(nounce) == sellerNounce.split("~")[1]:
                     data = AESCipher(nounce).encrypt("NOUNCE VERIFIED")
                     server.send(data)
                     data = server.recv(2048)
                     broucher = AESCipher(nounce).decrypt(data)
                     print broucher
                     inp = raw_input("Press the number to select any product: ")
                     data = AESCipher(nounce).encrypt(inp)
                     server.send(data)
                     data = server.recv(1024)
                     price = AESCipher(nounce).decrypt(data)
                     sellerId = price.split(";")[1]
                     price = price.split(";")[0]
                     print "Price of the product you want to buy is $" + str(price)
                     time.sleep(0.5)
                     inp = raw_input("Are you sure you want to buy? [Y/N]: ")
                     date = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                     dbTransact = str(self.id+";"+price+";"+sellerId+";"+date)
                     sign = signData(dbTransact, self.prkey)
                     if inp == "Y":
                         data = AESCipher(getHash(brokerSessionKey)).encrypt(dbTransact+"~"+sign)
                         server.send(data)
                         data = server.recv(2048)
                         imgSize = AESCipher(nounce).decrypt(data)
                         print imgSize
                         if imgSize.startswith('SIZE'):
                             tmp = imgSize.split()
                             size = int(tmp[1])
                             print 'got size'
                             print 'size is %s' % size
                             data = AESCipher(nounce).encrypt("GOT SIZE")
                             server.send(data)
                             imgData = server.recv(40960000)
                             imageString = AESCipher(nounce).decrypt(imgData)
                             output_file = open("Output/output_"+self.id+".jpg", "wb")
                             output_file.write(imageString.decode('base64'))
                             output_file.close()
                             server.close()
                             print "Transaction completed successfully. Hope to see you soon again"
                         else:
                             print "Error in getting image size"
                             server.close()
                     else:
                         sendData("No Purchase", server, key)
                 else:
                     data = AESCipher(nounce).encrypt("NOUNCE MISMATCH")
                     server.send(data)
                     print "Unable to authenticate seller"
                     server.close()                
             else:
                 sendData("Error", server, brokerPbKey)
         else:
             print "Improper Broker Public key"
             server.close()
     except Exception as e:
         print e
         server.close()
def onBrokerConnect(client, pukey, prkey):
    repeatFlag = True
    try:
        brokerPbKey = exchangeRSAPbKey(client, pukey)
        prDHkey = random.randint(100, 1000)
        if brokerPbKey:
            print "Received Broker Public key"
            #Diffie-Hellman Key Exchange Starts here
            data = decryptMsg(client.recv(1024), prkey)
            sendData(getDHkey(prDHkey), client, brokerPbKey)
            brokerSessionkey = getHash(getSessionKey(data, prDHkey))
            print "DH Authentication successful"
            userEphemeralkey = client.recv(1024)
            #userEphemeralkey = client.recv(1024)
            prDHkey = random.randint(100, 1000)
            sendData(getDHkey(prDHkey), client, userEphemeralkey)
            data = decryptMsg(client.recv(2048), prkey)
            randUserSellerNounce = getSessionKey(data, prDHkey)
            userSessionKey = getHash(randUserSellerNounce)
            print "Seller DH key received"
            broucher = """Below are the paintings available to buy
                Sr no.            Model                     Price
                1)                Mona Lisa                 $970
                2)                The Starry Night          $880
                3)                The Night Watch           $920
                4)                Impression, Sunrise       $810"""
            while repeatFlag:
                randUserSellerNounce = int(randUserSellerNounce) + 1
                sendAESData(
                    broucher, client,
                    getAESRandSessionKey(userSessionKey, randUserSellerNounce))
                randUserSellerNounce = int(randUserSellerNounce) + 1
                userinp = decryptAESData(
                    client,
                    getAESRandSessionKey(userSessionKey, randUserSellerNounce))
                userinp = int(userinp)
                price = 0
                if userinp == 1:
                    price = 970
                elif userinp == 2:
                    price = 880
                elif userinp == 3:
                    price = 920
                elif userinp == 4:
                    price = 810
                randUserSellerNounce = int(randUserSellerNounce) + 1
                sendAESData(
                    str(price), client,
                    getAESRandSessionKey(userSessionKey, randUserSellerNounce))
                data = decryptAESData(client, brokerSessionkey)
                if ("Paid " + str(price)) in data:
                    jpgdata = ''
                    inf = open('sellerImg/' + str(userinp) + '.jpg', 'rb')
                    jpgdata = base64.b64encode(inf.read())
                    size = len(jpgdata)
                    randUserSellerNounce = int(randUserSellerNounce) + 1
                    sendAESData(
                        jpgdata, client,
                        getAESRandSessionKey(userSessionKey,
                                             randUserSellerNounce))
                    inf.close()
                    randUserSellerNounce = int(randUserSellerNounce) + 1
                    time.sleep(1)
                    sendAESData(
                        "Do you want to continue shopping?", client,
                        getAESRandSessionKey(userSessionKey,
                                             randUserSellerNounce))
                    data = decryptAESData(client, brokerSessionkey)
                    data = RSA.importKey(prkey).decrypt(eval(data))
                    if data == "N":
                        repeatFlag = False
                        print "Closing connection"
                        client.close()
                else:
                    print "Transaction Aborted"
    except Exception as e:
        client.close()
        print "Unable to process user message in Seller"
        print e
    return None
def onUserConnect(client, addr):
    try:
        key = generateRSAkey()
        pukey = key.publickey().exportKey()
        userPbKey = exchangeUserRSAPbKey(client, pukey)
        if userPbKey:
            #Diffie-Hellman Key Exchange Starts here
            data = decryptMsg(client.recv(1024), key)
            sendData(getDHkey(prDHkey), client, userPbKey)
            userBrokerNounce = getSessionKey(data, prDHkey)
            nounceHash = getHash(userBrokerNounce)
            userNounceHash = decryptMsg(client.recv(1024), key)
            if userNounceHash == nounceHash:
                sendData("ACK", client, userPbKey)
                ipadd = decryptMsg(client.recv(1024), key)
                if "Error" not in data:
                    #DH Authentication Successful and Now can transmit messages
                    #Now get Seller Ip address from the user and connect to the Seller
                    print ipadd
                    brokerRsaKey = generateRSAkey()
                    brokerPuKey = brokerRsaKey.publickey().exportKey()
                    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    port = int(ipadd.split(":")[1])
                    server.connect((ipadd.split(":")[0], port))
                    server.send("Broker")
                    sellerPbKey = exchangeSellerRSAPbKey(server, brokerPuKey)
                    print "Seller Pb Key received"
                    print sellerPbKey
                    if sellerPbKey:
                        #Diffie-Hellman Key Exchange Starts here
                        sendData(getDHkey(prDHkey), server, sellerPbKey)
                        print "Broker - Seller Key Exchange successful"
                        print "DH exchange starts"
                        data = decryptMsg(server.recv(1024), brokerRsaKey)
                        nounce = getSessionKey(data, prDHkey)
                        sendData(getHash(nounce), server, sellerPbKey)
                        ack = decryptMsg(server.recv(1024), brokerRsaKey)
                        if ack == "ACK":
                            print "DH Authentication successful"
                            server.send(userPbKey)
                            client.send(sellerPbKey)
                            ackUser = client.recv(3)
                            ackSeller = server.recv(1024)
                            print ackSeller
                            print ackUser
                            if ackUser == "ACK" and ackSeller == "ACK":
                                data = client.recv(1024)
                                server.send(data)
                                print "Nounce exchange in Process between Seller and User"
                                data = server.recv(2048)
                                client.send(data)
                                ack = client.recv(1024)
                                server.send(ack)
                                broucher = server.recv(2048)
                                client.send(broucher)
                                userinp = client.recv(1024)
                                server.send(userinp)
                                price = server.recv(1024)
                                client.send(price)
                                data = AESCipher(nounceHash).decrypt(
                                    client.recv(1024))
                                dbTransact = data.split("~")[0]
                                if "No Purchase" not in data and verifySign(
                                        dbTransact, userPbKey,
                                        data.split("~")[1]):
                                    print "User authenticated Seller"
                                    price = dbTransact.split(";")[1]
                                    if price:
                                        confFile = open(
                                            os.path.join(
                                                os.path.abspath(
                                                    '.\\paymentDB'),
                                                "payment.csv"), "a")
                                        data = str(dbTransact)
                                        confFile.write(
                                            dbTransact.replace(";", ","))
                                        confFile.write("\n")
                                        confFile.close()
                                        sendData("Paid " + str(price), server,
                                                 sellerPbKey)
                                        size = server.recv(1024)
                                        client.send(size)
                                        data = client.recv(1024)
                                        server.send(data)
                                        img = server.recv(40960000)
                                        client.send(img)
                                        client.close()
                                        server.close()
                                else:
                                    print "Purchase Aborted. Closing the Servers"
                                    client.close()
                                    server.close()
                            else:
                                print "Unable to get acks for public key exchange between seller and user"
                                server.close()
                                client.close()
                        else:
                            sendData("Error", server, sellerPbKey)
                            server.close()
                            client.close()
                else:
                    print "Nounce didn't match between user and brokers"
                    client.close()
            else:
                print "Nounce exchange failed"
                client.close()
    except Exception as e:
        client.close()
        print "Unable to process user message in broker"
        print e
    return None
def connectBroker(server, brokerSessionKey, prkey, prDHkey):
    flag = True
    inp = raw_input(
        "Enter the Seller IP address & port (format:-ipaddress:port): ")
    sendAESData(inp, server, brokerSessionKey)
    sellerPbKey = server.recv(1024)
    print "Received Seller key in User"
    print sellerPbKey
    userSellerkey = generateRSAkey()
    userSellerPbkey = userSellerkey.publickey().exportKey()
    userSellerPrkey = userSellerkey.exportKey()
    #sendData(str(userSellerPbkey), server, sellerPbKey)
    server.send(userSellerPbkey)
    time.sleep(0.1)
    sellerNounce = decryptMsg(server.recv(2048), userSellerPrkey)
    prDHKey = random.randint(100, 1000)
    sendData(getDHkey(prDHKey), server, sellerPbKey)
    randUserSellerNounce = getSessionKey(sellerNounce, prDHKey)
    sellerSessionKey = getHash(randUserSellerNounce)
    rep = True
    while rep:
        randUserSellerNounce = int(randUserSellerNounce) + 1
        broucher = decryptAESData(
            server, getAESRandSessionKey(sellerSessionKey,
                                         randUserSellerNounce))
        print broucher
        inp = raw_input("Choose any product by its Serial Number: ")
        inpflag = False
        while inpflag == False:
            if (int(inp) > 4 or int(inp) < 1):
                print "Invalid Input. Try again"
                inp = raw_input("Choose any product by its Serial Number: ")
            else:
                inpflag = True
        randUserSellerNounce = int(randUserSellerNounce) + 1
        sendAESData(
            inp, server,
            getAESRandSessionKey(sellerSessionKey, randUserSellerNounce))
        randUserSellerNounce = int(randUserSellerNounce) + 1
        price = decryptAESData(
            server, getAESRandSessionKey(sellerSessionKey,
                                         randUserSellerNounce))
        print "Price of the product you want to buy is $" + str(price)
        inp = raw_input("Are you sure you want to buy? [Y/N]: ")
        dbTransact = str(price)
        sign = signData(dbTransact, prkey)
        if inp.upper() == "Y":
            sendAESData(dbTransact + "~" + sign, server, brokerSessionKey)
            randUserSellerNounce = int(randUserSellerNounce) + 1
            imageString = decryptAESData(
                server,
                getAESRandSessionKey(sellerSessionKey, randUserSellerNounce))
            output_file = open(
                "Output/output_buyer" + str(random.randint(10, 1000)) + ".jpg",
                "wb")
            output_file.write(imageString.decode('base64'))
            output_file.close()
            randUserSellerNounce = int(randUserSellerNounce) + 1
            msg = decryptAESData(
                server,
                getAESRandSessionKey(sellerSessionKey, randUserSellerNounce))
            print msg
            inp = raw_input("Press Y to continue else press N: ")
            if inp.upper() != "Y":
                rep = False
                inp = raw_input(
                    "Do you want to connect another seller [Y/N]: ")
                if inp.upper() != "Y":
                    flag = False
                    print "Bye!"
                    add = RSA.importKey(sellerPbKey).encrypt("N", 32)
                    sendAESData("quit:B" + str(add), server, brokerSessionKey)
                else:
                    add = RSA.importKey(sellerPbKey).encrypt("N", 32)
                    data = "broker:B" + str(add)
                    sendAESData(data, server, brokerSessionKey)
            else:
                add = RSA.importKey(sellerPbKey).encrypt("Y", 32)
                data = "seller:B" + str(add)
                sendAESData(data, server, brokerSessionKey)
        else:
            sendData("No Purchase", server, prkey)
    return flag