-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.py
More file actions
381 lines (323 loc) · 13.6 KB
/
App.py
File metadata and controls
381 lines (323 loc) · 13.6 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
#!/usr/bin/env python3
"""
Enhanced Message Encryptor/Decryptor Application
A modern GUI application for encrypting and decrypting messages using various
cryptographic ciphers. Features a responsive design that works across platforms.
Author: PhyniX and AlexBesios
"""
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import customtkinter as ctk
import sys
import os
import platform
from typing import Dict, Any, Optional
try:
import Ciphers as cp
except ImportError:
print("Error: Could not import Ciphers module")
sys.exit(1)
class CryptoGUI:
"""Main application class for the Crypto GUI."""
def __init__(self):
"""Initialize the GUI application."""
self.setup_appearance()
self.create_main_window()
self.create_widgets()
self.setup_bindings()
def setup_appearance(self):
"""Set up the appearance mode and color theme."""
# Set appearance mode and default color theme
ctk.set_appearance_mode("dark") # Modes: "System" (standard), "Dark", "Light"
ctk.set_default_color_theme(
"blue"
) # Themes: "blue" (standard), "green", "dark-blue"
def create_main_window(self):
"""Create and configure the main window."""
self.root = ctk.CTk()
self.root.title("Message Encryptor/Decryptor")
# Get screen dimensions for responsive sizing
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
# Calculate window size (70% of screen)
window_width = min(800, int(screen_width * 0.7))
window_height = min(700, int(screen_height * 0.7))
# Center the window
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")
self.root.minsize(600, 500)
# Configure grid weights for responsive design
self.root.grid_columnconfigure(0, weight=1)
self.root.grid_rowconfigure(0, weight=1)
# Platform-specific configurations
if platform.system() == "Linux":
# Linux-specific font configurations
self.root.option_add("*Font", "DejaVu Sans 10")
def create_widgets(self):
"""Create all GUI widgets."""
# Main container with padding
main_frame = ctk.CTkFrame(self.root)
main_frame.grid(row=0, column=0, padx=20, pady=20, sticky="nsew")
main_frame.grid_columnconfigure(0, weight=1)
main_frame.grid_rowconfigure(4, weight=1) # Make result area expandable
# Title
title_label = ctk.CTkLabel(
main_frame,
text="🔐 Message Encryptor/Decryptor",
font=ctk.CTkFont(size=24, weight="bold"),
)
title_label.grid(row=0, column=0, pady=(20, 30), sticky="ew")
# Configuration frame
config_frame = ctk.CTkFrame(main_frame)
config_frame.grid(row=1, column=0, padx=20, pady=(0, 20), sticky="ew")
config_frame.grid_columnconfigure(1, weight=1)
# Cipher selection
cipher_label = ctk.CTkLabel(
config_frame, text="Cipher:", font=ctk.CTkFont(weight="bold")
)
cipher_label.grid(row=0, column=0, padx=(20, 10), pady=15, sticky="w")
self.cipher_var = tk.StringVar(value="Caesar")
self.cipher_menu = ctk.CTkOptionMenu(
config_frame,
variable=self.cipher_var,
values=["Caesar", "Vigenère", "Affine", "Substitution", "OTP", "Hill"],
command=self.on_cipher_change,
)
self.cipher_menu.grid(row=0, column=1, padx=(0, 20), pady=15, sticky="ew")
# Action selection
action_label = ctk.CTkLabel(
config_frame, text="Action:", font=ctk.CTkFont(weight="bold")
)
action_label.grid(row=1, column=0, padx=(20, 10), pady=15, sticky="w")
self.action_var = tk.StringVar(value="Encrypt")
action_menu = ctk.CTkOptionMenu(
config_frame, variable=self.action_var, values=["Encrypt", "Decrypt"]
)
action_menu.grid(row=1, column=1, padx=(0, 20), pady=15, sticky="ew")
# Input frame
input_frame = ctk.CTkFrame(main_frame)
input_frame.grid(row=2, column=0, padx=20, pady=(0, 20), sticky="ew")
input_frame.grid_columnconfigure(0, weight=1)
# Message input
message_label = ctk.CTkLabel(
input_frame, text="Message:", font=ctk.CTkFont(weight="bold")
)
message_label.grid(row=0, column=0, padx=20, pady=(20, 5), sticky="w")
self.message_textbox = ctk.CTkTextbox(input_frame, height=80)
self.message_textbox.grid(row=1, column=0, padx=20, pady=(0, 15), sticky="ew")
# Key input with dynamic help text
key_label = ctk.CTkLabel(
input_frame, text="Key:", font=ctk.CTkFont(weight="bold")
)
key_label.grid(row=2, column=0, padx=20, pady=(15, 5), sticky="w")
self.key_entry = ctk.CTkEntry(input_frame, placeholder_text="Enter key...")
self.key_entry.grid(row=3, column=0, padx=20, pady=(0, 10), sticky="ew")
# Key help text
self.key_help_label = ctk.CTkLabel(
input_frame,
text=self.get_key_help("Caesar"),
font=ctk.CTkFont(size=12),
text_color="gray60",
)
self.key_help_label.grid(row=4, column=0, padx=20, pady=(0, 20), sticky="w")
# Action button
self.action_button = ctk.CTkButton(
main_frame,
text="🔄 Perform Encryption",
command=self.perform_action,
height=40,
font=ctk.CTkFont(size=16, weight="bold"),
)
self.action_button.grid(row=3, column=0, padx=20, pady=(0, 20), sticky="ew")
# Result frame
result_frame = ctk.CTkFrame(main_frame)
result_frame.grid(row=4, column=0, padx=20, pady=(0, 20), sticky="nsew")
result_frame.grid_columnconfigure(0, weight=1)
result_frame.grid_rowconfigure(1, weight=1)
result_label = ctk.CTkLabel(
result_frame, text="Result:", font=ctk.CTkFont(weight="bold")
)
result_label.grid(row=0, column=0, padx=20, pady=(20, 5), sticky="w")
self.result_textbox = ctk.CTkTextbox(result_frame, height=120)
self.result_textbox.grid(row=1, column=0, padx=20, pady=(0, 20), sticky="nsew")
# Copy button
copy_button = ctk.CTkButton(
result_frame, text="📋 Copy Result", command=self.copy_result, height=32
)
copy_button.grid(row=2, column=0, padx=20, pady=(0, 20), sticky="ew")
# Status bar
self.status_var = tk.StringVar(value="Ready")
status_label = ctk.CTkLabel(
main_frame,
textvariable=self.status_var,
font=ctk.CTkFont(size=11),
text_color="gray60",
)
status_label.grid(row=5, column=0, padx=20, pady=(0, 10), sticky="w")
def setup_bindings(self):
"""Set up keyboard bindings."""
# Bind Enter key to perform action
self.root.bind("<Return>", lambda e: self.perform_action())
self.root.bind("<Control-Return>", lambda e: self.perform_action())
# Bind Ctrl+C to copy result
self.root.bind("<Control-c>", lambda e: self.copy_result())
def get_key_help(self, cipher: str) -> str:
"""Get help text for the current cipher's key format."""
help_texts = {
"Caesar": "Enter an integer (e.g., 3)",
"Vigenère": "Enter a keyword (e.g., KEY)",
"Affine": "Enter two integers separated by comma (e.g., 5,8)",
"Hill": "Enter a square matrix (e.g., [[6, 24], [1, 13]])",
"Substitution": "Enter a dictionary (e.g., {'a': 'm', 'b': 'n', 'c': 'o'})",
"OTP": "Enter a string key at least as long as the message",
}
return help_texts.get(cipher, "Enter appropriate key for selected cipher")
def on_cipher_change(self, choice: str):
"""Handle cipher selection change."""
self.key_help_label.configure(text=self.get_key_help(choice))
self.key_entry.delete(0, tk.END)
# Update button text based on action
action = self.action_var.get()
icon = "🔒" if action == "Encrypt" else "🔓"
self.action_button.configure(text=f"{icon} Perform {action}")
def validate_inputs(self) -> tuple[str, str, str]:
"""Validate and return cleaned inputs."""
cipher = self.cipher_var.get()
action = self.action_var.get()
message = self.message_textbox.get("1.0", tk.END).strip()
key = self.key_entry.get().strip()
if not message:
raise ValueError("Message cannot be empty")
if not key:
raise ValueError("Key cannot be empty")
return cipher, action, message, key
def parse_key(self, cipher: str, key_str: str) -> Any:
"""Parse and validate the key based on cipher type."""
try:
if cipher == "Caesar":
return int(key_str)
elif cipher == "Vigenère":
if not key_str.isalpha():
raise ValueError("Vigenère key must contain only letters")
return key_str
elif cipher == "Affine":
parts = key_str.split(",")
if len(parts) != 2:
raise ValueError(
"Affine key must be two integers separated by comma"
)
return int(parts[0].strip()), int(parts[1].strip())
elif cipher == "Substitution":
return cp.safe_parse_substitution_key(key_str)
elif cipher == "Hill":
return cp.safe_parse_matrix(key_str)
elif cipher == "OTP":
return key_str
else:
raise ValueError(f"Unknown cipher: {cipher}")
except ValueError as e:
raise ValueError(f"Invalid key format: {str(e)}")
def perform_cipher_operation(
self, cipher: str, action: str, message: str, key: Any
) -> str:
"""Perform the actual cipher operation."""
if cipher == "Caesar":
return (
cp.caesar_encrypt(message, key)
if action == "Encrypt"
else cp.caesar_decrypt(message, key)
)
elif cipher == "Vigenère":
return (
cp.vigenere_encrypt(message, key)
if action == "Encrypt"
else cp.vigenere_decrypt(message, key)
)
elif cipher == "Affine":
a, b = key
return (
cp.affine_encrypt(message, a, b)
if action == "Encrypt"
else cp.affine_decrypt(message, a, b)
)
elif cipher == "Substitution":
return (
cp.substitution_encrypt(message, key)
if action == "Encrypt"
else cp.substitution_decrypt(message, key)
)
elif cipher == "OTP":
return (
cp.otp_encrypt(message, key)
if action == "Encrypt"
else cp.otp_decrypt(message, key)
)
elif cipher == "Hill":
return (
cp.hill_encrypt(message, key)
if action == "Encrypt"
else cp.hill_decrypt(message, key)
)
else:
raise ValueError(f"Unknown cipher: {cipher}")
def perform_action(self):
"""Perform the encryption/decryption action."""
try:
# Update status
self.status_var.set("Processing...")
self.root.update_idletasks()
# Validate inputs
cipher, action, message, key_str = self.validate_inputs()
# Parse key
key = self.parse_key(cipher, key_str)
# Perform operation
result = self.perform_cipher_operation(cipher, action, message, key)
# Display result
self.result_textbox.delete("1.0", tk.END)
self.result_textbox.insert("1.0", result)
# Update status
self.status_var.set(
f"{action} completed successfully using {cipher} cipher"
)
except ValueError as e:
self.show_error("Input Error", str(e))
self.status_var.set("Error: Invalid input")
except Exception as e:
self.show_error(
"Unexpected Error", f"An unexpected error occurred: {str(e)}"
)
self.status_var.set("Error: Operation failed")
def copy_result(self):
"""Copy result to clipboard."""
try:
result = self.result_textbox.get("1.0", tk.END).strip()
if result:
self.root.clipboard_clear()
self.root.clipboard_append(result)
self.status_var.set("Result copied to clipboard")
else:
self.status_var.set("No result to copy")
except Exception as e:
self.show_error("Copy Error", f"Failed to copy result: {str(e)}")
def show_error(self, title: str, message: str):
"""Show error message dialog."""
messagebox.showerror(title, message)
def run(self):
"""Start the GUI application."""
try:
self.root.mainloop()
except KeyboardInterrupt:
print("\nApplication interrupted by user")
except Exception as e:
print(f"Unexpected error: {e}")
def main():
"""Main entry point of the application."""
try:
app = CryptoGUI()
app.run()
except Exception as e:
print(f"Failed to start application: {e}")
sys.exit(1)
if __name__ == "__main__":
main()