-
Notifications
You must be signed in to change notification settings - Fork 0
/
vigenere.py
99 lines (56 loc) · 2.03 KB
/
vigenere.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
import getpass
import itertools
#builds standard alphabet
alphabet = [chr(i) for i in range(ord('a'), ord('z')+1)]
#user selects action
def main():
while True:
action = raw_input('\nFor ENCRYPTION enter \'E\'\nFor DECRYPTION enter \'D\'\nTo QUIT enter \'Q\'\n ').lower()
if action == 'e':
encrypt()
elif action == 'd':
decrypt()
elif action == 'q':
quit()
else:
print('\nPLEASE ENTER \'E\' or \'D\' or \'Q\'!')
#builds new alphabet starting from character following (x)
def new_alpha(x):
a = [chr(ord('a') + ((i-ord('a'))+x+1) % 26) for i in range(ord('a'), ord('z')+1)]
return a
def encrypt():
key = getpass.getpass('Please enter a key: ').lower()
key = list(key.replace(' ',''))
key_indices = [alphabet.index(l) for l in key]
alphas = [new_alpha(x) for x in key_indices]
msg = list((raw_input('Please enter a message to encrypt:\n')).lower())
msg_indices = [alphabet.index(m) if m in alphabet else m for m in msg]
c = itertools.cycle(alphas)
translation = []
for v in msg_indices:
try:
v = int(v)
translation.append(next(c)[v])
except ValueError:
translation.append(v)
new_msg = ''.join(x if x in alphabet else x for x in translation).upper()
print '\n%s\n' % new_msg
def decrypt():
key = getpass.getpass('Please enter a key: ').lower()
key = list(key.replace(' ',''))
matches = [alphabet.index(l) for l in key]
alphas = [new_alpha(x) for x in matches]
msg = list((raw_input('Please enter a message to decrypt:\n')).lower())
c = itertools.cycle(alphas)
msg_indices = [next(c).index(i) if i in alphabet else i for i in msg]
translation = []
for t in msg_indices:
try:
t = int(t)
translation.append(alphabet[t])
except ValueError:
translation.append(t)
orig_msg = ''.join(x for x in translation).upper()
print '\n%s\n' % orig_msg
if __name__ == '__main__':
main()