def new_transaction(): tx_data = request.get_json() required_fields = ["sender", "receiver", "pubkey"] # print(tx_data) for field in required_fields: if not tx_data.get(field): return "Invlaid transaction data", 403 if "value" not in tx_data: tx_data["value"] = MIN_COINS tx_data["pubkey"] = clean_key(tx_data["pubkey"]) tx_data["timestamp"] = time.time() if "message" in tx_data: tx_data["message"] = encryption.encrypt_message( bytes(tx_data["message"], encoding="utf-8"), encryption.read_public_key_string( tx_data.pop("pubkey", None).encode("ascii"))) else: tx_data["message"] = "**TRANSFER**" blockchain.add_new_transaction(tx_data) # print(tx_data) # t = Transaction(tx_data["sender"], tx_data["receiver"], tx_data["value"], tx_data["message"], tx_data["timestamp"]) # db.session.add(t) # db.session.commit() print("start mining") blockchain.mine(storage) return "Success", 201
def send_message(CID, UDP_port, host_address, s, message, key, data_remaining): ''' Sending a message to a specific UDP port by packing a complete UDP packet with all the necessary fields. :param CID: Client identification number to be recognized by the server whenever the client wants to send a message :param UDP_port: UDP port where the message is going to be directed :param host_address: Server address that is going to receive the message from the client :param s: Socket where the sending message occures :param message: Message to be sent to the server :param key: Specific key used to encode the message :param data_remaining: In multipart feature, this value tells how many bytes are left to be sent to the server ''' ack = True eom = False encrypted_message = encryption.encrypt_message(message, key) length = len(message) data = struct.pack('!8s??HH64s', bytes(CID, 'utf-8'), ack, eom, data_remaining, length, bytes(encrypted_message, 'utf-8')) s.sendto(data, (host_address, int(UDP_port)))
def add_details(): website = website_entry.get().title() email = email_entry.get() password = password_entry.get() new_data = { website: { "email": email, "password": encryption.encrypt_message(password) } } if len(website) == 0 or len(email) == 0 or len(password) == 0: messagebox.showerror( title="Empty Fields", message="Please make sure you haven't left any fields empty") return # messagebox.showinfo(title="Title", message="This is a message") is_ok = messagebox.askokcancel(title=f"Confirm details for {website}", message=f"Details entered: " f"\n\nEmail : {email}\n" f"Password : {password} " f"\n\nIs it ok to save?") if is_ok: try: # When the file is not present or is empty with open("data.json", "r") as file: data = json.load(file) except (FileNotFoundError, json.decoder.JSONDecodeError): data = new_data else: data.update(new_data) finally: with open("data.json", "w") as file: json.dump(data, file, indent=4) website_entry.delete(0, 'end') password_entry.delete(0, 'end') website_entry.focus()
def received_data(s, key): ''' Receiving a message from the socket connected to the UDP port of the server :param s: Socket used for listening the server messages :param key: Key used to decode the message received from the server :return words: Part of the message received from the server :return EOM: Flag used by the server to close the communication client-server :return data_remaining: How many bytes remain to be received from the server ''' #print("Received part:") received_package = struct.unpack('!8s??HH64s', s.recv(1024)) EOM = received_package[2] data_remaining = received_package[3] received_message = received_package[5] #print(received_message) #print(key) received_message = received_message.decode('UTF-8') received_message = received_message.rstrip('h\00') if EOM is not True: words = encryption.encrypt_message(received_message, key) #print(words) else: words = received_message return words, EOM, data_remaining
if msg_length: msg_length = int(msg_length) message = encryption.decrypt_message(sock.recv(msg_length), KEY).decode(FORMAT) sender_length = int(sock.recv(HEADER).decode(FORMAT)) sender = sock.recv(sender_length).decode(FORMAT) print(f"\n{sender}: {message}\nYou({name}): ", end='') except OSError as e: print(e) break if __name__ == '__main__': client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) name = input("Enter your nickname: ") send_message(name.encode(FORMAT), client) receive_thread = threading.Thread(target=message_receiver, args=(name, client)) receive_thread.start() while True: try: msg = encryption.encrypt_message( input(f'You({name}): ').encode(FORMAT), KEY) send_message(msg, client) except KeyboardInterrupt: send_message(DISCONNECT_MESSAGE.encode(FORMAT), client) client.close() break receive_thread.join()
signal.signal(signal.SIGTERM, exit_gracefully) while True: conn, addr = s.accept() conn.settimeout(10) try: received_data = conn.recv(BUFFER_SIZE) eprint("bank received " + str(len(received_data)) + " bytes (encrypted)") if received_data: decrypted_data = encryption.decrypt_message(received_data, key) # eprint("bank received (decrypted): " + my_base64encode(received_data)) if decrypted_data is None: myprint("protocol_error") conn.send( encryption.encrypt_message(constants.FAILURE, key)) else: eprint("processing message: " + decrypted_data) success = True request = Request.from_string(decrypted_data) if request is None: success = False else: success = process_request(request) if success: eprint("processing message -> SUCCESS") json = request.json_str() myprint(json) conn.send(encryption.encrypt_message(json, key)) else: eprint("processing message -> FAILURE")
def main(): args = arguments.read_atm_arguments(sys.argv[1:]) if args is None: eprint("parsing ATM arguments failed. terminating...") input_error_exit() (auth_filename, ip_address, port, card_filename, account_name, command, amount) = args if ip_address is None: ip_address = "127.0.0.1" if port is None: port = constants.DEFAULT_PORT if card_filename is None: card_filename = account_name + ".card" if auth_filename is None: auth_filename = "bank.auth" pin, key = None, None try: if command != "n": card_file = open(card_filename, 'r') pin = card_file.read() card_file.close() else: if os.path.isfile(card_filename): eprint("card file already exists:", card_filename) input_error_exit() pin = my_base64encode(encryption.create_random_key()) auth_file = open(auth_filename, 'rb') key = auth_file.read() eprint("atm key (base64): " + base64.b64encode(key).decode("utf-8")) auth_file.close() except IOError as e: eprint(e) input_error_exit() request = Request.Request(account_name, pin, command, amount) s = socket.socket() s.settimeout(10) try: s.connect((ip_address, port)) data_to_send = str(request) eprint("atm, sending (decrypted): " + data_to_send) encrypted_data_to_send = encryption.encrypt_message(data_to_send, key) eprint("atm, sending " + str(len(encrypted_data_to_send)) + " bytes, (encrypted)") s.send(encrypted_data_to_send) received_data = s.recv(BUFFER_SIZE) if not received_data: s.close() protocol_error_exit() decrypted_data = encryption.decrypt_message(received_data, key) if decrypted_data is None: s.close() protocol_error_exit() else: if decrypted_data == constants.FAILURE: eprint("received FAILURE code from bank. terminating...") s.close() input_error_exit() else: # success eprint("received JSON result from bank") myprint(decrypted_data) if command == "n": card_file = open(card_filename, 'w') card_file.write(pin) card_file.close() except Exception as e: eprint("socket error:", e) s.close() protocol_error_exit()