-
Notifications
You must be signed in to change notification settings - Fork 0
/
hylian.py
338 lines (288 loc) · 11.3 KB
/
hylian.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
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
import re
hylian = " ABCDEFGHIJKLMNOPRSTUVWXYZ."
def formessage(message, suffix=" ", prefix=""):
message = message.upper()
message = re.sub("[,:;]", ".", message)
message = re.sub("Q", "KW", message)
message = re.sub("0", prefix + "ZERO" + suffix, message)
message = re.sub("1", prefix + "ONE" + suffix, message)
message = re.sub("2", prefix + "TWO" + suffix, message)
message = re.sub("3", prefix + "THREE" + suffix, message)
message = re.sub("4", prefix + "FOUR" + suffix, message)
message = re.sub("5", prefix + "FIVE" + suffix, message)
message = re.sub("6", prefix + "SIX" + suffix, message)
message = re.sub("7", prefix + "SEVEN" + suffix, message)
message = re.sub("8", prefix + "EIGHT" + suffix, message)
message = re.sub("9", prefix + "NINE" + suffix, message)
return re.sub("[^A-PR-Z. ]", "", message)
def en(integer, block_len): # encode integer into text
assert isinstance(integer, int), "Error: message not integer"
assert 0 <= integer < 27 ** block_len, "Error: number out of range"
if integer == 0: return " " * block_len
result=""
while integer != 0:
integer, char = divmod(integer, 27); result += hylian[char]
return result.ljust(block_len, " ")
def de(string, block_len): # decode text into integer
assert isinstance(string, str), "Error: message not string"
assert len(string) <= block_len, "Error: string too long"
assert bool(re.fullmatch("[A-PR-Z. ]{1,%d}" % block_len, string))
result, string = 0, string[::-1].lstrip(" ")
for char in string:
result *= 27; result += hylian.index(char)
assert result < 27 ** block_len, "Error: number error"
return result
def egcd(a, b): # extended greatest common divisor
if a == 0: return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m): # multiplicative modular inverse
g, x, y = egcd(a, m)
if g != 1: raise Exception('modular inverse does not exist')
else: return x % m
def affine_check(block_len, add, mult):
assert isinstance(block_len, int) and block_len > 0
max = 27 ** block_len
assert isinstance(add, int) and 0 <= add < max
assert isinstance(mult, int) and 0 < mult < max and egcd(mult, 27)[0] == 1
def affine_en(integer, block_len, add, mult): # encrypts integer using affine
assert isinstance(integer, int)
affine_check(block_len, add, mult)
return (integer * mult + add) % (27 ** block_len)
def affine_de(integer, block_len, add, mult): # decrypts integer using affine
assert isinstance(integer, int)
affine_check(block_len, add, mult)
result = (integer - add) % (27 ** block_len)
return result * modinv(mult, 27 ** block_len) % (27 ** block_len)
################################################################################
# string = sentence in hylian including space and periods
# block_len = numbe rof characters in a block of code
# add, mult = additive and multiplicative key of cipher
def check(block_len, add, mult):
assert isinstance(block_len, int) and block_len > 0
max = 27 ** block_len
assert isinstance(add, int) and 0 <= add < max
assert isinstance(mult, int) and 1 <= mult < max and egcd(mult, 27)[0] == 1
def encrypt(string, block_len, add, mult): # encrypts hylian
assert isinstance(string, str)
check(block_len, add, mult)
chop = [string[i:i+block_len] for i in range(0, len(string), block_len)]
result = ""
for item in chop:
part = en(affine_en(de(item, block_len),block_len, add, mult), block_len)
result += part
return result
def decrypt(string, block_len, add, mult): # decrypts hylian
assert isinstance(string, str)
check(block_len, add, mult)
chop = [string[i:i+block_len] for i in range(0, len(string), block_len)]
assert len(chop[len(chop)-1]) == block_len
result = ""
for item in chop:
part = en(affine_de(de(item, block_len),block_len, add, mult), block_len)
result += part
return result.rstrip(" ")
################################################################################
from random import randint
def hy_gen(block_len): # create key for single hylian cipher
add = randint(0, 27 ** block_len - 1)
mult_1 = randint(0, 27 ** (block_len - 1) - 1) * 27
mult_2 = [1,2,4,5,7,8,10,11,13,14,16,17,19,20,22,23,25,26][randint(0, 17)]
return [block_len, add, mult_1 + mult_2]
def hylian_gen(x): # creates large keys for triple hylain cipher
assert isinstance(x, int) and 1 <= x <= 5
hyrule, e = [2] * x, 2
while e != 1:
block_pool, hyrule = list(range(9, 28)), []
for i in range(0, x):
hyrule.append(block_pool.pop(randint(0,len(block_pool)-1)))
e = hyrule[0]
for i in range(0, x):
e = egcd(e, hyrule[i])[0]
for i in range(0, 3): hyrule[i] = hy_gen(hyrule[i])
return hyrule
def hylian_gen_simple(x): # creates small keys for triple hylain cipher
assert isinstance(x, int) and 1 <= x <= 5
hyrule, e = [2] * x, 2
while e != 1:
block_pool, hyrule = list(range(3, 10)), []
for i in range(0, x):
hyrule.append(block_pool.pop(randint(0,len(block_pool)-1)))
e = hyrule[0]
for i in range(0, x):
e = egcd(e, hyrule[i])[0]
for i in range(0, 3): hyrule[i] = hy_gen(hyrule[i])
return hyrule
################################################################################
def multi_encrypt(string, array):
assert isinstance(string, str)
assert isinstance(array, list)
for i in array:
assert isinstance(i[0], int)
assert isinstance(i[1], int)
assert isinstance(i[2], int)
for i in range(0, len(array)):
string = encrypt(string, array[i][0], array[i][1], array[i][2])
return string
def multi_decrypt(string, array):
assert isinstance(string, str)
assert isinstance(array, list)
for i in array:
assert isinstance(i[0], int)
assert isinstance(i[1], int)
assert isinstance(i[2], int)
for i in range(len(array)-1, -1, -1):
string = decrypt(string, array[i][0], array[i][1], array[i][2])
return string
################################################################################
def multiline():
print("Enter as many lines of text as needed.")
print("When done, enter '>' on a line by itself.")
buffer = []
while True:
line = input()
if line == ">": break
buffer.append(line)
return "\n".join(buffer)
################################################################################
first_line = "------BEGIN GGR MESSAGE------"
second_line = "Version: DDMoe v.1.4.88 (Heil.OS)"
last_line = "------END GGR MESSGAE------"
################################################################################
def rect_en(message, n=1):
assert n in [1, 2], "n is not one or two"
x = 82 - n
return "\n".join([message[i:i+x] for i in range(0, len(message), x)] + [""])
def rectangle_en(message=''):
if message == '': print('type message with no newline'); message = input()
message_clean = rect.en(message)
return first_line + "\n" + second_line + "\n" + \
message_clean + last_line + "\n"
def rect_de(message):
return "".join(message.split("\n"))
def rectangle_de(message=''):
if message == '': message = multiline()
message_pure = message.rstrip("\n").rstrip(last_line) \
.lstrip(first_line + "\n" + second_line + "\n")
return rect_de(message_pure)
################################################################################
def tri_en(message, n=1, l=' ', r=' '):
assert n in [1, 2], "n is not one or two"
counter, result = n, ""
while message != "":
assert counter < 82 - n
printer, message = message[0:counter], message[counter:]
s = (81 - counter) // 2
result += (s * l + printer.ljust(counter, " ") + s * r + "\n")
counter += 2
return result
def triangle_en(message=''):
if message == '': print('type message with no newline'); message = input()
message_clean = tri_en(message)
return first_line + "\n" + second_line + "\n" + \
message_clean + last_line + "\n"
def tri_de(message, n=1):
assert n in [1, 2], "n is not one or two"
lister = message.split("\n")
for i in range(0, len(lister)):
s = (41 - n) - i
lister[i] = lister[i][s:-s]
return "".join(lister)
def triangle_de(message=''):
if message == '': message = multiline()
message_pure = message.rstrip("\n").rstrip(last_line) \
.lstrip(first_line + "\n" + second_line + "\n")
return tri_de(message_pure)
################################################################################
def formats(message="", code="en", shape="tri", wrap=True):
assert isinstance(message, str), "Message is not string"
assert code in ["en", "de"], "Coding is not 'en' or 'de'"
assert shape in ["tri", "rect"], "Shape is not 'tri' or 'rect'"
assert isinstance(wrap, bool), "Wrapping is not True or False"
if code == "en":
if shape == "tri":
if wrap == True: return triangle_en(message)
elif wrap == False: return tri_en(message)
elif shape == "rect":
if wrap == True: return rectangle_en(message)
elif wrap == False: return rect_en(message)
elif code == "de":
if shape == "tri":
if wrap == True: return triangle_de(message)
elif wrap == False: return tri_de(message)
elif shape == "rect":
if wrap == True: return rectangle_de(message)
elif wrap == False: return rect_de(message)
################################################################################
def bacon(message="", x=3, shape="tri", wrap=True):
assert isinstance(message, str), "Message is not string"
assert shape in ["tri", "rect"], "Shape is not 'tri' or 'rect'"
assert isinstance(wrap, bool), "Wrapping is not True or False"
password = hylian_gen(x)
message = formats(multi_encrypt(formessage(message), password), "en", shape, wrap))
print(password)
print(message)
def daggot(message="", password=[], shape="tri", wrap=True):
assert isinstance(message, str), "Message is not string"
assert shape in ["tri", "rect"], "Shape is not 'tri' or 'rect'"
assert isinstance(wrap, bool), "Wrapping is not True or False"
message = multi_decrypt(formats(message, "de", shape, wrap), password)
print(message)
################################################################################
from random import shuffle
class Chaocipher:
alphabet = " ABCDEFGHIJKLMNOPRSTUVWXYZ.";
def __init__(self, left, right):
self.orig_left = left
self.orig_right = right
self.reset()
self.check()
def reset(self):
self.left = list(self.orig_left.upper())
self.right = list(self.orig_right.upper())
def check(self):
left = self.left
right = self.right
if len(left) != 27:
raise Exception("Left side must contain 27 characters");
if len(right) != 27:
raise Exception("Left side must contain 27 characters");
for i in range(27):
char = self.alphabet[i]
if left.count(char) != 1:
raise Exception("Left side missing '%s'" % char)
if right.count(char) != 1:
raise Exception("Right side missing '%s'" % char)
def permute(self, idx):
for cnt2 in range(idx):
self.left.append(self.left.pop(0))
char = self.left.pop(1)
self.left.insert(13, char)
for cnt2 in range(idx+1):
self.right.append(self.right.pop(0))
char = self.right.pop(2)
self.right.insert(13, char)
def crypt(self, text, mode):
src = list(text)
dest = []
for cnt in range(len(src)):
char = src[cnt]
if self.alphabet.find(char) < 0:
print("Ignoring character '%s'" % char)
continue
if mode == "de":
idx = self.left.index(char)
dest.append(self.right[idx])
elif mode == "en":
idx = self.right.index(char)
dest.append(self.left[idx])
if cnt + 1 == len(src):
break
self.permute(idx)
return ''.join(dest)
def generate():
left, right = list(alphabet), list(alphabet)
shuffle(left); shuffle(right)
print(["".join(left), "".join(right)])
return Chaocipher("".join(left), "".join(right))