-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6.caesar.py
63 lines (46 loc) · 1.13 KB
/
6.caesar.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
ENC = 0
DEC = 1
def makeDisk(key):
keytable = map(lambda x: (chr(x+65), x), range(26))
key2index = {}
for t in keytable:
alphabet, index = t[0], t[1]
key2index[alphabet] = index
if key in key2index:
k = key2index[key]
else:
return None, None
enc_disk = {}
dec_disk = {}
for i in range(26):
enc_i = (i+k)%26
enc_ascii = enc_i + 65
enc_disk[chr(i+65)] = chr(enc_ascii)
dec_disk[chr(enc_ascii)] = chr(i+65)
return enc_disk, dec_disk
def caesar(msg, key, mode):
ret = ''
msg = msg.upper()
enc_disk, dec_disk = makeDisk(key)
if enc_disk is None:
return ret
if mode is ENC:
disk = enc_disk
if mode is DEC:
disk = dec_disk
for c in msg:
if c in disk:
ret += disk[c]
else:
ret += c
return ret
def main():
plaintext = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key = 'F'
print('Original:\t\t%s' %plaintext.upper())
ciphertext = caesar(plaintext, key, ENC)
print('Caesar Cipher:\t%s' %ciphertext)
deciphertext = caesar(ciphertext, key, DEC)
print('Deciphered:\t%s' %deciphertext)
if __name__ == '__main__':
main()