-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathCaesar_cipher.py
119 lines (105 loc) · 2.97 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
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
# making of Caesar Cipher
import sys
seriesEnlv1=dict()
seriesDelv1=dict()
seriesEnlv2=dict()
seriesDelv2=dict()
def mapping():
global seriesEnlv1
global seriesDelv1
global seriesEnlv2
global seriesDelv2
alphalv1='abcdefghijklmnopqrstuvwxyz'
for i in range(0,26):
seriesEnlv1[alphalv1[i]]=i
seriesDelv1[i]=alphalv1[i]
alphalv2='ZYXWVUTSRQPONMLKJIHGFEDCBA'
for i in range(-26,0):
seriesEnlv2[alphalv2[i]]=i
seriesDelv2[i]=alphalv2[i]
def check(message):
for i in message:
if((i==" " or i.isalpha())==False):
print("\n Message can't be send, remove any numbers or special symbols to continue ")
raise Exception(" message fault ")
def message(code):
mess=[]
##print(code)
global seriesDelv1
global seriesDelv2
for i in code:
if(i>0 or i==0):
mess.append(seriesDelv1[i])
else:
mess.append(seriesDelv2[i])
return ("".join(mess))
def modify(string):
splittedString = string.split(" ")
capStringWithoutSpace= ""
for i in splittedString:
capStringWithoutSpace= capStringWithoutSpace + i.capitalize()
return capStringWithoutSpace
def remodify(string):
wordList= []
count = -1
lengthOfString= len(string)
for i in string:
count+=1
if(count==0):
leftLimit=count
elif(i.isupper()):
rightLimit=count
wordList.append(string[leftLimit:rightLimit])
leftLimit=rightLimit
elif(count==lengthOfString-1):
rightLimit=count+1
wordList.append(string[leftLimit:rightLimit])
concatenatedString = " ".join(wordList)
lengthOfConcatenatedString = len(concatenatedString)
formattedString= concatenatedString[0].capitalize()+concatenatedString[1:lengthOfConcatenatedString].lower()
return formattedString
def textconv(text,key):
mapping()
key=key%26
try:
check(text)
except:
print(" Message format is incorrect ")
sys.exit()
text=modify(text)
code=[]
global seriesEnlv1
global seriesEnlv2
for i in text:
if(i.isupper()):
code.append(-(abs(seriesEnlv2[i]-key)%26))
else:
code.append((seriesEnlv1[i]+key)%26)
return (message(code))
def textrevert(encoded,key):
code=[]
key=key%26
global seriesEnlv1
for i in encoded:
if (i.islower()):
x=seriesEnlv1[i]- key
if(x<0):
x+=26
else:
x=seriesEnlv2[i]+ key
if(x>0 or x==0 ):
x-=26
code.append(x)
return remodify(message(code))
def main():
simpleText=input("Enter the simple text : ")
try:
key=int(input(" Enter the key for the Text :"))
except:
print(" Enter only numeric key ")
sys.exit()
encoded=textconv(simpleText,key)
print(encoded)
decoded=textrevert(encoded,key)
print(decoded)
main()