|
| 1 | +key='kumarsashank' |
| 2 | +matrix=[] |
| 3 | +key=key.upper() |
| 4 | +# print(key) |
| 5 | +distinct_key=[] |
| 6 | +for i in key: |
| 7 | + if i not in distinct_key: |
| 8 | + distinct_key.append(i) |
| 9 | + |
| 10 | +print('Distinct key: ',distinct_key) |
| 11 | +alphabets='ABCDEFGHIKLMNOPQRSTUVWXYZ' #Removed J |
| 12 | +temp=[] |
| 13 | +for i in distinct_key: |
| 14 | + temp.append(i) |
| 15 | +for i in alphabets: |
| 16 | + if i not in temp: |
| 17 | + temp.append(i) |
| 18 | +matrix=[temp[0:5],temp[5:10],temp[10:15],temp[15:20],temp[20:25]] |
| 19 | +print('Playfair Matrix: ') |
| 20 | +for i in range(5): |
| 21 | + print(matrix[i]) |
| 22 | + |
| 23 | + |
| 24 | +text=input('Enter plain text: ') |
| 25 | +# text='Rak' |
| 26 | +text=text.upper() |
| 27 | +list_1=[] |
| 28 | + |
| 29 | +#making group of pairs |
| 30 | +text=text.replace(' ','') |
| 31 | +list_1=list(text) |
| 32 | +# print(list_1) |
| 33 | +for i in range(len(list_1)): |
| 34 | + if i%2!=0: |
| 35 | + if list_1[i-1]==list_1[i]: |
| 36 | + list_1.insert(i,'X') |
| 37 | +# print(list_1) |
| 38 | +if(len(list_1)%2!=0): |
| 39 | + list_1.append('X') |
| 40 | +# print(list_1) |
| 41 | + |
| 42 | +#making pairs |
| 43 | +list_2=[] |
| 44 | +for i in range(0,len(list_1),2): |
| 45 | + list_2.append(list_1[i:i+2]) |
| 46 | +print('Pairs are: ',list_2) |
| 47 | + |
| 48 | +def find_position(temp,l): |
| 49 | + for i in range(5): |
| 50 | + for j in range(5): |
| 51 | + if l[i][j]==temp: |
| 52 | + return i,j |
| 53 | + |
| 54 | +#encryption |
| 55 | +cipher=[] |
| 56 | + |
| 57 | +for e in list_2: |
| 58 | + p1,q1=find_position(e[0],matrix) |
| 59 | + p2,q2=find_position(e[1],matrix) |
| 60 | + if p1==p2: |
| 61 | + cipher.append(matrix[p1][(q1+1)%5]) |
| 62 | + cipher.append(matrix[p2][(q2+1)%5]) |
| 63 | + elif q1==q2: |
| 64 | + cipher.append(matrix[(p1+1)%5][q1]) |
| 65 | + cipher.append(matrix[(p2+1)%5][q2]) |
| 66 | + else: |
| 67 | + cipher.append(matrix[p1][q2]) |
| 68 | + cipher.append(matrix[p2][q1]) |
| 69 | +# print(cipher) |
| 70 | + |
| 71 | +str='' |
| 72 | +for i in cipher: |
| 73 | + str+=i |
| 74 | +print('Cipher text: ',str) |
0 commit comments