def getKeyFromID(TID): message_to_send = ['1002',TID] enc_socket = socket.socket() enc_socket.connect(('127.0.0.1',9099)) sendMessage(enc_socket,message_to_send) message_received = receiveMessages(enc_socket) print(message_received) enc_socket.close()
def sendDataToServer(message_to_send): server = socket.socket() server.connect(('127.0.0.1', 9098)) sendMessage(server, message_to_send) message_received = receiveMessages(server) server.close() if (message_received): return message_received else: return False
def askForNewKeyandTID(message_to_send,notified_socket): enc_socket = socket.socket() enc_socket.connect(('127.0.0.1',9099)) sendMessage(enc_socket,message_to_send) message_received = receiveMessages(enc_socket) data = None if message_received[0] == '2001' and message_received[1]: data = message_received else: data = ['T1001',False,()] enc_socket.close() sendMessage(notified_socket,data)
def parsePost(s: str, orgId: int, botId: str) -> None: jObject = json.loads(s) chatId = jObject['message']['chatId'] msg = jObject['message']['message'] if (jObject['message']['userId'] == botId): return if (firebasehelper.getData(chatId) == 'null'): res = chatbot.initialize(chatId, 'chatbot', 'chat@bot', 'uofthacksteam2', 'Lu7qXWP3b3d3', jObject['message']['userId']) response = chatbot.parseString(chatId, msg) accessToken = firebasehelper.getDict(chatId)['accessToken'] message.sendMessage(accessToken, chatId, orgId, response)
def priceAlert(): timeInterval = 600.0 threading.Timer(timeInterval, priceAlert).start() print(f'Price checked at {datetime.datetime.now()}') response = requests.get( f"https://theshownation.com/mlb20/apis/listings.json?type=mlb_card&page=6" ).json() for item in response['listings']: if item.get('name') == 'Aroldis Chapman': if item.get('best_sell_price') > 185000: message = "Aroldis Price Reached" sendMessage(message) break
def newMessage(): if not loggedIn(): return json.dumps('fail') content = str(request.form['content']) receiver = str(request.form['receiverUsername']) messageId = message.sendMessage(sender=session['username'], receiver=receiver, title='', content=content) return json.dumps('success')
def newChat(userIds, string, accessToken, hypercareScope, orgId): url = "https://api-prod.hypercare.com/graphql/private" payload = "{\"query\":\"mutation createChat($memberIds: [ID!]!, $title: String) {\\r\\n createChat(members: $memberIds, title: $title) {\\r\\n ...ChatFragment\\r\\n }\\r\\n}\\r\\n\\r\\nfragment ChatFragment on Chat {\\r\\n id\\r\\n title\\r\\n members {\\r\\n ...GeneralUserFragment\\r\\n }\\r\\n lastMessage {\\r\\n ...MessageFragment\\r\\n }\\r\\n lastUnreadMessage {\\r\\n ...MessageFragment\\r\\n }\\r\\n unreadPriorityMessages\\r\\n}\\r\\n\\r\\nfragment GeneralUserFragment on GeneralUser {\\r\\n id\\r\\n username\\r\\n firstname\\r\\n lastname\\r\\n}\\r\\n\\r\\nfragment MessageFragment on Message {\\r\\n id\\r\\n type\\r\\n message\\r\\n sender {\\r\\n ...GeneralUserFragment\\r\\n }\\r\\n dateCreated\\r\\n}\",\"variables\":{\"memberIds\":" + str( userIds).replace("'", "\"") + "}}" headers = { 'hypercare-scope': hypercareScope, 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + accessToken } response = requests.request("POST", url, headers=headers, data=payload) chatId = json.loads(response.text)['data']['createChat']['id'] #sending message message.sendMessage(accessToken, chatId, orgId, string) #payload = "{\"query\":\"mutation removeMember($chatId: ID!, $userId: ID!) {\\n chat(chatId: $chatId) {\\n admin {\\n removeMember(userId: $userId) {\\n ...ChatFragment\\n }\\n }\\n }\\n}\\n\\nfragment ChatFragment on Chat {\\n id\\n title\\n members {\\n ...GeneralUserFragment\\n }\\n lastMessage {\\n ...MessageFragment\\n }\\n lastUnreadMessage {\\n ...MessageFragment\\n }\\n unreadPriorityMessages\\n}\\n\\nfragment GeneralUserFragment on GeneralUser {\\n id\\n username\\n firstname\\n lastname\\n}\\n\\nfragment MessageFragment on Message {\\n id\\n type\\n message\\n sender {\\n ...GeneralUserFragment\\n }\\n dateCreated\\n}\",\"variables\":{\"chatId\":\"" + chatId + "\",\"userId\":\"" + userIds[2] + "\"}}" response = requests.request("POST", url, headers=headers, data=payload) return response.text
def test_message(self): with main.app.app_context(): account.registerUser("testSender", "*****@*****.**", "1234", "10025") account.registerUser("testReceiver", "*****@*****.**", "1234", "10025") message.sendMessage(sender="testSender", receiver="testReceiver", title="message_title", content="message_content") assert "message_title" in json.dumps( message.getMessages(sender="testSender", receiver="testReceiver")) assert "message_title" not in json.dumps( message.getMessages(sender="testReceiver", receiver="testSender")) assert "message_content" in json.dumps( message.getMessagesByUser("testSender")) assert "message_content" in json.dumps( message.getMessagesByUser("testReceiver")) account.deleteUser("testSender") account.deleteUser("testReceiver") print "message test pass"
def readFile(self,time): with open('test.txt', 'r') as file: for line in file: split = line.split(";") process = None process_type = split[2] delay = int(split[1]) if process_type == "1": process = Llamar( split[0], split[3] , split[4]) process.setTimer( split[5] ) process.setDuracion( split[5] ) elif process_type == "2": process = recibirLlamada( split[0], split[3], split[4], split[5] ) elif process_type == "3": process = sendMessage( split[0], split[3], split[5], split[4] ) elif process_type == "4": process = receiveMessage( split[0],split[3],split[5],split[4] ) elif process_type == "5": process = StoreContact ( split[3] , split[0] , split[4].rstrip('\r\n') , split[5].rstrip('\r\n') ) elif process_type == "6": process = Other( split[3] , split[0] , split[4]) elif process_type == "7": process = SendPosition( split[3] , split[0]) elif process_type == "8": process = CheckPosition( split[3] , split[0] , split[4]) elif process_type == "9": process = Play( split[3] , split[0] , split[4]) elif process_type == "10": process = Music( split[3] , split[0] , split[4]) if(process != None): self.scheduler.schedule(time,process,delay) print "> Read file test.txt"
def authenticateUser(secret_number): system('cls') returnValue = True print( "you are required to enter the filename or full path of the filename which contains your private key" ) message_to_send = ['0001', secret_number] server = socket.socket() server.connect(('127.0.0.1', 9098)) sendMessage(server, message_to_send) message_received = receiveMessages(server) if (message_received[0] == '0002'): if (message_received[1] is False): print('no data found in corresponding to the given secret number') exit() puzzle_number = message_received[1] privateKey = None filename = input( 'your private key filename(full path of file with extension) : ') try: privateKey = SigningKey.from_pem(open(filename).read()) except: print( '(BBEMS error: 401) File does not contain any private key information' ) sendMessage(server, ['0010', False]) server.close() exit() signature = privateKey.sign(str(puzzle_number).encode()) message_to_send = ['0010', signature] sendMessage(server, message_to_send) message_received = receiveMessages(server) server.close() if message_received[0] == '0020' and message_received[1]: print('Authentication successful!!!\n') else: print('authentication failed !') returnValue = False else: print('(BBEMS error: 0001) Failed to autenticate user') returnValue = False return returnValue
print(comments) with open(messagesPath, encoding="utf8") as f: messages = [line.rstrip() for line in f] print(messages) with open(tagsPath, encoding="utf8") as f: tags = [line.rstrip() for line in f] print(tags) home = str(Path.home()) chromeOptions = webdriver.chrome.options.Options() chromeProfileDir = home + "\\AppData\\Local\\Google\\Chrome\\New User" print(chromeProfileDir) chromeOptions.add_argument("user-data-dir=" + chromeProfileDir) driver = webdriver.Chrome(options=chromeOptions) usernameList = [] comment = "" for tag in tags: usernames = likePosts(driver, tag, 5, choice(comments)) for username in usernames: if (username not in usernameList): usernameList.append(username) print(usernameList) for name in usernameList: sendMessage(driver, name, choice(messages))
def askForKeyFromTID(message_to_send): enc_socket = socket.socket() enc_socket.connect(('127.0.0.1',9099)) sendMessage(enc_socket,message_to_send) message_received = receiveMessages(enc_socket) return message_received
def serverHandShake(sock, privKey, cert): """ Function used by server's. They execute them after they receive a connection from a client to negotiate encrypt parameter and to authenticate both sides """ mandatoryFields = [] verification = lambda v: all(type(s) == str for s in v) mandatoryFields.append(Field("supportedCiphers", list, verification)) mandatoryFields.append(Field("supportedModes", list, verification)) mandatoryFields.append(Field("supportedPaddings", list, verification)) msg = readMessage(sock, mandatoryFields) cipherAlg = "" for cipher in POSSIB_CIPHERS: if cipher in msg["supportedCiphers"]: cipherAlg = cipher break if cipherAlg == "": raise UnkownAlgorithm("Unkown cipher algorithm") mode = paddingAlg = "" authEncryption = True if cipher not in POSSIB_AUTH_CIPHERS: authEncryption = False if cipher != "ChaCha20": for mod in POSSIB_MODES: if mod in msg["supportedModes"] and not (cipher == "CAST5" and mode == "CTR"): mode = mod break if mode == "": raise UnkownAlgorithm("Unkown cipher mode") if mode == "CBC": for padd in POSSIB_PADDING: if padd in msg["supportedPaddings"]: paddingAlg = padd break if paddingAlg == "": raise UnkownAlgorithm("Unkown padding algorithm") authenticationData = urandom(64) sendMessage( sock, { "chosenCipher": cipherAlg, "chosenMode": mode, "chosenPadding": paddingAlg, "certificate": b64encode(cert.public_bytes(Encoding.PEM)).decode("ascii"), "authenticationData": b64encode(authenticationData).decode("ascii") }) ################################################## mandatoryFields = [] mandatoryFields.append(BytesField("sharedKey")) mandatoryFields.append(BytesField("sessionId")) mandatoryFields.append(BytesField("certificate")) mandatoryFields.append(BytesField("signature")) mandatoryFields.append(BytesField("macKey")) msg = readMessage(sock, mandatoryFields) certBytes = b64decode(bytes(msg["certificate"], "ascii")) valid, cause, clientCert, clientIsServer = assymetric.validCertificate( certBytes) if not valid: raise InvalidCertificate("Client's invalid certificate") if clientIsServer: publicKeyClient = assymetric.PublicKeyServer(clientCert.public_key()) else: publicKeyClient = assymetric.PublicKeyClient(clientCert.public_key()) signature = b64decode(bytes(msg["signature"], "ascii")) try: publicKeyClient.verify(authenticationData, signature) except InvalidSignature: raise FailedClientAuthentication("Failed to authenticate client") try: sharedKey = privKey.decrypt(b64decode(bytes(msg["sharedKey"], "ascii"))) sessionId = privKey.decrypt(b64decode(bytes(msg["sessionId"], "ascii"))) sessionId = int(sessionId.hex(), 16) macKey = None if not authEncryption: macKey = privKey.decrypt(b64decode(bytes(msg["macKey"], "ascii"))) except: raise FailedDescrytingKeys("Decryption of shared keys failed") symmetricEncryption = None if cipherAlg in POSSIB_AUTH_CIPHERS: symmetricEncryption = symetric.AuthenticatedEncryption( getattr(aead, cipherAlg), sharedKey) else: if cipherAlg == "ChaCha20": symmetricEncryption = symetric.StreamEncryption(sharedKey, macKey) else: if mode == "CBC": symmetricEncryption = symetric.PaddedEncryption( getattr(algorithms, cipherAlg), sharedKey, macKey, getattr(padding, paddingAlg)) else: symmetricEncryption = symetric.NonPaddedEncryption( getattr(algorithms, cipherAlg), sharedKey, macKey, getattr(modes, mode)) ################################################## mandatoryFields = [] mandatoryFields.append(Field("handshake finish", str)) msg = readMessage(sock, mandatoryFields, symmetricEncryption, sessionId, 1) sendEncryptedMessage(sock, {"handshake finish": ""}, symmetricEncryption, sessionId, 2) return symmetricEncryption, clientCert, clientIsServer, sessionId
def clientHandShake(sock, privKey, cert, supportCiphers, supportModes, supportPadding): """ """ sendMessage( sock, { "supportedCiphers": supportCiphers, "supportedModes": supportModes, "supportedPaddings": supportPadding }) ################################################## mandatoryFields = [] mandatoryFields.append(BytesField("certificate")) mandatoryFields.append(BytesField("authenticationData")) mandatoryFields.append(Field("chosenCipher", str)) mandatoryFields.append(Field("chosenMode", str)) mandatoryFields.append(Field("chosenPadding", str)) msg = readMessage(sock, mandatoryFields) certBytes = b64decode(bytes(msg["certificate"], "ascii")) valid, cause, serverCert, clientIsServer = assymetric.validCertificate( certBytes) if not clientIsServer: raise Exception #TODO if not valid: raise InvalidCertificate("Server's certificate not valid") cipher = msg["chosenCipher"] mode = msg["chosenMode"] paddingAlg = msg["chosenPadding"] sharedKey = macKey = symmetricEncryption = None if cipher not in supportCiphers: raise UnkownAlgorithm("Unkown cipher algorithm") elif cipher in POSSIB_AUTH_CIPHERS: #see if it's a cipher algorithm with authentication cipher = getattr(aead, cipher) sharedKey = urandom(32) symmetricEncryption = symetric.AuthenticatedEncryption( cipher, sharedKey) else: # if it's a valid algorithm macKey = urandom(SHA256.digest_size) if cipher == "ChaCha20": cipher = algorithms.ChaCha20 sharedKey = urandom(int(max(cipher.key_sizes) / 8)) symmetricEncryption = symetric.StreamEncryption(sharedKey, macKey) else: cipher = getattr(algorithms, cipher) if cipher == algorithms.AES: sharedKey = urandom(32) else: sharedKey = urandom(int(max(cipher.key_sizes) / 8)) if mode not in supportModes: raise UnkownAlgorithm("Unkown cipher mode") elif mode == "CBC": if paddingAlg not in supportPadding: raise UnkownAlgorithm("Unkown padding algorithm") symmetricEncryption = symetric.PaddedEncryption( cipher, sharedKey, macKey, getattr(padding, paddingAlg)) else: symmetricEncryption = symetric.NonPaddedEncryption( cipher, sharedKey, macKey, getattr(modes, mode)) publicKeyServer = assymetric.PublicKeyServer(serverCert.public_key()) encryptedSharedKey = publicKeyServer.encrypt(sharedKey) authenticationData = b64decode(bytes(msg["authenticationData"], "ascii")) signature = privKey.sign(authenticationData) sessionId = urandom(32) encryptedSessionId = publicKeyServer.encrypt(sessionId) msg = { "sharedKey": b64encode(encryptedSharedKey).decode("ascii"), "sessionId": b64encode(encryptedSessionId).decode("ascii"), "certificate": b64encode(cert.public_bytes(Encoding.PEM)).decode("ascii"), "signature": b64encode(signature).decode("ascii") } if macKey != None: encryptedMacKey = publicKeyServer.encrypt(macKey) msg["macKey"] = b64encode(encryptedMacKey).decode("ascii") else: msg["macKey"] = "" sendMessage(sock, msg) ################################################## sessionId = int(sessionId.hex(), 16) sendEncryptedMessage(sock, {"handshake finish": ""}, symmetricEncryption, sessionId, 1) ################################################## mandatoryFields = [] mandatoryFields.append(Field("handshake finish", str)) msg = readMessage(sock, mandatoryFields, symmetricEncryption, sessionId, 2) return symmetricEncryption, sessionId
print(f"connection established with {client_socket}") socket_list.append(client_socket) else: message_received = receiveMessages(notified_socket) if message_received is False: print(f"disconnected from {notified_socket}") socket_list.remove(notified_socket) else: if message_received[0] == '1111': print("new registration save karna hai") secret_number = message_received[1][0] grade = message_received[1][1] public_key = message_received[1][2] value = saveRegistrationDataInDatabase(secret_number,public_key,grade) message_to_send = ['2111',value] sendMessage(notified_socket,message_to_send) elif message_received[0] == '1112': secret_number = message_received[1] value = getRegistrationDetailsFromDatabase(secret_number) print(value) message_to_send = ['2222',value[0]] sendMessage(notified_socket,message_to_send) elif message_received[0] == '0001': secret_number = message_received[1] data = getRegistrationDetailsFromDatabase(secret_number) if(data is False): message_to_send = ['0002',data] sendMessage(notified_socket,message_to_send) else: public_key = data[0][1] public_key = VerifyingKey.from_pem(public_key)
def enviarMsje(self,time): print "Waiting to run send msg..." process = sendMessage("enviar_msje",0,"","") self.scheduler.schedule(time,process,1)
"tennis.jpg", "location": "Kansas", "description": "I start to play tennis recently, and I need a defender tennis racquet. I don't have specific brand requirement, but make sure the tennis is in good condition. The price is negotiable" }) with main.app.app_context(): # add users for user in users: if user['username'] == 'system': users.remove(user) account.registerUser(user["username"], user["email"], user["password"], user["zipcode"]) message.sendMessage(receiver=user["username"], content="Hello, " + user["username"] + ". Welcome to sponge!") # add posts for item in sellerPosts: image = open(os.path.join("image", item["image"]), "r") post.createPost(item["title"], item["description"], item["category"], item["price"], item["location"], image.read(), random.choice(users)["username"], "Seller") image.close() for item in buyerPosts: image = open(os.path.join("image", item["image"]), "r") post.createPost(item["title"], item["description"], item["category"], item["price"], item["location"], image.read(), random.choice(users)["username"], "Buyer") image.close()