def postMessage(message, to_uid): print( f"Posting message to {USERS[to_uid]['fname']} {USERS[to_uid]['lname']}..." ) route = 'postMessage' url = f"{API}{route}&token={TOKEN}&uid={UID}" A = Crypto() A.load_keys(PUBKEYS[to_uid]['pubkey']) encrypted = A.encrypt(message) encrypted_bytes = base64.b64encode(encrypted) message = encrypted_bytes.decode('utf-8') payload = { 'uid': UID, 'to_uid': to_uid, 'message': message, 'token': TOKEN } headers = {'Content-Type': 'application/json'} r = requests.post(url, headers=headers, json=payload) return r.json()
def getMessages(count=1, latest=True): """ Gets decrypted messages from the server. """ print("Checking for new messages...") route = 'getMessage' url = f"{API}{route}&token={TOKEN}&uid={UID}&count={count}" r = requests.get(url) D = Crypto() D.load_keys(priv_file="my_private_key.txt") messages = r.json() messages = messages[ 'data'] # get all the messages received from other users for message in messages: fid, received = message['fid'], message[ 'message'] # grabs most recent message and user's id received_bytes = received.encode('utf-8') # prepares message received = base64.decodebytes(received_bytes) # for decryption try: decrypted = D.decrypt(received) #decrypts message print(f"\nfrom: {USERS[fid]['fname']} {USERS[fid]['lname']}") print("message:", decrypted, '\n') except ValueError: print(f"\nfrom: {USERS[fid]['fname']} {USERS[fid]['lname']}") print("message:", received, '\n')
def postMessage(message, to_uid): route = 'postMessage' url = f"{API}{route}&token={TOKEN}&uid={UID}" # to encrypt the message lets use the Crypto class C = Crypto() # to load the public key for encryption C.load_keys(KEYS[to_uid]['pubkey']) encryptedMessage = C.encrypt(message) # to make sure that text is in bytes format Byte_text = base64.b64encode(encryptedMessage) message = Byte_text.decode('utf-8') payload = { 'uid': UID, 'to_uid': to_uid, 'message': message, 'token': TOKEN } headers = {'Content-Type': 'application/json'} r = requests.post(url, headers=headers, json=payload) return r.json()