NSC Lab 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Network Security and Cryptography Lab

Lab Report 4
Date: 22-01-2024
20 CP 93
ALI SHER BAZ

Submitted to: Sir Adnan Mustafa


IMPLEMENTATION OF PLAYFAIR AND HILL CIPHER

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

print("Cipher Text:", cipher_text)


if __name__ ==
"__main__":
main()
def string_to_matrix(string):
string = ''.join([i for i in string if i.isalpha()])
rows = int(np.ceil(len(string) / 2)) matrix = []
for i in range(rows): row = [ord(j) - 65 for j
in string[i*2:(i+1)*2]] matrix.append(row)
return matrix
def
matrix_to_string(matrix):
string = ''
for row in matrix:
string += ''.join([chr(i + 65) for i in row])
return string
def encrypt(message,
key):
message_matrix = string_to_matrix(message)
key_matrix = np.array(key).reshape(2, 2) cipher_matrix
= np.dot(message_matrix, key_matrix) % 26 return
matrix_to_string(cipher_matrix)

message = input("Enter plaintext: ").upper()


key = [0, 1, 2, 3] encrypted_message =
encrypt(message, key) print("Encrypted:",
encrypted_message)

Output:
- -

You might also like