Advertisement
NaroxEG

Untitled

Jul 21st, 2024
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.16 KB | None | 0 0
  1. import os
  2. import socket
  3. import threading
  4. from Crypto.Cipher import AES
  5.  
  6. # Define AES encryption parameters
  7. key = b"TheNeuralNineKey"
  8. nonce = b"TheNeuralNineNce"
  9. cipher = AES.new(key, AES.MODE_EAX, nonce)
  10.  
  11. IP = socket.gethostbyname(socket.gethostname())
  12. PORT = 4466
  13. ADDR = (IP, PORT)
  14.  
  15. SIZE = 4096
  16. FORMAT = "utf-8"
  17. DATA_PATH = "device1_data"
  18.  
  19. def handle_connection(conn, addr):
  20. print(f"[New connection] {addr} connected")
  21. conn.send("ok@Welcome to the file transfer system".encode(FORMAT))
  22.  
  23. while True:
  24. data = conn.recv(SIZE).decode(FORMAT)
  25. cmd, *cmd_data = data.split("@")
  26.  
  27. if cmd == "HELP":
  28. send_data = "ok@"
  29. send_data += "LIST: List all files\n"
  30. send_data += "SEND <filename>: Send a file\n"
  31. send_data += "RECEIVE <filename>: Receive a file\n"
  32. send_data += "DISCONNECT: Disconnect from the system\n"
  33. send_data += "HELP: List all commands"
  34. conn.send(send_data.encode(FORMAT))
  35.  
  36. elif cmd == "DISCONNECT":
  37. break
  38.  
  39. elif cmd == "LIST":
  40. files = os.listdir(DATA_PATH)
  41. send_data = "ok@"
  42. if not files:
  43. send_data += "The directory is empty"
  44. else:
  45. send_data += "\n".join(files)
  46. conn.send(send_data.encode(FORMAT))
  47.  
  48. elif cmd == "SEND":
  49. filename = cmd_data[0]
  50. filepath = os.path.join(DATA_PATH, filename)
  51.  
  52. if not os.path.exists(filepath):
  53. conn.send("ERROR@File not found".encode(FORMAT))
  54. continue
  55.  
  56. with open(filepath, "rb") as f:
  57. file_data = f.read()
  58.  
  59. encrypted_data = cipher.encrypt(file_data)
  60. file_size = len(encrypted_data)
  61.  
  62. conn.send(f"READY@{file_size}".encode(FORMAT))
  63. conn.recv(SIZE) # Wait for receiver's acknowledgment
  64.  
  65. conn.sendall(encrypted_data)
  66.  
  67. conn.recv(SIZE) # Wait for receiver's confirmation
  68.  
  69. elif cmd == "RECEIVE":
  70. filename = cmd_data[0]
  71. file_size = int(cmd_data[1])
  72.  
  73. filepath = os.path.join(DATA_PATH, filename)
  74.  
  75. conn.send("READY".encode(FORMAT))
  76.  
  77. encrypted_data = b""
  78. remaining = file_size
  79. while remaining:
  80. chunk = conn.recv(min(SIZE, remaining))
  81. encrypted_data += chunk
  82. remaining -= len(chunk)
  83.  
  84. decrypted_data = cipher.decrypt(encrypted_data)
  85.  
  86. with open(filepath, "wb") as f:
  87. f.write(decrypted_data)
  88.  
  89. send_data = "ok@File received successfully"
  90. conn.send(send_data.encode(FORMAT))
  91.  
  92. print(f"[Disconnected] {addr} disconnected")
  93.  
  94. def start_server():
  95. print("[Starting] Server is starting")
  96. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  97. server.bind(ADDR)
  98. server.listen()
  99. print("[Listening] Server is listening on", ADDR)
  100.  
  101. while True:
  102. conn, addr = server.accept()
  103. thread = threading.Thread(target=handle_connection, args=(conn, addr))
  104. thread.start()
  105.  
  106. def connect_to_peer():
  107. peer_ip = input("Enter peer IP address: ")
  108. peer_port = int(input("Enter peer port: "))
  109. peer_addr = (peer_ip, peer_port)
  110.  
  111. client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  112. client.connect(peer_addr)
  113.  
  114. while True:
  115. data = client.recv(SIZE).decode(FORMAT)
  116. cmd, msg = data.split("@", 1)
  117.  
  118. if cmd == "ok":
  119. print(f"{msg}")
  120. elif cmd == "ERROR":
  121. print(f"Error: {msg}")
  122. elif cmd == "READY":
  123. file_size = int(msg)
  124. client.send("ACK".encode(FORMAT))
  125.  
  126. encrypted_data = b""
  127. remaining = file_size
  128. while remaining:
  129. chunk = client.recv(min(SIZE, remaining))
  130. encrypted_data += chunk
  131. remaining -= len(chunk)
  132.  
  133. decrypted_data = cipher.decrypt(encrypted_data)
  134. filename = input("Enter the filename to save: ")
  135. filepath = os.path.join(DATA_PATH, filename)
  136. with open(filepath, "wb") as f:
  137. f.write(decrypted_data)
  138. print(f"File {filename} received successfully.")
  139. client.send("DONE".encode(FORMAT))
  140.  
  141. user_input = input("> ")
  142. user_data = user_input.split(" ")
  143. cmd = user_data[0]
  144.  
  145. if cmd == "HELP":
  146. client.send(cmd.encode(FORMAT))
  147.  
  148. elif cmd == "DISCONNECT":
  149. client.send(cmd.encode(FORMAT))
  150. break
  151.  
  152. elif cmd == "LIST":
  153. client.send(cmd.encode(FORMAT))
  154.  
  155. elif cmd == "SEND":
  156. filename = user_data[1]
  157. filepath = os.path.join(DATA_PATH, filename)
  158.  
  159. if not os.path.exists(filepath):
  160. print("Error: File not found")
  161. continue
  162.  
  163. with open(filepath, "rb") as f:
  164. file_data = f.read()
  165.  
  166. encrypted_data = cipher.encrypt(file_data)
  167. file_size = len(encrypted_data)
  168.  
  169. client.send(f"RECEIVE@{filename}@{file_size}".encode(FORMAT))
  170. client.recv(SIZE) # Wait for peer's READY signal
  171.  
  172. client.sendall(encrypted_data)
  173.  
  174. elif cmd == "RECEIVE":
  175. filename = user_data[1]
  176. client.send(f"SEND@{filename}".encode(FORMAT))
  177.  
  178. print("Disconnected from the peer")
  179. client.close()
  180.  
  181. def main():
  182. os.makedirs(DATA_PATH, exist_ok=True)
  183. mode = input("Enter 's' for server mode or 'c' for client mode: ")
  184. if mode.lower() == 's':
  185. start_server()
  186. elif mode.lower() == 'c':
  187. connect_to_peer()
  188. else:
  189. print("Invalid mode. Exiting.")
  190.  
  191. if __name__ == "__main__":
  192. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement