Skip to content

Commit 336f73d

Browse files
authoredNov 14, 2022
Add files via upload
1 parent d067fe6 commit 336f73d

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
 

‎playfair_cipher.py

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
from collections import OrderedDict
2+
3+
4+
def Generate_Pairs():
5+
i = 0
6+
while i != len(plainText_lis):
7+
if (i == (len(plainText_lis) - (len(plainText_lis) % 2)) and len(plainText_lis) % 2 != 0):
8+
plainText_lis.append('x')
9+
break
10+
if (plainText_lis[i] == plainText_lis[i + 1]):
11+
plainText_lis.insert(i + 1, 'x')
12+
i += 2
13+
14+
Key_Matrix()
15+
16+
17+
def Key_Matrix():
18+
key_lis_tmp.extend(key_dup)
19+
20+
var = 0
21+
22+
while len(key_lis_tmp) != 25:
23+
value = chr(97 + var)
24+
if value not in key_lis_tmp:
25+
if value != 'j':
26+
key_lis_tmp.append(value)
27+
var += 1
28+
29+
for i in range(0, len(key_lis_tmp), 5):
30+
matrix_pf.append(key_lis_tmp[i:i + 5])
31+
32+
print("\nMatrix: ")
33+
for i in matrix_pf:
34+
print(i, end="\n")
35+
36+
Playfair_Cypher_Algo()
37+
38+
39+
def Fetch_Inde(valu_fn):
40+
for index_one_fe, i in enumerate(matrix_pf):
41+
for index_two_fe, j in enumerate(i):
42+
if j == valu_fn:
43+
return (index_one_fe, index_two_fe)
44+
45+
46+
def Playfair_Cypher_Algo():
47+
for i in range(0, len(plainText_lis) - 1, 2):
48+
index_one_pf, index_two_pf = Fetch_Inde(plainText_lis[i])
49+
index_three_pf, index_four_pf = Fetch_Inde(plainText_lis[i + 1])
50+
51+
if (index_one_pf == index_three_pf):
52+
index_two_pf = (index_two_pf + 1) % 5
53+
index_four_pf = (index_four_pf + 1) % 5
54+
cipherText.extend(matrix_pf[index_one_pf][index_two_pf])
55+
cipherText.extend(matrix_pf[index_three_pf][index_four_pf])
56+
57+
elif (index_two_pf == index_four_pf):
58+
index_one_pf = (index_one_pf + 1) % 5
59+
index_three_pf = (index_three_pf + 1) % 5
60+
cipherText.extend(matrix_pf[index_one_pf][index_two_pf])
61+
cipherText.extend(matrix_pf[index_three_pf][index_four_pf])
62+
63+
else:
64+
cipherText.extend(matrix_pf[index_one_pf][index_four_pf])
65+
cipherText.extend(matrix_pf[index_three_pf][index_two_pf])
66+
67+
print("\nCipher Text: ", "".join(cipherText))
68+
69+
70+
plainText = input("\nEnter Plain Text: ")
71+
key = input("Enter Key: ")
72+
73+
plainText = plainText.replace(" ", "").lower()
74+
plainText = plainText.replace("j", "i")
75+
key = key.replace(" ", "").lower()
76+
key = key.replace("j", "i")
77+
78+
key_dup = "".join(OrderedDict.fromkeys(key))
79+
80+
plainText_lis = list(plainText)
81+
matrix_pf = []
82+
key_lis_tmp = []
83+
cipherText = []
84+
85+
Generate_Pairs()
86+
Generate_Pairs()

0 commit comments

Comments
 (0)
Please sign in to comment.