Skip to content

Commit 7cdd1c3

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 72c566b commit 7cdd1c3

File tree

4 files changed

+134
-73
lines changed

4 files changed

+134
-73
lines changed

peer2peer_file_sharing/crypto/aes_crypto.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,41 @@
22
from cryptography.fernet import Fernet
33

44
SKIP_COMPRESSION_EXTENSIONS = {
5-
'.zip', '.gz', '.bz2', '.xz', '.rar', '.7z',
6-
'.jpg', '.jpeg', '.png', '.gif', '.webp',
7-
'.mp3', '.mp4', '.avi', '.mkv', '.mov',
8-
'.pdf'
5+
".zip",
6+
".gz",
7+
".bz2",
8+
".xz",
9+
".rar",
10+
".7z",
11+
".jpg",
12+
".jpeg",
13+
".png",
14+
".gif",
15+
".webp",
16+
".mp3",
17+
".mp4",
18+
".avi",
19+
".mkv",
20+
".mov",
21+
".pdf",
922
}
1023

24+
1125
def generate_aes_key():
1226
return Fernet.generate_key()
1327

28+
1429
def encrypt_chunk_with_aes(chunk: bytes, aes_key: bytes, file_extension: str) -> bytes:
1530
fernet = Fernet(aes_key)
1631
if file_extension.lower() not in SKIP_COMPRESSION_EXTENSIONS:
1732
try:
1833
chunk = zlib.compress(chunk)
1934
except Exception as e:
2035
print(f"\n[!] Compression failed: {e}")
21-
36+
2237
return fernet.encrypt(chunk)
2338

39+
2440
def decrypt_chunk_with_aes(chunk: bytes, aes_key: bytes, file_extension: str) -> bytes:
2541
fernet = Fernet(aes_key)
2642
try:
@@ -34,4 +50,4 @@ def decrypt_chunk_with_aes(chunk: bytes, aes_key: bytes, file_extension: str) ->
3450
except zlib.error:
3551
print("\n[!] Warning: Failed to decompress — file may not be compressed")
3652

37-
return decrypted_data
53+
return decrypted_data

peer2peer_file_sharing/crypto/rsa_crypto.py

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,63 @@
11
from cryptography.hazmat.primitives import serialization, hashes
22
from cryptography.hazmat.primitives.asymmetric import rsa, padding
33

4+
45
def generate_rsa_key_pair(private_path: str, public_path: str):
56
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
6-
7+
78
with open(private_path, "wb") as f:
8-
9-
f.write(private_key.private_bytes(
10-
serialization.Encoding.PEM,
11-
serialization.PrivateFormat.TraditionalOpenSSL,
12-
serialization.NoEncryption()
13-
))
14-
9+
f.write(
10+
private_key.private_bytes(
11+
serialization.Encoding.PEM,
12+
serialization.PrivateFormat.TraditionalOpenSSL,
13+
serialization.NoEncryption(),
14+
)
15+
)
16+
1517
with open(public_path, "wb") as f:
16-
17-
f.write(private_key.public_key().public_bytes(
18-
serialization.Encoding.PEM,
19-
serialization.PublicFormat.SubjectPublicKeyInfo
20-
))
18+
f.write(
19+
private_key.public_key().public_bytes(
20+
serialization.Encoding.PEM,
21+
serialization.PublicFormat.SubjectPublicKeyInfo,
22+
)
23+
)
2124

22-
def encrypt_with_rsa_public_key(data: bytes, public_key_path: str) -> bytes:
2325

26+
def encrypt_with_rsa_public_key(data: bytes, public_key_path: str) -> bytes:
2427
with open(public_key_path, "rb") as f:
2528
public_key = serialization.load_pem_public_key(f.read())
2629

2730
if not isinstance(public_key, rsa.RSAPublicKey):
2831
raise TypeError("\n[!] The loaded public key is not an RSA key.")
29-
32+
3033
return public_key.encrypt(
3134
data,
32-
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
35+
padding.OAEP(
36+
mgf=padding.MGF1(algorithm=hashes.SHA256()),
37+
algorithm=hashes.SHA256(),
38+
label=None,
39+
),
3340
)
3441

42+
3543
def decrypt_with_rsa_private_key(ciphertext: bytes, private_key_path: str) -> bytes:
36-
3744
with open(private_key_path, "rb") as f:
3845
private_key = serialization.load_pem_private_key(f.read(), password=None)
3946

4047
if not isinstance(private_key, rsa.RSAPrivateKey):
4148
raise TypeError("\n[!] The loaded private key is not an RSA key.")
42-
49+
4350
return private_key.decrypt(
4451
ciphertext,
45-
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
52+
padding.OAEP(
53+
mgf=padding.MGF1(algorithm=hashes.SHA256()),
54+
algorithm=hashes.SHA256(),
55+
label=None,
56+
),
4657
)
4758

59+
4860
def is_valid_pem_key(file_path: str, is_private: bool = False) -> bool:
49-
5061
try:
5162
with open(file_path, "rb") as f:
5263
data = f.read()
@@ -57,7 +68,6 @@ def is_valid_pem_key(file_path: str, is_private: bool = False) -> bool:
5768
else:
5869
serialization.load_pem_public_key(data)
5970
return True
60-
71+
6172
except Exception:
6273
return False
63-

peer2peer_file_sharing/peer.py

Lines changed: 71 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
Enter receiver's port: 6001
1616
"""
1717

18-
1918
import os
2019
import socket
2120
import threading
@@ -27,20 +26,31 @@
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
3442
from 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

4048
ensure_dir(RECEIVE_DIR)
4149
ensure_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.")
@@ -51,10 +61,11 @@
5161

5262
LISTEN_PORT = args.listen_port
5363

64+
5465
def 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+
110136
def 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("\nSend file [y], wait [w], or exit [e]? ").strip().lower()
189+
user_input = (
190+
input("\nSend 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("\nEnter file path to send: ").strip()
165199
peer_ip = input("\nEnter receiver's IP address: ").strip()
166200
peer_port_input = input("\nEnter 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

Comments
 (0)