-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcipher_decryption.py
More file actions
2132 lines (1958 loc) · 66.5 KB
/
Copy pathcipher_decryption.py
File metadata and controls
2132 lines (1958 loc) · 66.5 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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import math
import collections
import itertools
import functools
import cipher_texts
import pdb
import random
import numpy as np
start_time = time.time()
# -----------------------
# -----------------------
# ---Utility functions---
# -----------------------
# -----------------------
def match(original: str, formatted: str) -> str:
formatted = list(letters(formatted).lower())
original = list(original)
for index, value in enumerate(formatted):
if not original[index].isalpha() and formatted[index].isalpha():
formatted.insert(index, original[index])
elif original[index].isupper() and formatted[index].isalpha():
formatted[index] = formatted[index].upper()
result = "".join(formatted)
return result
def letters(string: str, keep: list=[]) -> str:
"""Return only alphabetic letters or those in keep."""
return "".join(
character for character in string
if character.isalpha() or character in keep)
def mod_inverse(num: int, mod: int) -> int:
"""Return the modular inverse of num modulo mod, if it exists."""
num = num % mod
for possible_inverse in range(mod):
if num * possible_inverse % mod == 1:
return possible_inverse
raise ValueError
def word_reverse(text: str) -> str:
"""Reverse all the words in a text."""
return " ".join(
"".join(reversed(word))
for word in text.split(" ")
)
def pad_to_length(string: str, length: int, fillvalue=" "):
new_string = string
if len(new_string) >= length:
return new_string
else:
new_string += fillvalue
return pad_to_length(new_string, length, fillvalue=fillvalue)
def chunked(iterable, chunk_length):
return (
iterable[i: i + chunk_length]
for i in range(0, len(iterable), chunk_length)
)
def keys_nicer(key):
new_key = dict()
new_key_ls = list()
for k, v in key.items():
new_key_ls.append(
(k, v.upper())
)
return dict(sorted(new_key_ls, key=lambda x: x[1]))
def key_swap_chars(key, char1, char2):
new_key = dict(key.items())
for k, value in new_key.items():
if value == char1:
swap1 = k
elif value == char2:
swap2 = k
new_key[swap1], new_key[swap2] = new_key[swap2], new_key[swap1]
return keys_nicer(new_key)
def hill_climbing(
initial_key,
fitness,
neighbors,
count=1000
):
current_key = initial_key
for c in range(count):
possible_keys = list()
parent_fitness = fitness(current_key)
print(parent_fitness)
possible_keys.append(KeyFit(key=current_key, fitness=parent_fitness))
for child_key in neighbors(current_key):
child_fitness = fitness(child_key)
possible_keys.append(KeyFit(key=child_key, fitness=child_fitness))
best_key = sorted(
possible_keys,
key=lambda elem: elem.fitness,
reverse=True
)[0].key
if current_key == best_key:
break
else:
current_key = best_key
return current_key
def simulated_annealing(
initial_key,
fitness,
new_key,
initial_temp=50,
count=10000,
max_length=1000,
stale=100000,
stale_fitness=-100000,
threshold=-100000
):
temp_step = initial_temp / count
temp = initial_temp
current_key = initial_key
same_key = 0
best_fitness = -100000
for c in range(count):
if same_key == max_length:
break
print(c)
if c == stale and best_fitness < stale_fitness:
print("Stale! Restarting.")
return simulated_annealing(
initial_key=best_key,
fitness=fitness,
new_key=new_key,
initial_temp=initial_temp,
count=count,
max_length=max_length,
stale=stale,
stale_fitness=stale_fitness,
threshold=threshold
)
parent_fitness = fitness(current_key)
print("Fitness: ", parent_fitness)
child_key = new_key(current_key)
child_fitness = fitness(child_key)
dF = child_fitness - parent_fitness
if dF > 0:
current_key = child_key
same_key = 0
print("New key!")
elif dF < 0 and math.e ** (dF/temp) >= random.random():
current_key = child_key
same_key = 0
print("New key!")
else:
same_key += 1
temp -= temp_step
if child_fitness > best_fitness:
best_key = child_key
best_fitness = child_fitness
if best_fitness < threshold:
print("Stale! Restarting.")
return simulated_annealing(
initial_key=best_key,
fitness=fitness,
new_key=new_key,
initial_temp=initial_temp,
count=count,
max_length=max_length,
stale=stale,
stale_fitness=stale_fitness,
threshold=threshold
)
return current_key
# -----------------------
# -----------------------
# --Frequency analysis---
# -----------------------
# -----------------------
ENGLISH_LANG_LEN = 26
ENGLISH_LOWER_CODEX = 0.06
ENGLISH_UPPER_CODEX = 0.071
english_chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
]
# Source: Wikipedia
english_1gram_expected_dict = {
'e': 12.49, 't': 9.28, 'a': 8.04, 'o': 7.64,
'i': 7.57, 'n': 7.23, 's': 6.51, 'r': 6.28,
'h': 5.05, 'l': 4.07, 'd': 3.82, 'c': 3.34,
'u': 2.73, 'm': 2.51, 'f': 2.40, 'p': 2.14,
'g': 1.87, 'w': 1.68, 'y': 1.66, 'b': 1.48,
'v': 1.05, 'k': 0.54, 'x': 0.23, 'j': 0.16,
'q': 0.12, 'z': 0.09
}
CharFreq = collections.namedtuple(
'CharacterFrequency', ['character', 'frequency']
)
TextFit = collections.namedtuple(
"TextFitness", ['text', 'fitness']
)
TextKey = collections.namedtuple(
"TextKey", ['text', 'key']
)
KeyFit = collections.namedtuple(
"KeyFitness", ['key', 'fitness']
)
def auto_freq_analyser(text: str, keep: list=[]) -> list:
"""Analyse the frequency of characters in a text."""
local_alphabet_freq = collections.defaultdict(int)
# text = letters(text, keep=keep).lower()
for character in text:
local_alphabet_freq[character] += 1
freq_table = (
CharFreq(character=key, frequency=value*100/len(text))
for key, value in local_alphabet_freq.items()
)
return sorted(
freq_table, key=lambda elem: elem.frequency, reverse=True
)
def english_1gram_chi(text: str) -> float:
"""
Return the chi-squared stat
between a text and the normal 1gram distribution for english.
"""
counts = {char: 0 for char in english_chars}
text = letters(text).lower()
for char in text:
counts[char] += 1
observed = (
count[1] for count in sorted(counts.items())
)
expected = (
math.ceil(english_1gram_expected_dict[char] * (
len(text) / 100)
) for char in english_chars
)
return sum((o - e)**2 / e for o, e in zip(observed, expected))
def codex(text: str) -> float:
"""Return the index of coincidence of a text."""
# text = letters(text).lower()
length = len(text)
return sum(
count * (count - 1)
for count in collections.Counter(text).values()
)/(
length * (length - 1)
)
english_4gram_expected_dict = dict()
@functools.lru_cache(maxsize=128)
def english_quadgram_fitness(text: str) -> float:
"""Return the fitness of a text, based on quadgram count."""
if not english_4gram_expected_dict:
with open("english_quadgrams.txt") as f:
total = 0
for line in f:
line = line.split(" ")
english_4gram_expected_dict[line[0]] = int(line[1])
total += int(line[1])
for key, count in english_4gram_expected_dict.items():
english_4gram_expected_dict[key] = math.log10(count/total)
fitness = 0
text = letters(text).upper()
for index in range(len(text) - 3):
quadgram = text[index:index + 4]
if quadgram in english_4gram_expected_dict:
fitness += english_4gram_expected_dict[quadgram]
else:
fitness -= 10
return fitness
# -----------------------
# -----------------------
# ------Decryption-------
# -----------------------
# -----------------------
class Caesar:
def __init__(self, text: str, shift: int=0, forced: bool=False):
self.text = text
self.shift = shift
self.auto = not (bool(self.shift) or forced)
@staticmethod
def char_shift(char: str, shift: int) -> str:
"""Shift a character by shift."""
return english_chars[
(
shift + english_chars.index(char.lower())
) % ENGLISH_LANG_LEN
]
def encipher(self, give_key=False) -> str:
"""Encipher the text."""
if self.auto:
modal_char = auto_freq_analyser(self.text)[0].character
self.shift = (
english_chars.index("e") - english_chars.index(modal_char)
) % ENGLISH_LANG_LEN
enciphered = "".join(
self.char_shift(char, self.shift) if char.isalpha()
else char for char in self.text
)
if give_key:
return TextKey(match(self.text, enciphered), self.shift)
else:
return match(self.text, enciphered)
class Affine:
Key = collections.namedtuple('AffineKey', ['a', 'b'])
TextChiKey = collections.namedtuple('TextChiKey', ['text', 'chi', 'key'])
MAX_SEARCH = 5
def __init__(self, text: str, switch: tuple=(1, 0)):
self.text = text
self.key = Affine.Key(*switch)
self.auto = bool(sum(switch) < 2)
@property
def modal_pairs(self):
"""Find the possible pairs of 'e' and 't' in the text."""
freq_chars = (
freq.character for freq in auto_freq_analyser(
self.text
)[0:Affine.MAX_SEARCH]
)
return itertools.permutations(freq_chars, 2)
@property
def prob_keys(self) -> list:
"""
Finds the possible affine keys according to this formula:
a*c1 + b = p1
a*c2 + b = p2
a*(c1 - c2) = p1 - p2
a = (p1 - p2)(c1 - c2) ^ -1
b = p1 - a*c1
"""
for pair in self.modal_pairs:
try:
cipher1 = english_chars.index(pair[0])
plain1 = english_chars.index("e")
cipher2 = english_chars.index(pair[1])
plain2 = english_chars.index("t")
a = (plain1 - plain2)*mod_inverse(
num=(cipher1 - cipher2),
mod=ENGLISH_LANG_LEN) % ENGLISH_LANG_LEN
b = (plain1 - a*cipher1) % ENGLISH_LANG_LEN
except ValueError:
print("FAILED")
continue
else:
yield Affine.Key(a, b)
# possible_keys.append(Affine.Key(a, b))
# return possible_keys
@staticmethod
def char_shift(char: str, key) -> str:
"""Shift a char using the affine key."""
return english_chars[
(english_chars.index(char.lower())*key.a + key.b)
% ENGLISH_LANG_LEN
]
def encipher(self, give_key=False) -> str:
"""Encrypt the given text."""
if self.auto:
possible_texts = list()
for key in self.prob_keys:
deciphered = "".join(
self.char_shift(char, key) if char.isalpha()
else char for char in self.text
)
possible_texts.append(
Affine.TextChiKey(
text=deciphered,
chi=english_1gram_chi(deciphered),
key=key
)
)
best = sorted(
possible_texts, key=lambda elem: elem.chi)[0]
enciphered = best.text
self.key = best.key
else:
enciphered = "".join(
self.char_shift(char, self.key) if char.isalpha()
else char for char in self.text
)
if give_key:
return TextKey(match(self.text, enciphered), self.key)
else:
return match(self.text, enciphered)
class Viginere:
ChiShift = collections.namedtuple("ChiShift", ['chi', 'shift'])
MAX_SEARCH = 100
def __init__(self, text: str, key: str=""):
self.text = text
self.key = key
self.auto = not bool(key)
@property
def prob_key_length(self) -> int:
text = letters(self.text).lower()
for possible_length in range(2, Viginere.MAX_SEARCH):
split_text = list(
"".join(text[offset::possible_length])
for offset in range(possible_length)
)
average_codex = sum(
codex(split) for split in split_text
) / len(split_text)
if average_codex > ENGLISH_LOWER_CODEX:
# print("Found one!")
return possible_length
else:
return 1
@property
def split_text(self):
text = letters(self.text).lower()
return (
"".join(text[offset::self.prob_key_length])
for offset in range(self.prob_key_length)
)
@property
def prob_key(self) -> str:
shifts = list()
for split in self.split_text:
split_shifts = list()
for possible_shift in range(ENGLISH_LANG_LEN):
shifted_text = Caesar(
split, shift=possible_shift, forced=True).encipher()
split_shifts.append(
Viginere.ChiShift(
english_1gram_chi(shifted_text),
possible_shift
)
)
split_shift = sorted(split_shifts)[0].shift
shifts.append(-1*split_shift % ENGLISH_LANG_LEN)
return "".join(english_chars[shift] for shift in shifts)
def encipher(self, give_key=False) -> str:
if self.auto:
self.key = self.prob_key
split_text = self.split_text
else:
text = letters(self.text).lower()
split_text = (
"".join(text[offset::len(self.key)])
for offset in range(len(self.key))
)
shifted_split = list()
for index, split in enumerate(split_text):
split = Caesar(
split,
shift=ENGLISH_LANG_LEN-english_chars.index(self.key[index]),
# Above: Complement of key for decryption
).encipher()
shifted_split.append(split)
enciphered = "".join(
"".join(chunk)
for chunk in itertools.zip_longest(*shifted_split, fillvalue="")
)
if give_key:
return TextKey(match(self.text, enciphered), self.key)
else:
return match(self.text, enciphered)
class AffineViginere:
def __init__(self, text: str, key: str="", switch: tuple=(1, 0)):
self.text = text
self.key = key
self.switch = Affine.Key(*switch)
self.auto = bool(sum(switch) < 2)
def encipher(self) -> str:
if self.auto:
possible_switches = (
(switch, 0) for switch in range(ENGLISH_LANG_LEN)
if math.gcd(switch, ENGLISH_LANG_LEN) == 1
)
for switch in possible_switches:
possible_text = Affine(self.text, switch=switch).encipher()
if Viginere(possible_text).prob_key_length != 1:
break
enciphered = Viginere(possible_text).encipher()
else:
aff_text = Affine(self.text, switch=self.switch).encipher()
enciphered = Viginere(aff_text, key=self.key).encipher()
return match(self.text, enciphered)
class Scytale:
TextFitLen = collections.namedtuple(
"TextFitnessLength", ['text', 'fitness', 'length'])
MAX_SEARCH = 10
def __init__(self, text: str, key: int=1, auto: bool=True, keep=[]):
self.text = text
self.key = key
self.auto = not bool(key > 1)
self.keep = keep
def encipher(self, give_key=False, pretty=False) -> str:
text = letters(self.text, keep=self.keep).lower()
if self.auto:
possible_texts = list()
for length in range(1, Scytale.MAX_SEARCH):
skip = round(len(text) / length)
possible_text = "".join(
text[i::skip]
for i in range(skip)
)
possible_texts.append(
Scytale.TextFitLen(
text=possible_text,
fitness=english_quadgram_fitness(possible_text),
length=length
)
)
best = sorted(
possible_texts,
key=lambda text_fit: text_fit.fitness,
reverse=True
)[0]
enciphered = best.text
self.key = best.length
else:
skip = round(len(text) / self.key)
enciphered = "".join(
text[i::skip]
for i in range(skip)
)
if pretty:
enciphered = match(self.text, enciphered)
if give_key:
return TextKey(enciphered, self.key)
else:
return enciphered
class ScytaleViginere:
MAX_SEARCH = 10
def __init__(self, text: str, length: int=1, key: str="", keep=[]):
self.text = text
self.length = length
self.key = key
self.auto = not bool(key)
self.keep = keep
def encipher(self):
text = letters(self.text, keep=self.keep).lower()
if self.auto:
for length in range(2, ScytaleViginere.MAX_SEARCH):
possible_text = Scytale(
text, key=length, keep=self.keep).encipher()
if Viginere(possible_text).prob_key_length != 1:
break
enciphered = Viginere(possible_text).encipher()
else:
enciphered = Scytale(
text,
key=self.length,
keep=self.keep
).encipher()
enciphered = Viginere(enciphered, key=self.key).encipher()
return match(self.text, enciphered)
class MonoSub:
KeyFit = collections.namedtuple('KeyFitness', ['key', 'fitness'])
CharSwap = collections.namedtuple('CharSwap', ['char', 'swap_char'])
MAX_SEARCH = 1000
def __init__(self, text: str, key=None, keyword=False, alternative=False):
self.text = text
self.key = key
self.auto = not bool(key)
self.alternative = alternative
if keyword:
self.key = self.keyword_to_key(key, self.alternative)
@staticmethod
def keyword_to_key(key: str, alt: bool) -> dict:
"""Converts a keyword into a substituiton dict."""
new_key = "".join(
collections.OrderedDict.fromkeys(letters(key).lower()))
if alt:
start = english_chars.index(new_key[-1])
else:
start = max(english_chars.index(char) for char in new_key)
characters = english_chars[start:] + english_chars[:start]
for char in characters:
if char not in new_key:
new_key += char
final_key = {
key_char: eng_char.upper()
for key_char, eng_char in zip(new_key, english_chars)
}
return final_key
@property
def prob_key(self) -> dict:
analysed = auto_freq_analyser(self.text)
for char in english_1gram_expected_dict:
if all(char not in char_freq.character for char_freq in analysed):
analysed.append(CharFreq(character=char, frequency=0))
current_key = {
observed.character: expected
for observed, expected in zip(
analysed,
english_1gram_expected_dict
)
}
return current_key
@staticmethod
def gen_neigbors_key(key):
for swap1, swap2 in itertools.combinations(range(ENGLISH_LANG_LEN), 2):
new_key = list(list(item) for item in key.items())
pair1, pair2 = new_key[swap1], new_key[swap2]
pair1[1], pair2[1] = pair2[1], pair1[1]
yield {char: swap_char for char, swap_char in new_key}
@property
def text_fitness(self):
def key_fitness(key):
return english_quadgram_fitness(
self.encipher(key=key)
)
return key_fitness
@property
def best_key(self) -> dict:
return hill_climbing(
initial_key=self.prob_key,
fitness=self.text_fitness,
neighbors=MonoSub.gen_neigbors_key
)
def encipher(self, key: dict={}, give_key=False) -> str:
if not key:
if self.key:
key = self.key
else:
key = self.best_key
enciphered = "".join(
key[char] if char in key
else char for char in self.text.lower()
)
# return TextKey(enciphered, key)
if give_key:
return TextKey(match(self.text, enciphered), key)
else:
return match(self.text, enciphered)
class DuoSub:
def __init__(self, text, key_square: list=[]):
self.text = text
if key_square:
self.key = self.create_substitution_dict(key_square)
self.auto = not bool(key_square)
@staticmethod
def duo_to_mono(text):
new_text = letters(text).lower()
split_text = list(
new_text[i:i + 2] for i in range(0, len(new_text), 2)
)
substitutions = {}
eng_index = 0
for bigram in split_text:
if bigram not in substitutions:
substitutions[bigram] = english_chars[eng_index]
eng_index += 1
# if eng_index == 24:
# break
return "".join(substitutions[bigram] for bigram in split_text)
@staticmethod
def create_substitution_dict(key):
substitutions = dict()
eng_index = 0
for row in key[0]:
for col in key[1]:
substitutions[row + col] = english_chars[eng_index].upper()
eng_index += 1
if eng_index == english_chars.index("j"): # Skip j
eng_index += 1
return substitutions
def encipher(self, give_key=False):
if self.auto:
new_text = self.duo_to_mono(self.text)
enciphered = MonoSub(new_text).encipher(give_key=give_key)
if give_key:
self.key = enciphered.key
enciphered = enciphered.text
else:
new_text = letters(self.text).lower()
split_text = (
new_text[i: i + 2] for i in range(0, len(new_text), 2)
)
enciphered = "".join(self.key[bigram] for bigram in split_text)
if give_key:
return TextKey(match(self.text, enciphered), self.key)
else:
return match(self.text, enciphered)
class MultiSub:
def __init__(self, text, size, keep=[]):
self.text = text
self.size = size
self.keep = keep
@staticmethod
def multi_to_mono(text, size, keep=[]):
new_text = letters(text, keep=keep)
print(new_text)
split_text = list(
new_text[i:i + size] for i in range(0, len(new_text), size)
)
print(split_text)
substitutions = {}
eng_index = 0
for ngram in split_text:
if ngram not in substitutions:
if eng_index == 26:
substitutions[ngram] = " "
else:
substitutions[ngram] = english_chars[eng_index]
eng_index += 1
return "".join(substitutions[ngram] for ngram in split_text)
def encipher(self):
best = MonoSub(
self.multi_to_mono(self.text, self.size, self.keep)
).encipher(give_key=True)
return TextKey(best.text, best.key)
class Straddle:
TextKeyCodex = collections.namedtuple(
'TextKeyCodex', ['text', 'key', 'codex'])
def __init__(self, text):
self.text = text
def convert_to_eng(self, blanks):
row_num = 0
final_ls = list()
for index, char in enumerate(self.text):
if row_num != 0:
row_num = 0
continue
int_c = int(char)
if int_c not in blanks:
final_ls.append(char)
else:
row_num = 1
final_ls.append(char + self.text[index + 1])
substitutions = {}
eng_index = 0
final_string = ""
for item in final_ls:
if item not in substitutions:
substitutions[item] = english_chars[eng_index]
eng_index += 1
final_string += substitutions[item]
return final_string
def encipher(self, give_key=False):
possible_keys = list()
for blanks in itertools.combinations(range(10), 2):
try:
possible_text = y.convert_to_eng(blanks)
except IndexError:
continue
else:
if (
ENGLISH_UPPER_CODEX > codex(possible_text)
and codex(possible_text) > ENGLISH_LOWER_CODEX
):
possible_keys.append(
Straddle.TextKeyCodex(
text=possible_text,
key=blanks,
codex=codex(possible_text)
)
)
continue
print(possible_keys)
best = sorted(
possible_keys,
key=lambda elem: elem.codex,
reverse=True
)[0]
enciphered = MonoSub(
best.text
).encipher()
if give_key:
return TextKey(enciphered, best.key)
else:
return enciphered
class AutoKey:
def __init__(self, text: str, size, key: str="", reset: int=None):
self.text = text
self.key = key
self.auto = not bool(key)
self.size = size
if reset:
self.reset = reset
@staticmethod
def char_shift(cipher_char, plain_or_key_char):
return english_chars[
(english_chars.index(
cipher_char
) - english_chars.index(
plain_or_key_char
)) % ENGLISH_LANG_LEN
]
@property
def text_fitness(self):
def key_fitness(key):
return english_quadgram_fitness(
self.encipher(key=key)
)
return key_fitness
@staticmethod
def gen_new_key(key):
choice = random.randrange(len(key))
new_letter = english_chars[random.randrange(26)]
new_key = list(key)
new_key[choice] = new_letter
return "".join(new_key)
@property
def best_key(self):
initial = "".join(
random.choice(english_chars)
for i in range(self.size)
)
return simulated_annealing(
initial_key=initial,
fitness=self.text_fitness,
new_key=AutoKey.gen_new_key,
initial_temp=30,
count=10000,
max_length=1000,
stale=5000,
stale_fitness=-20000,
threshold=-19000
)
def encipher(self, key="", give_key=False, pretty=False):
if not key:
if self.key:
key = self.key
else:
key = self.best_key
text = letters(self.text).lower()
if hasattr(self, "reset"):
split_text = list(
text[i:i + self.reset]
for i in range(0, len(text), self.reset)
)
else:
split_text = [text]
final_plain = ""
for split in split_text:
initial_plain = "".join(
self.char_shift(cipher_char, key_char)
for cipher_char, key_char
in zip(split, key)
)
start_index = len(initial_plain)
split = split[start_index:]
plain_index = 0
for char in split:
initial_plain += self.char_shift(
char, initial_plain[plain_index]
)
plain_index += 1
final_plain += initial_plain
enciphered = final_plain
if pretty:
enciphered = match(self.text, enciphered)
if give_key:
return TextKey(enciphered, key)
else:
return enciphered
class ColTrans:
MAX_SEARCH = 10
TextFitPerm = collections.namedtuple(
'TextFitnessPermutation',
['text', 'fitness', 'perm']
)
def __init__(self, text, key: tuple=(), guessed_length: int=1, keep=[]):
self.text = text
self.key = key
self.guessed_length = guessed_length
self.auto_length = guessed_length == 1
self.keep = keep
self.auto = not bool(key)
@staticmethod
def permute(block: str, key: tuple):
if len(block) > len(key):
return block
elif len(block) < len(key):
block = pad_to_length(block, len(key))
else:
pass
return "".join(
block[perm_index]
for perm_index in key
)
@property
def text_fitness(self):
def key_fitness(key):
return english_quadgram_fitness(self.encipher(key=key))
return key_fitness
@staticmethod
def swap_two_pos(key):
swap1, swap2 = tuple(random.choices(range(len(key)), k=2))
new_key = list(key)
new_key[swap1], new_key[swap2] = new_key[swap2], new_key[swap1]
return tuple(new_key)
@staticmethod
def segment_slide(key):
seg_1, seg_2 = random.sample(range(len(key)), k=2)
if seg_1 > seg_2:
seg_1, seg_2 = seg_2, seg_1
segment = key[seg_1:seg_2]
key_no_seg = key[:seg_1] + key[seg_2:]
shift = random.randrange(len(segment))
return key_no_seg[:shift] + segment + key_no_seg[shift:]
@staticmethod
def gen_new_key(key):
choice = random.randrange(2)
transformations = {
0: ColTrans.swap_two_pos,
1: ColTrans.segment_slide
}