-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcaesar-cipher.py
68 lines (63 loc) · 1.85 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
#This is a python program to decode and encode a caesar-cypher, given its key.
#Function to encrypt a given string.
def encrypt(k):
n,i=0,0
l="abcdefghijklmnopqrstuvwxyz"
l=list(l)
b=[]
a=input("enter text to be encrypted: ")
a=list(a)
while(n<len(a)):
if a[n].lower() in l:
if a[n].isupper():
i=l.index(a[n].lower())
i=(i+k)%26
b.append(l[i].upper())
n+=1
else:
i=l.index(a[n])
i=(i+k)%26
b.append(l[i])
n+=1
else:
if(a[n]==' '):
b.append(' ')
n+=1
print("The encrypted text is: ","".join(b))
#Function to decrypt an encrypted string.
def decrypt(k):
n,i=0,0
l="abcdefghijklmnopqrstuvwxyz"
l=list(l)
b=[]
a=input("Enter cipher to be decrypted: ")
a=list(a)
while(n<len(a)):
if a[n].lower() in l:
if a[n].isupper():
i=l.index(a[n].lower())
i=(i-k)%26
b.append(l[i].upper())
n+=1
else:
i=l.index(a[n])
i=(i-k)%26
b.append(l[i])
n+=1
else:
if(a[n]==' '):
b.append(' ')
n+=1
print("Cipher after decryption is: ","".join(b))
#Main
opt=int(input("1.encrypt 2.decrypt 0.exit"))
while(opt!=0):
if(opt==1):
n=int(input("enter key"))
encrypt(n)
elif(opt==2):
n=int(input("enter key"))
decrypt(n)
else:
print("enter valid option")
opt=int(input("1.encrypt 2.decrypt 0.exit"))