-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVignereBreaker.py
More file actions
668 lines (553 loc) · 21.9 KB
/
VignereBreaker.py
File metadata and controls
668 lines (553 loc) · 21.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QWidget,
QVBoxLayout,
QHBoxLayout,
QLabel,
QPushButton,
QGroupBox,
QScrollArea,
QLineEdit,
QComboBox,
QApplication,
QTextEdit,
QMessageBox,
QFormLayout,
)
from ChiSquare import ChiSquare
from FrequencyAnalysis import Frequency
from FriedmanAnalysis import Friedman
from SubstringDistance import SubstringDistance
import markdown
class AlphabetSlider(QWidget):
"""Widget for shifting cipher alphabets with improved visual feedback"""
def __init__(self, alphabet, parent, index=0):
super(QWidget, self).__init__(parent)
self.parent1 = parent
self.alphabet = alphabet
self.oalphabet = alphabet
self.shift = 0
self.index = index
layout = QVBoxLayout()
# Add position label
position_label = QLabel(f"Position {index}")
position_label.setStyleSheet("font-weight: bold; color: #555;")
layout.addWidget(position_label)
# Control layout
control_layout = QHBoxLayout()
self.lbutton = QPushButton("◀")
self.lbutton.setToolTip("Shift alphabet left (decrease key value)")
self.lbutton.setFixedWidth(40)
self.lbutton.clicked.connect(self.shiftLeft)
control_layout.addWidget(self.lbutton)
# Shift indicator
self.shift_label = QLabel(
f"Shift: {self.shift} Key Value: {self.oalphabet[self.shift]}"
)
self.shift_label.setAlignment(Qt.AlignCenter)
self.shift_label.setStyleSheet("font-weight: bold; color: #0066cc;")
self.shift_label.setMinimumWidth(80)
control_layout.addWidget(self.shift_label)
self.rbutton = QPushButton("▶")
self.rbutton.setToolTip("Shift alphabet right (increase key value)")
self.rbutton.setFixedWidth(40)
self.rbutton.clicked.connect(self.shiftRight)
control_layout.addWidget(self.rbutton)
layout.addLayout(control_layout)
# Alphabet display
self.label = QLabel(alphabet)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet(
"""
QLabel {
font-family: 'Courier New', monospace;
font-size: 12pt;
padding: 8px;
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 4px;
}
"""
)
layout.addWidget(self.label)
self.setLayout(layout)
def shiftRight(self):
self.alphabet = self.alphabet[-1] + self.alphabet[:-1]
self.label.setText(self.alphabet)
self.shift = (self.shift + 1) % len(self.alphabet)
self.shift_label.setText(
f"Shift: {self.shift} Key Value: {self.oalphabet[self.shift]}"
)
self.parent1.changePreview()
def shiftLeft(self):
self.alphabet = self.alphabet[1:] + self.alphabet[0]
self.label.setText(self.alphabet)
self.shift = (self.shift - 1) % len(self.alphabet)
self.shift_label.setText(
f"Shift: {self.shift} Key Value: {self.oalphabet[self.shift]}"
)
self.parent1.changePreview()
def setAlphabet(self, alphabet):
self.alphabet = alphabet
self.oalphabet = alphabet
self.shift = 0
self.shift_label.setText(
f"Shift: {self.shift} Key Value: {self.oalphabet[self.shift]}"
)
self.label.setText(self.alphabet)
self.parent1.changePreview()
class VigenereWindow(QWidget):
"""Main window for Vigenère cipher analysis with improved UX"""
def __init__(self, parent=None):
super(VigenereWindow, self).__init__(parent)
self.setWindowTitle("Vigenère Cipher Analyzer")
self.setMinimumSize(900, 700)
main_layout = QVBoxLayout()
# Add instructions panel
self.add_instructions_panel(main_layout)
# Add alphabet configuration section
self.add_alphabet_config(main_layout)
# Add ciphertext input section
self.add_ciphertext_input(main_layout)
# Add analysis tools section
self.add_analysis_tools(main_layout)
# Add key configuration section
self.add_key_config(main_layout)
# Add statistics section
self.add_statistics_section(main_layout)
# Add preview section
self.add_preview_section(main_layout)
self.setLayout(main_layout)
# Initialize analysis windows
self.substringd = None
self.friedmanw = None
self.frequencyw = None
self.chiw = None
def add_instructions_panel(self, layout):
"""Add collapsible instructions panel"""
instructions_group = QGroupBox("ℹ️ Instructions")
instructions_group.setStyleSheet(
"""
QGroupBox {
font-weight: bold;
border: 2px solid #4CAF50;
border-radius: 5px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
color: #4CAF50;
}
"""
)
instructions_layout = QVBoxLayout()
instructions_text = QLabel(
markdown.markdown(
"""
## How to use this tool:
1. **Enter ciphertext:** Paste the encrypted text you want to analyze
2. **Determine key length:** Use Friedman Test or Substring Distance analysis
3. **Set key length:** Select the likely key length from the dropdown
4. **Analyze frequencies:** Use Frequency or Chi-Square analysis to find shift values
5. **Adjust shifts:** Use the arrow buttons to shift each alphabet position until readable text appears
6. **Read decrypted text:** View the result in the preview panel at the bottom
**Tips:**
- The Friedman test helps estimate key length based on Index of Coincidence
- Substring distance looks for repeating patterns in the ciphertext
- Frequency analysis compares letter frequencies to expected English frequencies
- Chi-square analysis provides a statistical measure of how English-like the text is
"""
)
)
instructions_text.setWordWrap(True)
instructions_text.setStyleSheet("padding: 10px; font-weight: normal;")
scroll = QScrollArea()
scroll.setWidget(instructions_text)
instructions_layout.addWidget(scroll)
instructions_group.setLayout(instructions_layout)
layout.addWidget(instructions_group)
def add_alphabet_config(self, layout):
"""Add alphabet configuration section"""
alphabet_group = QGroupBox("📝 Alphabet Configuration")
alphabet_group.setStyleSheet(
"""
QGroupBox {
font-weight: bold;
border: 2px solid #2196F3;
border-radius: 5px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
color: #2196F3;
}
"""
)
alphabet_layout = QFormLayout()
# Plain alphabet
plain_label = QLabel("Plaintext Alphabet:")
plain_label.setToolTip(
"The alphabet used for the decrypted text (usually standard A-Z)"
)
self.plainalphabettextbox = QLineEdit()
self.plainalphabettextbox.setText("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
self.plainalphabettextbox.setPlaceholderText(
"Enter plaintext alphabet (e.g., ABCDEFGHIJKLMNOPQRSTUVWXYZ)"
)
self.plainalphabettextbox.textChanged.connect(self.changePlainLabel)
alphabet_layout.addRow(plain_label, self.plainalphabettextbox)
# Cipher alphabet
cipher_label = QLabel("Ciphertext Alphabet:")
cipher_label.setToolTip(
"The alphabet used in the encrypted text (may be reordered)"
)
self.cipheralphabettextbox = QLineEdit()
self.cipheralphabettextbox.setText("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
self.cipheralphabettextbox.setPlaceholderText("Enter ciphertext alphabet")
self.cipheralphabettextbox.textChanged.connect(self.changeCipherLabel)
alphabet_layout.addRow(cipher_label, self.cipheralphabettextbox)
alphabet_group.setLayout(alphabet_layout)
layout.addWidget(alphabet_group)
def add_ciphertext_input(self, layout):
"""Add ciphertext input section"""
ciphertext_group = QGroupBox("🔒 Encrypted Text Input")
ciphertext_group.setStyleSheet(
"""
QGroupBox {
font-weight: bold;
border: 2px solid #FF5722;
border-radius: 5px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
color: #FF5722;
}
"""
)
ciphertext_layout = QVBoxLayout()
label = QLabel("Paste your encrypted text below:")
ciphertext_layout.addWidget(label)
self.ciphertextbox = QTextEdit()
self.ciphertextbox.setPlaceholderText("Enter or paste ciphertext here...")
self.ciphertextbox.setMaximumHeight(100)
self.ciphertextbox.textChanged.connect(self.cipherTextChanged)
ciphertext_layout.addWidget(self.ciphertextbox)
# Add character count
self.char_count_label = QLabel("Characters: 0")
self.char_count_label.setStyleSheet("color: #666; font-style: italic;")
ciphertext_layout.addWidget(self.char_count_label)
ciphertext_group.setLayout(ciphertext_layout)
layout.addWidget(ciphertext_group)
def add_analysis_tools(self, layout):
"""Add analysis tools section"""
tools_group = QGroupBox("🔍 Analysis Tools")
tools_group.setStyleSheet(
"""
QGroupBox {
font-weight: bold;
border: 2px solid #9C27B0;
border-radius: 5px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
color: #9C27B0;
}
"""
)
tools_layout = QVBoxLayout()
# First row: Key length analysis
key_length_layout = QHBoxLayout()
key_length_label = QLabel("Determine Key Length:")
key_length_label.setStyleSheet("font-weight: bold;")
key_length_layout.addWidget(key_length_label)
self.substringd_button = QPushButton("📊 Substring Distance")
self.substringd_button.setToolTip(
"Find repeating patterns to estimate key length"
)
self.substringd_button.clicked.connect(self.launch_substringd)
key_length_layout.addWidget(self.substringd_button)
self.friedman_button = QPushButton("📈 Friedman Test")
self.friedman_button.setToolTip(
"Calculate Index of Coincidence to estimate key length"
)
self.friedman_button.clicked.connect(self.launch_friedman)
key_length_layout.addWidget(self.friedman_button)
key_length_layout.addStretch()
tools_layout.addLayout(key_length_layout)
# Second row: Frequency analysis
freq_layout = QHBoxLayout()
freq_label = QLabel("Analyze Letter Frequencies:")
freq_label.setStyleSheet("font-weight: bold;")
freq_layout.addWidget(freq_label)
self.frequency_button = QPushButton("📊 Frequency Analysis")
self.frequency_button.setToolTip(
"Compare letter frequencies with expected English frequencies"
)
self.frequency_button.clicked.connect(self.launch_frequency)
freq_layout.addWidget(self.frequency_button)
self.chi_button = QPushButton("📉 Chi-Square Analysis")
self.chi_button.setToolTip("Statistical analysis to find the best shift values")
self.chi_button.clicked.connect(self.launch_chi)
freq_layout.addWidget(self.chi_button)
freq_layout.addStretch()
tools_layout.addLayout(freq_layout)
tools_group.setLayout(tools_layout)
layout.addWidget(tools_group)
def add_key_config(self, layout):
"""Add key configuration section"""
key_group = QGroupBox("🔑 Key Configuration")
key_group.setStyleSheet(
"""
QGroupBox {
font-weight: bold;
border: 2px solid #FF9800;
border-radius: 5px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
color: #FF9800;
}
"""
)
key_layout = QVBoxLayout()
# Key length selector
length_layout = QHBoxLayout()
length_label = QLabel("Key Length:")
length_label.setToolTip("Number of different Caesar shifts in the key")
length_label.setStyleSheet("font-weight: bold;")
length_layout.addWidget(length_label)
self.number_alphabets = QComboBox()
self.number_alphabets.addItems([str(x) for x in range(1, 25)])
self.number_alphabets.setToolTip(
"Select the estimated length of the Vigenère key"
)
self.number_alphabets.currentIndexChanged.connect(self.changeNumberAlphabets)
length_layout.addWidget(self.number_alphabets)
length_layout.addStretch()
key_layout.addLayout(length_layout)
# Current cipher alphabet display
self.ciphertextlabel = QLabel("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
self.ciphertextlabel.setAlignment(Qt.AlignCenter)
self.ciphertextlabel.setStyleSheet(
"""
font-family: 'Courier New', monospace;
font-size: 11pt;
padding: 5px;
background-color: #fff3e0;
border: 1px solid #FF9800;
border-radius: 3px;
"""
)
key_layout.addWidget(self.ciphertextlabel)
# Alphabet sliders in scroll area
slider_label = QLabel("Adjust each position of the key:")
slider_label.setStyleSheet("font-weight: bold; margin-top: 10px;")
key_layout.addWidget(slider_label)
scrollArea = QScrollArea()
scrollArea.setWidgetResizable(True)
scrollArea.setMaximumHeight(300)
alphabet_widget = QWidget()
self.alphabet_widget_layout = QVBoxLayout()
self.alphabets = [AlphabetSlider("ABCDEFGHIJKLMNOPQRSTUVWXYZ", self, 0)]
self.alphabet_widget_layout.addWidget(self.alphabets[0])
alphabet_widget.setLayout(self.alphabet_widget_layout)
scrollArea.setWidget(alphabet_widget)
key_layout.addWidget(scrollArea)
key_group.setLayout(key_layout)
layout.addWidget(key_group)
def add_statistics_section(self, layout):
"""Add statistics display section"""
stats_group = QGroupBox("📊 Statistics")
stats_group.setStyleSheet(
"""
QGroupBox {
font-weight: bold;
border: 2px solid #607D8B;
border-radius: 5px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
color: #607D8B;
}
"""
)
stats_layout = QHBoxLayout()
ic_label = QLabel("Index of Coincidence:")
ic_label.setToolTip(
"Higher IC (closer to 0.065) suggests more English-like text"
)
stats_layout.addWidget(ic_label)
self.overall_IC_label = QLabel("N/A")
self.overall_IC_label.setStyleSheet("font-weight: bold; color: #0066cc;")
stats_layout.addWidget(self.overall_IC_label)
stats_layout.addStretch()
chi_label = QLabel("Chi-Square Value:")
chi_label.setToolTip("Lower chi-square value suggests better match to English")
stats_layout.addWidget(chi_label)
self.overall_chi_label = QLabel("N/A")
self.overall_chi_label.setStyleSheet("font-weight: bold; color: #0066cc;")
stats_layout.addWidget(self.overall_chi_label)
stats_group.setLayout(stats_layout)
layout.addWidget(stats_group)
def add_preview_section(self, layout):
"""Add decrypted text preview section"""
preview_group = QGroupBox("✅ Decrypted Text Preview")
preview_group.setStyleSheet(
"""
QGroupBox {
font-weight: bold;
border: 2px solid #4CAF50;
border-radius: 5px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
color: #4CAF50;
}
"""
)
preview_layout = QVBoxLayout()
help_label = QLabel(
"The decrypted text appears below. Adjust the key shifts until readable text appears:"
)
help_label.setStyleSheet("font-style: italic; color: #666;")
preview_layout.addWidget(help_label)
self.previewtextbox = QTextEdit()
self.previewtextbox.setReadOnly(True)
self.previewtextbox.setPlaceholderText("Decrypted text will appear here...")
self.previewtextbox.setStyleSheet(
"""
QTextEdit {
font-family: 'Courier New', monospace;
font-size: 11pt;
background-color: #e8f5e9;
}
"""
)
preview_layout.addWidget(self.previewtextbox)
# Add copy button
copy_button = QPushButton("📋 Copy Decrypted Text")
copy_button.clicked.connect(self.copy_preview)
copy_button.setToolTip("Copy the decrypted text to clipboard")
preview_layout.addWidget(copy_button)
preview_group.setLayout(preview_layout)
layout.addWidget(preview_group)
def copy_preview(self):
"""Copy decrypted text to clipboard"""
clipboard = QApplication.clipboard()
clipboard.setText(self.decode(include_forgein=False))
# Show confirmation
QMessageBox.information(self, "Copied", "Decrypted text copied to clipboard!")
def cipherTextChanged(self):
# Update character count
text = self.ciphertextbox.toPlainText()
cipher_alpha = self.cipheralphabettextbox.text()
alpha_chars = sum(1 for c in text if c in cipher_alpha)
self.char_count_label.setText(
f"Characters: {len(text)} (Alphabet chars: {alpha_chars})"
)
self.changePreview()
if self.substringd:
self.substringd.plot()
if self.friedmanw:
self.friedmanw.plot()
if self.frequencyw:
self.frequencyw.plot()
def changeCipherLabel(self):
self.ciphertextlabel.setText(self.cipheralphabettextbox.text())
self.changePreview()
if self.friedmanw:
self.friedmanw.plot()
def changePlainLabel(self):
text = self.plainalphabettextbox.text()
for i, w in enumerate(self.alphabets):
w.setAlphabet(text)
self.changePreview()
def changeNumberAlphabets(self):
new = int(self.number_alphabets.currentText())
text = self.plainalphabettextbox.text()
while new > len(self.alphabets):
w = AlphabetSlider(text, self, len(self.alphabets))
self.alphabets.append(w)
self.alphabet_widget_layout.addWidget(w)
while new < len(self.alphabets):
self.alphabet_widget_layout.removeWidget(self.alphabets[-1])
self.alphabets[-1].deleteLater()
self.alphabets.remove(self.alphabets[-1])
if self.frequencyw:
self.frequencyw.lengthbox.setCurrentText(
self.number_alphabets.currentText()
)
if self.chiw:
self.chiw.lengthbox.setCurrentText(self.number_alphabets.currentText())
self.changePreview()
def decode(self, include_forgein=True):
ciphertext = self.ciphertextbox.toPlainText()
cipher_alpha = self.cipheralphabettextbox.text()
out = ""
i = 0
for c in ciphertext:
if c in cipher_alpha:
d = cipher_alpha.index(c)
out += self.alphabets[i % len(self.alphabets)].alphabet[d]
i += 1
else:
if include_forgein:
out += c
return out
def changePreview(self):
out = self.decode()
alpha = self.cipheralphabettextbox.text()
try:
ic_value = Friedman.IC(out, alpha)
self.overall_IC_label.setText(f"{ic_value:.4f}")
except:
self.overall_IC_label.setText("N/A")
if self.chiw:
try:
chi_value = self.chiw.current_chi_value()
self.overall_chi_label.setText(f"{chi_value:.2f}")
except:
self.overall_chi_label.setText("N/A")
# Format preview text in columns
length = len(self.alphabets)
formatted_lines = []
for i in range(0, len(out), length * 10): # 10 groups per line
line_chunk = out[i : i + length * 10]
groups = [
line_chunk[j : j + length] for j in range(0, len(line_chunk), length)
]
formatted_lines.append(" ".join(groups))
self.previewtextbox.setText("\n".join(formatted_lines))
def launch_substringd(self):
if not self.substringd:
self.substringd = SubstringDistance(self)
if not self.substringd.isVisible():
self.substringd.show()
def launch_friedman(self):
if not self.friedmanw:
self.friedmanw = Friedman(self)
if not self.friedmanw.isVisible():
self.friedmanw.show()
def launch_frequency(self):
if not self.frequencyw:
self.frequencyw = Frequency(self)
if not self.frequencyw.isVisible():
self.frequencyw.show()
def launch_chi(self):
if not self.chiw:
self.chiw = ChiSquare(self)
if not self.chiw.isVisible():
self.chiw.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
# Set application-wide style
app.setStyle("Fusion")
main = VigenereWindow()
main.show()
sys.exit(app.exec_())