/
ciphers.py
232 lines (189 loc) · 8.33 KB
/
ciphers.py
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
class Cipher:
def __init__(self, name) -> None:
self.name = name
def encode(self, data: bytes, key: str | None = None) -> str:
return data.decode("utf-8")
def decode(self, string: str, key: str | None = None) -> bytes:
return string.encode("utf-8")
class TextCipher(Cipher):
def __init__(self) -> None:
super().__init__("Text")
def encode(self, data: bytes, key: str | None = None) -> str:
return data.decode("utf-8")
def decode(self, string: str, key: str | None = None) -> bytes:
return string.encode("utf-8")
class HexAsciiCipher(Cipher):
def __init__(self) -> None:
super().__init__("Hex")
def encode(self, data: bytes, key: str | None = None) -> str:
string = data.decode("utf-8")
out = " ".join([str(hex(ord(c))[2:]) for c in string])
return out
def decode(self, string: str, key: str | None = None) -> bytes:
string = string.replace("0x", "")
if not " " in string and len(string) % 2 != 0:
return "No spaces in string and string of odd length".encode("utf-8")
char_vals = string.split(" ") if " " in string else [string[i:i+2] for i in range(0, len(string), 2)]
try:
chars = [chr(int(h, 16)) for h in char_vals if h != ""]
except ValueError:
return "Please use valid hexadecimal values".encode("utf-8")
return ("".join(chars)).encode("utf-8")
class NumbersCipher(Cipher):
def __init__(self) -> None:
super().__init__("Numbers")
def encode(self, data: bytes, key: str | None = None) -> str:
string = data.decode("utf-8")
out = " ".join([str(ord(c) % 32) for c in string if c.isalpha()]) # todo: auto split with even length
return out
def decode(self, string: str, key: str | None = None) -> bytes:
if not " " in string and len(string) % 2 != 0:
return "No spaces in string and string of odd length".encode("utf-8")
number_strings = string.split() if " " in string else [string[i:i+2] for i in range(0, len(string), 2)]
try:
out = "".join([chr(int(n) % 32 + 96) for n in number_strings])
except ValueError:
out = ""
return out.encode("utf-8")
class CaesarCipher(Cipher):
def __init__(self) -> None:
super().__init__("Caesar")
def shift_char(self, c, shift):
if not c.isalpha():
return c
n = ord(c) % 32
sn = (n + shift - 1 + 26) % 26 + 1 # +26 to deal with negative keys, removed by remainder op again
return chr(sn + 96)
def encode(self, data: bytes, key: str | None = "all") -> str | list[str]:
if key is None or not key.isnumeric():
return [str(self.encode(data, key=str(shift))) for shift in range(0, 26)] # the str() conversion converts str->str and is only necessary to comfort the type checker
#return [f"{shift}: {self.encode(data, key=str(shift))}" for shift in range(0, 26)]
else:
shift = int(key) * (-1) + 26 if key.isnumeric() else 0
string = data.decode("utf-8")
#numbers = [ord(c) % 32 for c in string if c.isalpha()]
#shifted_numbers = [(n + shift - 1 + 26) % 26 + 1 for n in numbers]
#out = "".join([chr(n + 96) for n in shifted_numbers])
out = "".join([self.shift_char(c, shift) for c in string])
return out
def decode(self, string: str, key: str | None = "all") -> bytes | list[bytes]:
if key is None or not key.isnumeric():
return [str(self.encode(string.encode("utf-8"), key=str(shift * (-1) + 26))).encode("utf-8") for shift in range(0, 26)]
#return [f"{shift}: {self.encode(string.encode("utf-8"), key=str(shift * (-1) + 26))}".encode("utf-8") for shift in range(0, 26)]
else:
return str(self.encode(string.encode("utf-8"), str(int(key) * (-1) + 26))).encode("utf-8")
class TapCodeCipher(Cipher):
def __init__(self) -> None:
super().__init__("Tap")
self.tap_by_char = {
'a': "11", 'b': "12", 'c': "13", 'd': "14", 'e': "15",
'f': "21", 'g': "22", 'h': "23", 'i': "24", 'j': "25",
'l': "31", 'm': "32", 'n': "33", 'o': "34", 'p': "35",
'q': "41", 'r': "42", 's': "43", 't': "44", 'u': "45",
'v': "51", 'w': "52", 'x': "53", 'y': "54", 'z': "55",
'k': "13"
}
self.char_by_tap = { self.tap_by_char[k]: k for k in self.tap_by_char.keys() }
def encode(self, data: bytes, key: str | None = None) -> str:
string = data.decode("utf-8")
out = " ".join([(self.tap_by_char[c] if c in self.tap_by_char else "??") for c in string.lower()])
return out
def decode(self, string: str, key: str | None = None) -> bytes:
if not " " in string and len(string) % 2 != 0:
return "No spaces in string and string of odd length".encode("utf-8")
pairs = string.split(" ") if " " in string else [string[i:i+2] for i in range(0, len(string), 2)]
out = "".join([(self.char_by_tap[tap] if tap in self.char_by_tap else "?") for tap in pairs])
return out.encode("utf-8")
class MorseCodeCipher(Cipher):
def __init__(self) -> None:
super().__init__("Morse")
self.morse_by_char = {
"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": "--..",
"1": ".----",
"2": "..---",
"3": "...--",
"4": "....-",
"5": ".....",
"6": "-....",
"7": "--...",
"8": "---..",
"9": "----.",
"0": "-----"
}
self.char_by_morse = { self.morse_by_char[k]: k for k in self.morse_by_char.keys() }
def encode(self, data: bytes, key: str | None = None) -> str:
string = data.decode("utf-8")
out = " ".join([(self.morse_by_char[c] if c in self.morse_by_char else "???") for c in string.lower()])
return out
def decode(self, string: str, key: str | None = None) -> bytes:
symbols = string.split(" ")
out = "".join([(self.char_by_morse[symbol] if symbol in self.char_by_morse else "?") for symbol in symbols])
return out.encode("utf-8")
class SMSMultiTapCipher(Cipher):
def __init__(self) -> None:
super().__init__("SMS")
self.mt_by_char = {
"a": "2",
"b": "22",
"c": "222",
"d": "3",
"e": "33",
"f": "333",
"g": "4",
"h": "44",
"i": "444",
"j": "5",
"k": "55",
"l": "555",
"m": "6",
"n": "66",
"o": "666",
"p": "7",
"q": "77",
"r": "777",
"s": "7777",
"t": "8",
"u": "88",
"v": "888",
"w": "9",
"x": "99",
"y": "999",
"z": "9999",
" ": "0"
}
self.char_by_mt = { self.mt_by_char[k]: k for k in self.mt_by_char.keys() }
def encode(self, data: bytes, key: str | None = None) -> str:
string = data.decode("utf-8")
out = " ".join([(self.mt_by_char[c] if c in self.mt_by_char else "???") for c in string.lower()])
return out
def decode(self, string: str, key: str | None = None) -> bytes:
symbols = string.split(" ")
out = "".join([(self.char_by_mt[symbol] if symbol in self.char_by_mt else "?") for symbol in symbols])
return out.encode("utf-8")
all_ciphers = [TextCipher(), NumbersCipher(), CaesarCipher(), MorseCodeCipher(), TapCodeCipher(), SMSMultiTapCipher(), HexAsciiCipher()]
analysis_ciphers = [NumbersCipher(), CaesarCipher(), MorseCodeCipher(), TapCodeCipher(), SMSMultiTapCipher(), HexAsciiCipher()]