-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.py
More file actions
223 lines (205 loc) · 8.82 KB
/
Client.py
File metadata and controls
223 lines (205 loc) · 8.82 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import socket
import threading
import os
import json
import hashlib
import base64
import tkinter as tk
from tkinter import scrolledtext
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 9988
def aes_encrypt(key, iv, text):
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
enc = cipher.encryptor()
return base64.b64encode(enc.update(text.encode()) + enc.finalize()).decode()
def aes_decrypt(key, iv, data):
raw = base64.b64decode(data)
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
dec = cipher.decryptor()
return (dec.update(raw) + dec.finalize()).decode()
def send(conn, data):
payload = json.dumps(data).encode()
conn.sendall(len(payload).to_bytes(4, "big") + payload)
def recv(conn):
def read(n):
buf = b""
while len(buf) < n:
chunk = conn.recv(n - len(buf))
if not chunk:
raise ConnectionError("Server disconnected")
buf += chunk
return buf
return json.loads(read(int.from_bytes(read(4), "big")))
def handshake(conn, username, password):
msg = recv(conn)
server_pub = serialization.load_pem_public_key(msg["key"].encode(), backend=default_backend())
aes_key = os.urandom(32)
iv = os.urandom(16)
def rsa_enc(data):
return base64.b64encode(server_pub.encrypt(
data,
padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
)).decode()
send(conn, {"type": "keys", "aes_key": rsa_enc(aes_key), "iv": rsa_enc(iv)})
send(conn, {
"type": "login",
"username": aes_encrypt(aes_key, iv, username),
"password": aes_encrypt(aes_key, iv, password)
})
result = recv(conn)
if not result["ok"]:
raise PermissionError(result.get("reason", "Login failed"))
return aes_key, iv
class LoginWindow(tk.Tk):
def __init__(self):
super().__init__()
self.title("Secure Chat — Login")
self.configure(bg="#111")
self.resizable(False, False)
self.geometry("380x320+{}+{}".format(
self.winfo_screenwidth() // 2 - 190,
self.winfo_screenheight() // 2 - 160
))
self._build()
def _build(self):
tk.Label(self, text="🔐 SECURE CHAT", font=("Courier", 18, "bold"),
fg="#00ff99", bg="#111").pack(pady=(24, 4))
tk.Label(self, text="RSA-2048 + AES-256 Encrypted",
font=("Courier", 8), fg="#555", bg="#111").pack()
frm = tk.Frame(self, bg="#1a1a1a", padx=20, pady=16)
frm.pack(padx=20, pady=14, fill="x")
def field(label, hide=None):
tk.Label(frm, text=label, font=("Courier", 9), fg="#888", bg="#1a1a1a").pack(anchor="w")
entry = tk.Entry(frm, show=hide, font=("Courier", 11), bg="#222",
fg="#00ff99", insertbackground="#00ff99", relief="flat", bd=6)
entry.pack(fill="x", pady=(2, 8))
return entry
self.u = field("USERNAME")
self.p = field("PASSWORD", hide="*")
self.u.focus()
self.err = tk.StringVar()
tk.Label(self, textvariable=self.err, fg="#ff4444",
font=("Courier", 9), bg="#111").pack()
tk.Button(self, text="[ CONNECT ]", font=("Courier", 11, "bold"),
bg="#00ff99", fg="#000", activebackground="#00cc77",
relief="flat", pady=8, cursor="hand2",
command=self._login).pack(fill="x", padx=20, pady=6)
tk.Label(self, text="test: arshad/arshad123 sam/sam123 muthu/muthu123",
font=("Courier", 7), fg="#333", bg="#111").pack()
self.bind("<Return>", lambda e: self._login())
def _login(self):
u = self.u.get().strip()
p = self.p.get()
if not u or not p:
self.err.set("enter username and password")
return
self.err.set("connecting...")
self.update()
threading.Thread(target=self._connect, args=(u, p), daemon=True).start()
def _connect(self, username, password):
try:
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect((SERVER_HOST, SERVER_PORT))
aes_key, iv = handshake(conn, username, password)
# FIX: capture all variables explicitly — Python 3.13 lambda closure fix
self.after(0, lambda c=conn, k=aes_key, i=iv, u=username:
self._open_chat(c, k, i, u))
except PermissionError as e:
m = str(e)
self.after(0, lambda m=m: self.err.set(m))
except ConnectionRefusedError:
self.after(0, lambda: self.err.set("cannot connect — is server running?"))
except Exception as e:
m = str(e)
self.after(0, lambda m=m: self.err.set(f"error: {m}"))
def _open_chat(self, conn, aes_key, iv, username):
self.withdraw()
ChatWindow(self, conn, aes_key, iv, username)
class ChatWindow(tk.Toplevel):
def __init__(self, parent, conn, aes_key, iv, username):
super().__init__(parent)
self.parent = parent
self.conn = conn
self.aes_key = aes_key
self.iv = iv
self.username = username
self.title(f"Secure Chat — {username} 🔐")
self.configure(bg="#111")
self.geometry("800x540+{}+{}".format(
self.winfo_screenwidth() // 2 - 400,
self.winfo_screenheight() // 2 - 270
))
self.protocol("WM_DELETE_WINDOW", self._quit)
self._build()
threading.Thread(target=self._receive_loop, daemon=True).start()
def _build(self):
top = tk.Frame(self, bg="#0d0d0d", pady=8)
top.pack(fill="x")
tk.Label(top, text="⬡ SECURECHAT", font=("Courier", 12, "bold"),
fg="#00ff99", bg="#0d0d0d").pack(side="left", padx=14)
tk.Label(top, text=f"[ {self.username} ]", font=("Courier", 9),
fg="#444", bg="#0d0d0d").pack(side="left")
tk.Label(top, text="🔒 AES-256 encrypted",
font=("Courier", 8), fg="#333", bg="#0d0d0d").pack(side="right", padx=14)
self.chat = scrolledtext.ScrolledText(
self, state="disabled", wrap="word",
bg="#0d0d0d", fg="#ccc", font=("Courier", 10),
relief="flat", bd=0, padx=10, pady=8
)
self.chat.pack(fill="both", expand=True, padx=8, pady=(6, 0))
self.chat.tag_config("me", foreground="#00ff99")
self.chat.tag_config("other", foreground="#66d9ff")
self.chat.tag_config("server", foreground="#ffaa00")
row = tk.Frame(self, bg="#111", pady=8)
row.pack(fill="x", padx=8)
self.entry = tk.Entry(row, font=("Courier", 11), bg="#1a1a1a",
fg="#00ff99", insertbackground="#00ff99",
relief="flat", bd=6)
self.entry.pack(side="left", fill="x", expand=True, padx=(0, 6))
self.entry.bind("<Return>", lambda e: self._send())
self.entry.focus()
tk.Button(row, text="SEND 🔒", font=("Courier", 10, "bold"),
bg="#00ff99", fg="#000", activebackground="#00cc77",
relief="flat", padx=12, cursor="hand2",
command=self._send).pack(side="right")
def _send(self):
text = self.entry.get().strip()
if not text:
return
self.entry.delete(0, "end")
encrypted = aes_encrypt(self.aes_key, self.iv, text)
try:
send(self.conn, {"type": "msg", "data": encrypted})
self._show(f"[You]: {text}\n", "me")
except Exception as e:
m = str(e)
self._show(f"[!] Send failed: {m}\n", "server")
def _receive_loop(self):
while True:
try:
msg = recv(self.conn)
plain = aes_decrypt(self.aes_key, self.iv, msg["data"])
tag = "server" if plain.startswith("[SERVER]") else "other"
self.after(0, lambda m=plain, t=tag: self._show(m + "\n", t))
except Exception:
self.after(0, lambda: self._show("[!] Disconnected\n", "server"))
break
def _show(self, text, tag="other"):
self.chat.configure(state="normal")
self.chat.insert("end", text, tag)
self.chat.configure(state="disabled")
self.chat.see("end")
def _quit(self):
try:
send(self.conn, {"type": "quit"})
except Exception:
pass
self.conn.close()
self.destroy()
self.parent.destroy()
if __name__ == "__main__":
LoginWindow().mainloop()