-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
75 lines (62 loc) · 2.12 KB
/
Copy pathserver.py
File metadata and controls
75 lines (62 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import base64
import os
import socket
import sys
import threading
from libs import aes, path, web_io
def has_key(filename: str) -> bool:
file_path = path.get_key_path(filename)
return os.path.exists(file_path)
def main_recv(s: socket.socket, key: bytes, stop_event: threading.Event):
"""副线程用于接受另一个用户的消息"""
while True:
try:
en_data = web_io.recv_msg(s)
data = aes.decrypt_ecb(key, en_data).decode("utf-8")
print(data)
except web_io.SocketUtilsError:
print("远程主机强迫关闭了当前的连接")
stop_event.set()
break
def run():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("127.0.0.1", 12345))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.listen(1)
conn, addr = s.accept()
rsa_keys = ["pubkey.pem", "privkey.pem"]
if not all(map(has_key, rsa_keys)):
_ = sys.stderr.write("RSA keys is uncompletely!\n")
sys.exit(-1)
content = []
with open(f"{path.get_key_path('pubkey.pem')}", "r") as f:
content = f.readlines()
d = content[1].encode("utf-8")
e = content[2].encode("utf-8")
pubkey = (d + e).strip()
# 发送 rsa 公钥
with conn:
web_io.send_msg(pubkey, conn)
# 接受 aes 密钥
aes_key = web_io.recv_msg(conn)
aes_key = base64.b64decode(aes_key)
# 使用密钥加密通讯
stop_event = threading.Event()
t = threading.Thread(
target=main_recv,
args=(
conn,
aes_key,
stop_event,
),
daemon=True,
)
t.start()
while True:
msg = input("> ")
if msg == "quit" or stop_event.is_set():
break
en_msg = aes.encrypt_ecb(aes_key, msg.encode("utf-8"))
web_io.send_msg(en_msg, conn)
if __name__ == "__main__":
run()