-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecret_messager.py
More file actions
493 lines (388 loc) · 18.9 KB
/
secret_messager.py
File metadata and controls
493 lines (388 loc) · 18.9 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
from tkinter import *
from tkinter import messagebox, Toplevel, Label, PhotoImage, ttk, CENTER, END, GROOVE, WORD, filedialog, Button
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
from functools import partial
from PIL import ImageTk
import base64
import webbrowser
import qrcode
import random
import string
import tempfile
import urllib.parse
import json
BLOCK_SIZE = 16 # Padding for AES (should be 16 bytes)
# Liste für die letzten 10 Schlüssel
password_history = []
# Liste der offenen Fenster
open_windows = []
def pad(s):
padding_length = BLOCK_SIZE - len(s) % BLOCK_SIZE
padding = chr(padding_length).encode()
return s + padding * padding_length
def unpad(s):
padding_length = s[-1]
return s[:-padding_length]
def get_key(password):
hasher = SHA256.new(password.encode('utf-8'))
return hasher.digest()
def save_password_history():
with open('database/password_history.json', 'w') as file:
json.dump(password_history, file)
def check_password_strength(password):
if len(password) < 8:
return "Schlüssel ist zu kurz. Mindestens 8 Zeichen verwenden."
if not any(char.isupper() for char in password) or not any(char.islower() for char in password):
return "Mindestens ein Groß- und Kleinbuchstaben verwenden."
if not any(char.isdigit() for char in password):
return "Mindestens eine Ziffer verwenden."
special_characters = "!@#$%^&*()-_=+[{]}|;:,<.>/?"
if not any(char in special_characters for char in password):
return "Mindestens ein Sonderzeichen verwenden."
return "Die Schlüsselstärke ist ausreichend."
# Funktion zur zufälligen Generierung eines Passworts
def generate_random_key():
while True:
password = []
password.append(random.choice(string.ascii_uppercase))
password.append(random.choice(string.ascii_lowercase))
password.append(random.choice(string.punctuation))
password.append(random.choice(string.digits))
password.append(random.choice(string.ascii_letters))
# Füge zufällige Zeichen hinzu, um die Mindestlänge zu erreichen
password.extend(random.choices(string.ascii_lowercase + string.ascii_uppercase + string.ascii_letters + string.digits + string.punctuation, k=random.randint(5, 13)))
# Mische die Zeichen zufällig
random.shuffle(password)
# Konvertiere die Liste in einen String
password = ''.join(password)
if len(password) >= 8:
return password
def on_double_cklick(event):
item = tree.focus()
if item:
values = tree.item(item, "values")
key = values[0]
key_entry.delete(0, END)
key_entry.insert(END, key)
event.widget.master.destroy()
def save_image_to_file_and_send_email(qr_image):
file_path = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png")])
if file_path:
try:
qr_image.save(file_path)
print(f"Image saved to {file_path}")
messagebox.showinfo("Information", "QR Code gespeichert")
# Kodieren des Dateipfads
encoded_file_path = urllib.parse.quote(file_path)
subject = urllib.parse.quote("QR Code Attachment")
body = urllib.parse.quote("Anbei ein QR-Code.")
# Öffnen des Standard-E-Mail-Programms mit dem QR-Code als Anhang
webbrowser.open(f'mailto:?subject={subject}&body={body}&attachment="{encoded_file_path}"')
except Exception as e:
messagebox.showerror("Error", f"Failed to save QR Code: {str(e)}")
else:
print("No file selected")
def add_to_history(password):
if len(password_history) >= 10:
password_history.pop(0)
password_history.append(password)
save_password_history()
def show_password_history():
global tree, key_entry, screen, open_windows
history_window = Toplevel(screen) # Erstellt ein neues Toplevel-Fenster
open_windows.append(history_window)
history_window.title("Passworthistorie")
history_window.geometry("300x200")
history_window.configure(bg="#f0f0f0")
Label(history_window, text="Zuletzt verwendete Schlüssel:", bg="#f0f0f0").pack(pady=10)
def clear_password_history():
try:
with open('database/password_history.json', 'w') as file:
json.dump([], file)
messagebox.showinfo("Information", "Die Passwort-Historie wird beim Beenden des Programms gelöscht.")
except Exception as e:
messagebox.showinfo("Error", f"Fehler beim Leeren der Passwort-Historie: {str(e)}")
history_label = Label(history_window, text="Liste löschen", fg="blue", font=("calibri", 10, "underline"), cursor="hand2")
history_label.bind("<Button-1>", lambda e: clear_password_history())
history_label.place(x=223, y=30)
# Button(history_window, text="Liste löschen", height="1", width=20, bg="#6a6a6a", fg="white", bd=0, command=clear_history).place(x=10, y=20)
history_listbox = Listbox(history_window, bg="white", height=10, width=40)
history_listbox.pack(pady=10)
for pw in password_history:
history_listbox.insert(END, pw)
# Function to handle double-click event in history_window
def on_double_click(event):
item = history_listbox.curselection()
if item:
selected_password = history_listbox.get(item)
key_entry.delete(0, END)
key_entry.insert(END, selected_password)
history_window.destroy()
screen.focus_set()
# Bindet das Doppelklick-Ereignis an die Listbox in history_window
history_listbox.bind("<Double-1>", on_double_click)
# Funktion zum Kopieren des ausgewählten Schlüssels in die Zwischenablage
def copy_selection():
selected_password = history_listbox.get(history_listbox.curselection())
history_window.clipboard_clear()
history_window.clipboard_append(selected_password)
# Kontextmenü zum Kopieren hinzufügen
popup_menu = Menu(history_window, tearoff=0)
popup_menu.add_command(label="Kopieren", command=copy_selection)
def popup(event):
popup_menu.post(event.x_root, event.y_root)
history_listbox.bind("<Button-3>", popup)
# Packt die Listbox und das Key Entry-Feld in das history_window
history_listbox.pack(expand=True, fill=BOTH)
# Setzt den Fokus auf das history_window
history_window.focus_set()
def encrypt():
password = code.get()
if password == "":
messagebox.showerror("encryption", "Bitte einen Schlüssel eingeben.")
return
strength_feedback = check_password_strength(password)
if not strength_feedback == "Die Schlüsselstärke ist ausreichend.":
messagebox.showwarning("encryption", strength_feedback)
return
screen1 = Toplevel(screen)
open_windows.append(screen1)
screen1.title("encryption")
screen1.geometry("400x250")
screen1.configure(bg="#ed3833")
image_icon = PhotoImage(file="img/kisspng-key-icon-magic-keys.png")
screen1.iconphoto(False, image_icon)
message = text1.get(1.0, END).strip()
if not message:
messagebox.showerror("encryption", "No message to encrypt.")
return
try:
key = get_key(password)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_message = pad(message.encode('utf-8'))
encrypted_message = base64.b64encode(iv + cipher.encrypt(padded_message)).decode('utf-8')
# Passwort in die Historie aufnehmen
add_to_history(password)
Label(screen1, text="ENCRYPT", font="arial", fg="white", bg="#ed3833").place(x=10, y=0)
text2 = Text(screen1, font=("Roboto", 10), bg="white", relief=GROOVE, wrap=WORD, bd=0)
text2.place(x=10, y=40, width=380, height=150)
text2.insert(END, encrypted_message)
def send_email_wrapper(message_type, qr_image=None):
if message_type == 'encrypted':
email_content = f"----- Beginn der verschlüsselten Nachricht ----- \n \n{encrypted_message}"
webbrowser.open('mailto:?subject=Encrypted%20Message&body=' + urllib.parse.quote(email_content))
elif message_type == 'qr_code' and qr_image is not None:
email_content = f"Anbei ein QR-Code."
send_email_with_attachment(qr_image, email_content)
def copy_to_clipboard():
text = text2.get(1.0, END)
screen.clipboard_clear()
screen.clipboard_append(text)
screen.update()
messagebox.showinfo("Information", "Text in die Zwischenablage kopiert")
def show_qr_code():
if not encrypted_message:
messagebox.showerror("Error", "No encrypted message to generate QR code.")
return
qr_image = generate_qr_code(encrypted_message)
qr_window = Toplevel(screen1)
qr_window.title("QR Code")
qr_window.geometry("450x430")
qr_window.configure(bg="#ed3833")
image_icon = PhotoImage(file="img/kisspng-key-icon-magic-keys.png")
qr_window.iconphoto(False, image_icon)
qr_photo = ImageTk.PhotoImage(qr_image)
qr_label = Label(qr_window, image=qr_photo)
qr_label.image = qr_photo
qr_label.pack()
# Erstellen der Buttons
button1 = Button(qr_window, text="per Mail", height=2, width=15, bg="#1089ff", fg="white", bd=0, command=lambda: save_image_to_file_and_send_email(qr_image))
button2 = Button(qr_window, text="QR Code speichern", height=2, width=15, bg="#1089ff", fg="white", bd=0, command=lambda: save_image_to_file(qr_image))
# Platzierung der Buttons
button1.place(relx=0.25, rely=0.93, anchor=CENTER)
button2.place(relx=0.75, rely=0.93, anchor=CENTER)
def generate_qr_code(message):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(message)
qr.make(fit=True)
qr_image = qr.make_image(fill='black', back_color='white')
return qr_image
def save_image_to_file(qr_image):
file_path = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png")])
if file_path:
qr_image.save(file_path)
print(f"Image saved to {file_path}")
messagebox.showinfo("Information", "QR Code gespeichert")
else:
print("No image to save")
def send_email_with_attachment(qr_image, email_content):
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file:
temp_file_path = temp_file.name
qr_image.save(temp_file_path)
# Kodieren des Dateipfads
encoded_file_path = urllib.parse.quote(temp_file_path)
subject = urllib.parse.quote("QR Code Attachment")
body = urllib.parse.quote(email_content)
# Öffnet das Standard-E-Mail-Programm mit dem QR-Code als Anhang
webbrowser.open(f'mailto:?subject={subject}&body={body}&attachment="{encoded_file_path}"')
except Exception as e:
messagebox.showerror("Error", f"Failed to save QR Code: {str(e)}")
Button(screen1, text="Kopieren", height="2", width=15, bg="#1089ff", fg="white", bd=0, command=copy_to_clipboard).place(relx=0.15, rely=0.9, anchor=CENTER)
Button(screen1, text="QR Code", height="2", width=15, bg="#1089ff", fg="white", bd=0, command=show_qr_code).place(relx=0.50, rely=0.9, anchor=CENTER)
Button(screen1, text="per Mail", height="2", width=15, bg="#1089ff", fg="white", bd=0, command=partial(send_email_wrapper, 'encrypted')).place(relx=0.85, rely=0.9, anchor=CENTER)
except Exception as e:
messagebox.showerror("encryption", f"Encryption failed: {str(e)}")
def decrypt():
password = code.get()
if password == "":
messagebox.showerror("encryption", "Schlüssel eingeben")
return
screen2 = Toplevel(screen)
open_windows.append(screen2)
screen2.title("decryption")
screen2.geometry("400x250")
screen2.configure(bg="#00bd56")
image_icon = PhotoImage(file="img/kisspng-key-icon-magic-keys.png")
screen2.iconphoto(False, image_icon)
message = text1.get(1.0, END).strip()
if not message:
messagebox.showerror("decryption", "Keine Nachricht zu entschlüsseln")
return
try:
key = get_key(password)
message_bytes = base64.b64decode(message)
iv = message_bytes[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted_message = cipher.decrypt(message_bytes[AES.block_size:])
decrypted_message = unpad(decrypted_message).decode('utf-8')
Label(screen2, text="DECRYPT", font="arial", fg="white", bg="#00bd56").place(x=10, y=0)
text2 = Text(screen2, font=("Roboto", 10), bg="white", relief=GROOVE, wrap=WORD, bd=0)
text2.place(x=10, y=40, width=380, height=150)
text2.insert(END, decrypted_message)
except Exception as e:
messagebox.showerror("decryption", f"Decryption failed: {str(e)}")
def open_history():
global tree, text1, screen3
screen3 = Toplevel()
screen3.title("Vorschläge")
screen3.geometry("440x230")
# Erstellen einer Tabelle (Treeview) in screen3
tree = ttk.Treeview(screen3, columns=("Key", "Strength"), show="headings")
# Überschriften der Spalten definieren
tree.heading("Key", text="Schlüssel", anchor="w")
tree.heading("Strength", text="Stärke", anchor="w")
# Einträge in die Tabelle einfügen
for i in range(1, 21): # 20 Einträge erstellen
random_key = generate_random_key()
strength = check_password_strength(random_key)
tree.insert("", END, iid=i, text=str(i), values=(random_key, strength))
# Doppelklick-Ereignisbindung für die Treeview
tree.bind("<Double-1>", on_double_cklick)
# Funktion zur Kopierfähigkeit der Zellen in der Spalte "Schlüssel"
def copy_selection():
selected_item = tree.focus()
if selected_item:
item_text = tree.item(selected_item)["values"][0]
screen3.clipboard_clear()
screen3.clipboard_append(item_text)
# Kontextmenü für Kopieren hinzufügen
tree.bind("<Button-3>", lambda event: tree.focus() or tree.selection_set(tree.identify_row(event.y)) or tree.selection_add(tree.identify_row(event.y)))
popup_menu = Menu(screen3, tearoff=0)
popup_menu.add_command(label="Kopieren", command=copy_selection)
def popup(event):
popup_menu.post(event.x_root, event.y_root)
tree.bind("<Button-3>", popup)
# Doppelklick-Ereignisbindung für die Treeview
tree.bind("<Double-1>", on_double_cklick)
# Tabelle in das Fenster einfügen
tree.pack(expand=True, fill=BOTH)
# Textfeld für die Übernahme des Schlüssels per Doppelklick
key_entry = Text(screen3, font=("Roboto", 10), bg="white", relief=GROOVE, wrap=WORD, bd=0)
key_entry.pack(expand=True, fill=BOTH)
def update_password_strength():
password = code.get()
strength_feedback = check_password_strength(password)
if strength_feedback == "Die Schlüsselstärke ist ausreichend.":
strength_label.config(text="Schlüsselstärke: Stark", fg="green")
else:
strength_label.config(text=strength_feedback, fg="red")
def toggle_key_visibility():
global show_key_icon
if key_entry.cget('show') == '*':
key_entry.config(show='')
show_key_icon = hide_key_image
else:
key_entry.config(show='*')
show_key_icon = show_key_image
show_hide_key_button.config(image=show_key_icon)
def on_closing():
if messagebox.askokcancel("Beenden", "Möchten Sie das Programm wirklich beenden?"):
save_password_history()
screen.destroy()
def load_password_history():
global password_history
try:
with open('database/password_history.json', 'r') as file:
password_history = json.load(file)
except FileNotFoundError:
pass # Die Datei existiert noch nicht
load_password_history()
def main_screen():
global screen
global code
global text1
global strength_label
global show_key_image
global hide_key_image
global show_key_icon
global key_entry
global show_hide_key_button
screen = Tk()
screen.geometry("390x440")
# Icon
image_icon = PhotoImage(file="img/kisspng-key-icon-magic-keys.png")
screen.iconphoto(False, image_icon)
screen.title("Secret Messenger")
def reset():
code.set("")
text1.delete(1.0, END)
Label(text="Text oder Chiffre hier eingeben:", fg="black", font=('calibri', 13)).place(x=10, y=10)
text1 = Text(font=("Roboto", 10), bg="white", relief=GROOVE, wrap=WORD, bd=0)
text1.place(x=10, y=40, width=345, height=100)
Label(text="Geheimer Schlüssel:", fg="black", font=("calibri", 13)).place(x=10, y=170)
Button(screen, text="Vorschläge", height="1", width=9, bg="#1089ff", fg="white", bd=0, command=open_history).place(x=278, y=170)
code = StringVar()
key_entry = Entry(textvariable=code, width=37, bd=0, font=("arial", 13), show="*")
key_entry.place(x=10, y=200, height=30)
# Define images for showing and hiding key
show_key_image = PhotoImage(file="img/show_password.png")
hide_key_image = PhotoImage(file="img/hide_password.png")
# Button to toggle key visibility
show_key_icon = show_key_image
show_hide_key_button = Button(screen, image=show_key_icon, bd=0, command=toggle_key_visibility)
show_hide_key_button.place(x=355, y=210)
# Add label for password strength feedback
strength_label = Label(text="Schlüsselstärke: ", fg="black", font=("calibri", 11))
strength_label.place(x=10, y=255)
# Add button to update password strength feedback
Button(text="Check Password Strength", height="1", width=23, bg="#1089ff", fg="white", bd=0, command=update_password_strength).place(x=10, y=280)
# Add button with icon
decrypt_icon = PhotoImage(file="img/decrypt_icon.png")
Button(screen, text="VERSCHLÜSSELN", image=decrypt_icon, compound=LEFT, padx=10, pady=10, height="22", width=153, bg="#ed3833", fg="white", bd=0, command=encrypt).place(x=10, y=330)
encrypt_icon = PhotoImage(file="img/encrypt_icon.png")
Button(screen, text="ENTSCHLÜSSELN", image=encrypt_icon, compound=LEFT, padx=10, pady=10, height="22", width=152, bg="#00bd56", fg="white", bd=0, command=decrypt).place(x=200, y=330)
Button(screen, text="RESET", height="2", width=51, bg="#6a6a6a", fg="white", bd=0, command=reset).place(x=10, y=380)
history_label = Label(screen, text="History", fg="blue", font=("calibri", 10, "underline"), cursor="hand2")
history_label.bind("<Button-1>", lambda e: show_password_history())
history_label.place(x=295, y=230)
screen.mainloop()
main_screen()