NSC Lab 4
NSC Lab 4
NSC Lab 4
Lab Report 4
Date: 22-01-2024
20 CP 93
ALI SHER BAZ
Task 1:
Encrypt plain text communication with keyword computer using Playfair cipher.
Code:
import string
MX = 5 def playfair(ch1,
ch2, key):
cipher_text = "" for i
in range(MX): for j in
range(MX): if ch1 ==
key[i][j]:
w = i
x = j elif ch2 ==
key[i][j]:
y = i
z = j
if w == y:
x = (x + 1) % 5 z = (z + 1)
% 5 cipher_text += key[w][x] +
key[y][z] elif x == z:
pass
else:
w = (w + 1) % 5
y = (y + 1) % 5
cipher_text += key[w][x] + key[y][z]
cipher_text += key[w][z] + key[y][x]
return cipher_text
def
main():
keystr = input("Enter key: ").upper().replace("J", "I")
plaintext = input("Enter the plain text: ").upper().replace("J", "I")
keyminus = "" for char in
string.ascii_uppercase: if char not in
keystr and char != "J":
keyminus += char
key = [[0] * MX for _
in range(MX)]
k = 0 m = 0
for i in range(MX): for
j in range(MX): if
k < len(keystr):
key[i][j] = keystr[k]
k += 1 else:
key[i][j] = keyminus[m]
m += 1
print("Key
Matrix:") for row in
key:
print(' '.join(row))
print("\nEntered text:",
plaintext) cipher_text = "" i =
0 while i < len(plaintext):
if i == len(plaintext) - 1:
cipher_text += playfair(plaintext[i], 'X', key)
i += 1 elif plaintext[i] == plaintext[i+1]:
cipher_text += playfair(plaintext[i], 'X', key)
i += 1 else:
cipher_text += playfair(plaintext[i], plaintext[i+1], key)
i += 2
Output:
- -