-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar_cipher.py
76 lines (62 loc) · 1.4 KB
/
caesar_cipher.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
# function to get the Casesar Cipher Encoding dictionary
def get_encoding():
dict = {}
r_dict = {}
dict[' '] = 00
r_dict[0] = ' '
for i in range(65, 65 + 26):
dict[chr(i)] = i-64
r_dict[i-64] = chr(i)
dict[','] = 27
dict['.'] = 28
dict['?'] = 29
r_dict[27] = ','
r_dict[28] = '.'
r_dict[29] = '?'
for i in range(48, 48 + 10):
dict[chr(i)] = i-18
r_dict[i-18] = chr(i)
for i in range(97, 97 + 26):
dict[chr(i)] = i-57
r_dict[i-57] = chr(i)
dict['!'] = 66
r_dict[66] = '!'
# print(dict)
# print(r_dict)
return (dict, r_dict)
# encrypt the input string using the given key using Caesar Cipher
def encrypt(string, key):
dict, r_dict = get_encoding()
keys = list(dict.keys())
# print(keys)
out = ""
for char in string:
if char not in keys:
# print("Err: Invalid character")
return -1
else:
now = dict[char]
fin = ((now + key) % 67)
# print(fin)
out += r_dict[fin]
return out
# Decrypt the input string using the given key using Caesar Cipher
def decrypt(string, key):
dict, r_dict = get_encoding()
keys = list(dict.keys())
# print(keys)
out = ""
for char in string:
if char not in keys:
# print("Err: Invalid character")
return -1
else:
now = dict[char]
fin = ((now - key) % 67)
out += r_dict[fin%67]
return out
# string = "Hello .World!"
# key = 112
# enc = encrypt(string, key)
# print("encrypted: ", enc)
# print(decrypt(enc, key))