1515 Enter receiver's port: 6001
1616"""
1717
18-
1918import os
2019import socket
2120import threading
2726 decrypt_with_rsa_private_key ,
2827 encrypt_with_rsa_public_key ,
2928 generate_rsa_key_pair ,
30- is_valid_pem_key
29+ is_valid_pem_key ,
30+ )
31+ from crypto .aes_crypto import (
32+ generate_aes_key ,
33+ encrypt_chunk_with_aes ,
34+ decrypt_chunk_with_aes ,
35+ )
36+ from utils .file_utils import (
37+ ensure_dir ,
38+ sha256_digest_stream ,
39+ is_valid_ip ,
40+ is_valid_port ,
3141)
32- from crypto .aes_crypto import generate_aes_key , encrypt_chunk_with_aes , decrypt_chunk_with_aes
33- from utils .file_utils import ensure_dir , sha256_digest_stream , is_valid_ip , is_valid_port
3442from utils .file_utils import CHUNK_SIZE
3543
36- PRIVATE_KEY_PATH = ' keys/private_key.pem'
37- PUBLIC_KEY_PATH = ' keys/public_keys.pem'
38- RECEIVE_DIR = ' received_files'
44+ PRIVATE_KEY_PATH = " keys/private_key.pem"
45+ PUBLIC_KEY_PATH = " keys/public_keys.pem"
46+ RECEIVE_DIR = " received_files"
3947
4048ensure_dir (RECEIVE_DIR )
4149ensure_dir ("keys" )
4250
43- if not is_valid_pem_key (PRIVATE_KEY_PATH , is_private = True ) or not is_valid_pem_key (PUBLIC_KEY_PATH , is_private = False ):
51+ if not is_valid_pem_key (PRIVATE_KEY_PATH , is_private = True ) or not is_valid_pem_key (
52+ PUBLIC_KEY_PATH , is_private = False
53+ ):
4454 print ("\n [!] RSA key missing or invalid. Regenerating..." )
4555 generate_rsa_key_pair (PRIVATE_KEY_PATH , PUBLIC_KEY_PATH )
4656 print ("\n [+] RSA key pair regenerated." )
5161
5262LISTEN_PORT = args .listen_port
5363
64+
5465def peer_listener ():
5566 try :
5667 server_socket = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
57- server_socket .bind ((' 0.0.0.0' , LISTEN_PORT ))
68+ server_socket .bind ((" 0.0.0.0" , LISTEN_PORT ))
5869 server_socket .listen (1 )
5970 print (f"\n [+] Listening on port { LISTEN_PORT } ..." )
6071
@@ -63,34 +74,48 @@ def peer_listener():
6374 print (f"\n \n [+] Incoming connection from { addr } \n " )
6475
6576 try :
66- key_size = int .from_bytes (client_socket .recv (4 ), ' big' )
77+ key_size = int .from_bytes (client_socket .recv (4 ), " big" )
6778 encrypted_key = client_socket .recv (key_size )
6879
69- name_len = int .from_bytes (client_socket .recv (4 ), ' big' )
80+ name_len = int .from_bytes (client_socket .recv (4 ), " big" )
7081 file_name = client_socket .recv (name_len ).decode ()
7182
72- extension = int .from_bytes (client_socket .recv (4 ), ' big' )
83+ extension = int .from_bytes (client_socket .recv (4 ), " big" )
7384 file_extension = client_socket .recv (extension ).decode ()
7485
75- total_size = int .from_bytes (client_socket .recv (8 ), ' big' )
76-
86+ total_size = int .from_bytes (client_socket .recv (8 ), " big" )
87+
7788 aes_key = decrypt_with_rsa_private_key (encrypted_key , PRIVATE_KEY_PATH )
7889
7990 file_path = os .path .join (RECEIVE_DIR , file_name )
80-
81- with open (file_path , 'wb' ) as f_out , tqdm (total = total_size , desc = f"[+] Receiving { file_name } " , unit = "B" , unit_scale = True ) as pbar :
91+
92+ with (
93+ open (file_path , "wb" ) as f_out ,
94+ tqdm (
95+ total = total_size ,
96+ desc = f"[+] Receiving { file_name } " ,
97+ unit = "B" ,
98+ unit_scale = True ,
99+ ) as pbar ,
100+ ):
82101 received_bytes = 0
83102 while received_bytes < total_size :
84- rcv_chunk_size = int .from_bytes (client_socket .recv (4 ), ' big' )
103+ rcv_chunk_size = int .from_bytes (client_socket .recv (4 ), " big" )
85104 encrypted_chunk = b""
86-
105+
87106 while len (encrypted_chunk ) < rcv_chunk_size :
88- part = client_socket .recv (rcv_chunk_size - len (encrypted_chunk ))
107+ part = client_socket .recv (
108+ rcv_chunk_size - len (encrypted_chunk )
109+ )
89110 if not part :
90- raise Exception ("\n [!] Connection lost during transfer." )
111+ raise Exception (
112+ "\n [!] Connection lost during transfer."
113+ )
91114 encrypted_chunk += part
92115
93- decrypted_chunk = decrypt_chunk_with_aes (encrypted_chunk , aes_key , file_extension )
116+ decrypted_chunk = decrypt_chunk_with_aes (
117+ encrypted_chunk , aes_key , file_extension
118+ )
94119 f_out .write (decrypted_chunk )
95120 received_bytes += len (decrypted_chunk )
96121 pbar .update (len (decrypted_chunk ))
@@ -107,9 +132,9 @@ def peer_listener():
107132 except Exception as e :
108133 print (f"\n [!] Server failed: { str (e )} \n { traceback .format_exc ()} " )
109134
135+
110136def send_file (file_path , peer_ip , peer_port ):
111137 try :
112-
113138 file_name = os .path .basename (file_path )
114139 file_extension = os .path .splitext (file_name )[1 ].lower ()
115140
@@ -120,23 +145,31 @@ def send_file(file_path, peer_ip, peer_port):
120145 client_socket = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
121146 client_socket .connect ((peer_ip , peer_port ))
122147
123- client_socket .sendall (len (encrypted_key ).to_bytes (4 , ' big' ))
148+ client_socket .sendall (len (encrypted_key ).to_bytes (4 , " big" ))
124149 client_socket .sendall (encrypted_key )
125150
126- client_socket .sendall (len (file_name .encode ()).to_bytes (4 , ' big' ))
151+ client_socket .sendall (len (file_name .encode ()).to_bytes (4 , " big" ))
127152 client_socket .sendall (file_name .encode ())
128153
129- client_socket .sendall (len (file_extension .encode ()).to_bytes (4 , ' big' ))
154+ client_socket .sendall (len (file_extension .encode ()).to_bytes (4 , " big" ))
130155 client_socket .sendall (file_extension .encode ())
131156
132- client_socket .sendall (file_size .to_bytes (8 , ' big' ))
133-
157+ client_socket .sendall (file_size .to_bytes (8 , " big" ))
158+
134159 print ()
135160
136- with open (file_path , 'rb' ) as f , tqdm (total = file_size , desc = f"[+] Sending { file_name } " , unit = "B" , unit_scale = True ) as pbar :
137- for chunk in iter (lambda : f .read (CHUNK_SIZE ), b'' ):
161+ with (
162+ open (file_path , "rb" ) as f ,
163+ tqdm (
164+ total = file_size ,
165+ desc = f"[+] Sending { file_name } " ,
166+ unit = "B" ,
167+ unit_scale = True ,
168+ ) as pbar ,
169+ ):
170+ for chunk in iter (lambda : f .read (CHUNK_SIZE ), b"" ):
138171 encrypted_chunk = encrypt_chunk_with_aes (chunk , aes_key , file_extension )
139- client_socket .sendall (len (encrypted_chunk ).to_bytes (4 , ' big' ))
172+ client_socket .sendall (len (encrypted_chunk ).to_bytes (4 , " big" ))
140173 client_socket .sendall (encrypted_chunk )
141174 pbar .update (len (chunk ))
142175
@@ -147,20 +180,21 @@ def send_file(file_path, peer_ip, peer_port):
147180 print (f"\n [!] Failed to send file: { str (e )} \n { traceback .format_exc ()} " )
148181
149182
150- if __name__ == '__main__' :
151-
183+ if __name__ == "__main__" :
152184 try :
153185 threading .Thread (target = peer_listener , daemon = True ).start ()
154186 sleep (0.5 )
155187
156188 while True :
157- user_input = input ("\n Send file [y], wait [w], or exit [e]? " ).strip ().lower ()
189+ user_input = (
190+ input ("\n Send file [y], wait [w], or exit [e]? " ).strip ().lower ()
191+ )
158192
159- if user_input == 'e' :
193+ if user_input == "e" :
160194 print ("\n [INFO] Exiting..." )
161195 break
162196
163- elif user_input == 'y' :
197+ elif user_input == "y" :
164198 file_path = input ("\n Enter file path to send: " ).strip ()
165199 peer_ip = input ("\n Enter receiver's IP address: " ).strip ()
166200 peer_port_input = input ("\n Enter receiver's port: " ).strip ()
@@ -176,16 +210,14 @@ def send_file(file_path, peer_ip, peer_port):
176210 peer_port = int (peer_port_input )
177211 send_file (file_path , peer_ip , peer_port )
178212
179- elif user_input == 'w' :
213+ elif user_input == "w" :
180214 print ("\n [INFO] Waiting for incoming transfers..." )
181215
182216 else :
183217 print ("\n [!] Invalid input. Use 'y', 'w', or 'e'." )
184218
185219 except KeyboardInterrupt :
186220 print ("\n [INFO] Exiting by keyboard interrupt." )
187-
221+
188222 except Exception as e :
189223 print (f"\n [!] An error occurred: { str (e )} \n { traceback .format_exc ()} " )
190-
191-
0 commit comments