-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlayfair.py
101 lines (90 loc) · 2.82 KB
/
Playfair.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
key = input("Enter key : ")
key = key.replace(" ", "")
key = key.upper()
def matrix(x, y, initial):
return [[initial for i in range(x)] for j in range(y)]
result = list()
for c in key:
if c not in result:
if c == 'J':
result.append('I')
else:
result.append(c)
flag = 0
for i in range(65, 91):
if chr(i) not in result:
if i == 73 and chr(74) not in result:
result.append("I")
flag = 1
elif flag == 0 and i == 73 or i == 74:
pass
else:
result.append(chr(i))
k = 0
my_matrix = matrix(5, 5, 0)
for i in range(0, 5):
for j in range(0, 5):
my_matrix[i][j] = result[k]
k += 1
def locindex(c):
loc = list()
if c == 'J':
c = 'I'
for i, j in enumerate(my_matrix):
for k, l in enumerate(j):
if c == l:
loc.append(i)
loc.append(k)
return loc
def encrypt():
msg = str(input("ENTER MSG : "))
msg = msg.upper()
msg = msg.replace(" ", "")
i = 0
for s in range(0, len(msg) + 1, 2):
if s < len(msg) - 1:
if msg[s] == msg[s + 1]:
msg = msg[:s + 1] + 'X' + msg[s + 1:]
if len(msg) % 2 != 0:
msg = msg[:] + 'X'
print("CIPHER TEXT:", end=' ')
while i < len(msg):
loc = list()
loc = locindex(msg[i])
loc1 = list()
loc1 = locindex(msg[i + 1])
if loc[1] == loc1[1]:
print("{}{}".format(my_matrix[(loc[0] + 1) % 5][loc[1]], my_matrix[(loc1[0] + 1) % 5][loc1[1]]), end=' ')
elif loc[0] == loc1[0]:
print("{}{}".format(my_matrix[loc[0]][(loc[1] + 1) % 5], my_matrix[loc1[0]][(loc1[1] + 1) % 5]), end=' ')
else:
print("{}{}".format(my_matrix[loc[0]][loc1[1]], my_matrix[loc1[0]][loc[1]]), end=' ')
i = i + 2
def decrypt():
msg = str(input("ENTER CIPHER TEXT:"))
msg = msg.upper()
msg = msg.replace(" ", "")
print("PLAIN TEXT:", end=' ')
i = 0
while i < len(msg):
loc = list()
loc = locindex(msg[i])
loc1 = list()
loc1 = locindex(msg[i + 1])
if loc[1] == loc1[1]:
print("{}{}".format(my_matrix[(loc[0] - 1) % 5][loc[1]], my_matrix[(loc1[0] - 1) % 5][loc1[1]]), end=' ')
elif loc[0] == loc1[0]:
print("{}{}".format(my_matrix[loc[0]][(loc[1] - 1) % 5], my_matrix[loc1[0]][(loc1[1] - 1) % 5]), end=' ')
else:
print("{}{}".format(my_matrix[loc[0]][loc1[1]], my_matrix[loc1[0]][loc[1]]), end=' ')
i = i + 2
while (1):
choice = int(input("\n 1.Encryption \n 2.Decryption: \n 3.EXIT \n Enter Your Choice: \n "))
if choice == 1:
encrypt()
elif choice == 2:
decrypt()
elif choice == 3:
exit()
else:
print("Choose correct choice")