-
Notifications
You must be signed in to change notification settings - Fork 0
/
VigenereCipher3.py
286 lines (228 loc) · 10.7 KB
/
VigenereCipher3.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
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
"""Cipher.py:"""
from __future__ import annotations
__author__ = "Jacob Taylor Casasdy"
__email__ = "[email protected]"
from unittest import TestCase, TestResult, TestSuite, result
from abc import ABC, abstractmethod
from os.path import join, dirname, isfile, sep
from os import listdir
from json import loads, load
from argparse import ArgumentParser
from random import shuffle
from typing import Union, Dict, Any
LOCK_AND_KEY_DIRECTORY = join(dirname(__file__), "..", "lock_and_key")
RESOURCE_DIRECTORY = join(dirname(__file__), "..", "resources")
CIPHER_RESOURCE = join(LOCK_AND_KEY_DIRECTORY, "cipher.json")
assert isfile(CIPHER_RESOURCE), "CIPHER resource file unable to be found."
DATA_KEY_BASE = "0123456789AaBbCcDdEeFfGgHhJjKkLlMmNnOoPpQqRrSsTtUuVvXxYyZz \n{}[]()<>,.!@#$%^&*_+-=/\\\'\""
FILE_NAME_KEY_BASE = "0123456789AaBbCcDdEeFfGgHhJjKkLlMmNnOoPpQqRrSsTtUuVvXxYyZz "
class Cipher(ABC):
"""[summary]"""
@abstractmethod
def encode(self, message: str) -> str:
"""[summary]
Args:
message (str): [description]
Returns:
str: [description]"""
pass
@abstractmethod
def decode(self, message: str) -> str:
"""[summary]
Args:
message (str): [description]
Returns:
str: [description]"""
pass
@staticmethod
def generate_random_key(key_base: str) -> str:
"""[summary]
Args:
key_base (str): [description]
Returns:
str: [description]"""
key_list = [char for char in key_base]
shuffle(key_list)
return "".join(key_list)
def decode_file(self, file_path: str) -> None:
"""[summary]
Args:
file_path (str): [description]"""
with open(file_path, "r") as file:
file_data = file.read()
file_name = file_path.split(sep=sep)[-1]
decoded_data = self.decode(message=file_data)
decoded_file_name = self.decode(message=file_name)
decoded_file_path = join(RESOURCE_DIRECTORY, decoded_file_name)
with open(decoded_file_path, "w+") as encoded_file:
encoded_file.write(decoded_data)
def load_encoded_file(self, file_directory: str, file_name) -> str:
"""[summary]
Args:
file_directory (str): [description]
file_name ([type]): [description]
Returns:
str: [description]"""
encoded_key_file_name = self.encode(file_name)
with open(join(file_directory, encoded_key_file_name),
"r") as encoded_key_file:
encoded_key_file_data = encoded_key_file.read()
return loads(self.decode(encoded_key_file_data))
class VigenereCipher(Cipher):
"""First described by Italian Cryptologist Giovan Battista Bellaso in 1553"""
def __init__(self, key: Union[str, None] = None, alphabet: Union[str, None] = None):
"""[summary]
Args:
key (str): [description]
alphabet (str): [description]"""
self.key = key
self.alphabet = alphabet
def encode(self, message: str) -> str:
"""[summary]
Args:
message (str): [description]
Returns:
str: [description]"""
result = ""
stretched_key = VigenereCipher.get_stretched_key(key=self.key, message_length=len(message))
for character_index, character in enumerate(message):
if self.alphabet.find(character) != -1:
result += VigenereCipher.shift_char(alphabet=self.alphabet, character=character,
shift_char=stretched_key[character_index])
else:
result += message[character_index]
return result
def decode(self, message: str) -> str:
"""[summary]
Args:
message (str): [description]
Returns:
str: [description]"""
result = ""
stretched_key = VigenereCipher.get_stretched_key(key=self.key, message_length=len(message))
for character_index, character in enumerate(message):
if self.alphabet.find(character) != -1:
result += VigenereCipher.deshift_char(alphabet=self.alphabet,
character=character,
shift_char=stretched_key[character_index])
else:
result += character
return result
@staticmethod
def shift_char(alphabet: str, character: str, shift_char: str) -> str:
"""[summary]
Args:
alphabet (str): [description]
character (str): [description]
shift_char (str): [description]
Returns:
str: [description]"""
shift = alphabet.find(shift_char)
shifted_value = alphabet.find(character) + shift
if shifted_value >= len(alphabet):
shifted_value -= len(alphabet)
return alphabet[shifted_value]
@staticmethod
def deshift_char(alphabet: str, character: str, shift_char: str) -> str:
"""[summary]
Args:
alphabet (str): [description]
character (str): [description]
shift_char (str): [description]
Returns:
str: [description]"""
shift = alphabet.find(shift_char)
shifted_value = alphabet.find(character) - shift
if shifted_value < 0:
shifted_value += len(alphabet)
return alphabet[shifted_value]
@staticmethod
def get_stretched_key(key: str, message_length: int) -> str:
"""[summary]
Args:
message_length (int): [description]
Returns:
str: [description]"""
stretched_key: str = ""
while len(stretched_key) <= message_length:
stretched_key += key
return stretched_key[:message_length]
class Test_VigenereCipher(TestCase):
"""[summary]"""
def test_encode_and_decode(self):
test_message = "Hello World."
test_cipher = VigenereCipher(key=Cipher.generate_random_key(key_base=DATA_KEY_BASE), alphabet=Cipher.generate_random_key(key_base=DATA_KEY_BASE))
encoded_message = test_cipher.encode(message=test_message)
decoded_message = test_cipher.decode(message=encoded_message)
assert test_message == decoded_message
def load_json_resource(file_name_cipher: VigenereCipher, data_cipher: VigenereCipher, resource_file_name: str) -> Dict[str, Any]:
"""[summary]
Args:
resource_file_name (str): [description]
Returns:
Dict[str, Any]: [description]"""
encoded_resource_file_name = file_name_cipher.encode(resource_file_name)
with open(join(RESOURCE_DIRECTORY, encoded_resource_file_name), "r") as encoded_resource_file:
encoded_resource_data = encoded_resource_file.read()
decoded_resource_data = data_cipher.decode(encoded_resource_data)
return loads(decoded_resource_data)
def initialize_lock_and_key_ciphers() -> Dict[str, VigenereCipher]:
"""[summary]
Returns:
Dict[VigenereCipher]: [description]"""
ciphers = {}
with open(CIPHER_RESOURCE, "r") as cipher_resource_file:
cipher_data = load(cipher_resource_file)['vigenere']
for cipher_key_name, cipher_keys in cipher_data.items():
ciphers[cipher_key_name] = VigenereCipher(key=cipher_keys['key'], alphabet=cipher_keys['alphabet'])
return ciphers
if __name__ == "__main__":
argument_parser = ArgumentParser()
argument_parser.add_argument("-t", "--test", type=bool, required=False, default=False,
help="If true, performs unit tests for the cipher")
argument_parser.add_argument("-ef", "--encodeFile", type=str, required=False, default=None, action="store")
argument_parser.add_argument("-df", "--decodeFile", type=str, required=False, default=None, action="store")
argument_parser.add_argument("-er", "--encodeResources", type=bool, required=False, default=False, action="store")
argument_parser.add_argument("-dr", "--decodeResources", type=bool, required=False, default=False, action="store")
argument_parser.add_argument("-gk", "--generateKey", type=str, required=False, default=None, action="store")
argument_parser.add_argument("-gdk", "--generateDataKey", type=bool, required=False, default=False, action="store")
argument_parser.add_argument("-gfk", "--generateFileKey", type=bool, required=False, default=False, action="store")
arguments = argument_parser.parse_args()
if arguments.test:
print("Running unittests...")
test_result = TestResult()
unit_test_suite = TestSuite()
unit_test_suite.addTests(tests= [Test_VigenereCipher.test_encode_and_decode])
unit_test_suite.run(test_result)
print("Unittest error count: ", len(test_result.errors))
elif arguments.encodeFile is not None:
pass
elif arguments.decodeFile is not None:
pass
elif arguments.encodeResources:
files_to_encode = [file for file in listdir(RESOURCE_DIRECTORY) if isfile(join(RESOURCE_DIRECTORY, file)) and ".json" or ".csv" in file]
ciphers = initialize_lock_and_key_ciphers()
for file_name in files_to_encode:
encoded_file_name = ciphers['file_name'].encode(file_name)
with open(join(RESOURCE_DIRECTORY, file_name), "r") as decoded_file:
encoded_file_data = ciphers['data'].encode(decoded_file.read())
with open(join(RESOURCE_DIRECTORY, encoded_file_name), "w+") as encoded_file:
encoded_file.write(encoded_file_data)
elif arguments.decodeResources:
files_to_decode = [file for file in listdir(RESOURCE_DIRECTORY) if isfile(join(RESOURCE_DIRECTORY, file)) and ".json" or ".csv" not in file]
ciphers = initialize_lock_and_key_ciphers()
for file_name in files_to_decode:
encoded_file_name = ciphers['file_name'].decode(file_name)
with open(join(RESOURCE_DIRECTORY, file_name), "r") as encoded_file:
decoded_file_data = ciphers['data'].decode(encoded_file.read())
with open(join(RESOURCE_DIRECTORY, encoded_file_name), "w+") as decoded_file:
decoded_file.write(decoded_file_data)
elif arguments.generateKey is not None:
generated_key = Cipher.generate_random_key(key_base=arguments.generateKey)
print("generated_key: ", repr(generated_key))
elif arguments.generateDataKey:
generated_key = Cipher.generate_random_key(key_base=DATA_KEY_BASE)
print("generated data key: ", repr(generated_key))
elif arguments.generateFileKey:
generated_key = Cipher.generate_random_key(key_base=FILE_NAME_KEY_BASE)
print("generated file key: ", repr(generated_key))