1
|
|
|
from random import random |
2
|
|
|
from math import floor |
3
|
|
|
|
4
|
|
|
from st2actions.runners.pythonrunner import Action |
5
|
|
|
|
6
|
|
|
__all__ = [ |
7
|
|
|
'SubSolver' |
8
|
|
|
] |
9
|
|
|
|
10
|
|
|
ALPHABET = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
def _gen_cipher_mapping(): |
14
|
|
|
cipher = [] |
15
|
|
|
alphabet = list(ALPHABET) |
16
|
|
|
|
17
|
|
|
for letter in ALPHABET: |
18
|
|
|
random_letter = int(floor(random() * len(alphabet))) |
19
|
|
|
mapping = (letter, alphabet.pop(random_letter)) |
20
|
|
|
|
21
|
|
|
cipher.append(mapping) |
22
|
|
|
|
23
|
|
|
return cipher |
24
|
|
|
|
25
|
|
|
|
26
|
|
|
def _get_cipher_mapping(cipher): |
27
|
|
|
cipher_map = [] |
28
|
|
|
alphabet = list(ALPHABET) |
29
|
|
|
|
30
|
|
|
for _ in range(len(ALPHABET)): |
31
|
|
|
mapping = (alphabet.pop(0), cipher.pop(0)) |
32
|
|
|
|
33
|
|
|
cipher_map.append(mapping) |
34
|
|
|
|
35
|
|
|
return cipher_map |
36
|
|
|
|
37
|
|
|
|
38
|
|
|
def _get_cipher(cipher): |
39
|
|
|
cipher_text = [] |
40
|
|
|
|
41
|
|
|
for _, mapping in cipher: |
42
|
|
|
cipher_text.append(mapping) |
43
|
|
|
|
44
|
|
|
return ''.join(cipher_text) |
45
|
|
|
|
46
|
|
|
|
47
|
|
|
def _encrypt_letter(letter, cipher): |
48
|
|
|
if letter == ' ': |
49
|
|
|
return ' ' |
50
|
|
|
|
51
|
|
|
for plain_text, cipher_text in cipher: |
52
|
|
|
if letter == plain_text: |
53
|
|
|
return cipher_text |
54
|
|
|
|
55
|
|
|
|
56
|
|
|
def _decrypt_letter(letter, cipher): |
57
|
|
|
if letter == ' ': |
58
|
|
|
return ' ' |
59
|
|
|
|
60
|
|
|
for plain_text, cipher_text in cipher: |
61
|
|
|
if letter == cipher_text: |
62
|
|
|
return plain_text |
63
|
|
|
|
64
|
|
|
|
65
|
|
|
def _encrypt_text(text, cipher): |
66
|
|
|
encrypted_text = [] |
67
|
|
|
text_list = list(text) |
68
|
|
|
|
69
|
|
|
for letter in text_list: |
70
|
|
|
encrypted_text.append(_encrypt_letter(letter, cipher)) |
71
|
|
|
|
72
|
|
|
return ''.join(encrypted_text) |
73
|
|
|
|
74
|
|
|
|
75
|
|
|
def _decrypt_text(text, cipher): |
76
|
|
|
decrypted_text = [] |
77
|
|
|
text_list = list(text) |
78
|
|
|
|
79
|
|
|
for letter in text_list: |
80
|
|
|
decrypted_text.append(_decrypt_letter(letter, cipher)) |
81
|
|
|
|
82
|
|
|
return ''.join(decrypted_text) |
83
|
|
|
|
84
|
|
|
|
85
|
|
|
class SubSolver(Action): |
86
|
|
|
def run(self, encode, message, cipher=None): |
87
|
|
|
if encode: |
88
|
|
|
cipher_map = _gen_cipher_mapping() |
89
|
|
|
cipher = _get_cipher(cipher_map) |
90
|
|
|
cipher_text = _encrypt_text(message, cipher_map) |
91
|
|
|
|
92
|
|
|
result = { |
93
|
|
|
'cipher_text': cipher_text, |
94
|
|
|
'cipher': cipher |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
return result |
98
|
|
|
|
99
|
|
|
else: |
100
|
|
|
cipher_list = list(cipher) |
101
|
|
|
|
102
|
|
|
cipher_map = _get_cipher_mapping(cipher_list) |
103
|
|
|
result = { |
104
|
|
|
'message': _decrypt_text(message, cipher_map) |
105
|
|
|
} |
106
|
|
|
|
107
|
|
|
return result |
108
|
|
|
|