Practical 5
Practical 5
Practical : 5
Aim : Write a program to perform encryption and decryption using Play-fair Cipher
Technique.
Procedure: The best-known multiple letter encryption cipher is the Playfair. It is a symmetric-encryption
technique. The Play-Fair algorithm uses a 5x5 matrix of letters called Playfair square or Wheatston-square,
constructed using keyword.
EXAMPLE:
OUTPUT:
PLAY-FAIR KEYWORD MATRIX:
C E I T D
P A R M N
B F G H K
L O Q S U
V W X Y Z
ENCRYPTION:
PLAIN-TEXT ARRANGMENT: BA LX LO ON SX
CIPHER-TEXT: FPQVOQUAQY
Page No: 5
2CEIT5PE11: Cryptography and Network Security Practical - 5
DECRYPTION:
CIPHER-TEXT: FPQVOQUAQY
PLAIN-TEXT: BALXLOONSX --> Remove ‘X’ So, Message is: BALLOONS
Code:
# Function to locate the position of a character in the 5x5 cipher
matrix def indexlocator(char): for i in range(5): for j
in range(5): if ciphermatrix[i][j] == char:
return i, j
#Initializing variables a and b for use in recursion in filling other
characters a = b = 0
#Getting user inputs Key (to make the 5x5 char matrix) and
Plain Text key = input("Enter key: ") key = key.replace(" ",
"") key = key.upper() plaintext = input("Plain text: ")
plaintext = plaintext.replace(" ", "") plaintext =
plaintext.upper()
# The function matrix that creates a nested list recursively (5x5
grid) def matrix(x, y, initial):
return [[initial for i in range(x)] for j in
range(y)] # Populating keyintomatrix with unique
characters from the key keyintomatrix = list() for c in
key: if c not in keyintomatrix: if c == 'J':
keyintomatrix.append('I')
else:
keyintomatrix.append(c)
# Filling the rest of the matrix with unused letters from the
alphabet for i in range(65, 91): if chr(i) not in
keyintomatrix: if i == 73 and chr(74) not in
keyintomatrix:
keyintomatrix.append("I")
a = 1 elif a == 0 and i == 73
or i == 74:
pass
else:
keyintomatrix.append(chr(i))
# Defining the cipher matrix as a 5x5 matrix with an initial
value of 0 ciphermatrix = matrix(5, 5, 0) for i in range(0, 5):
for j in range(0, 5):
ciphermatrix[i][j] = keyintomatrix[b] # Populating ciphermatrix with
characters b += 1
# Encryption function using the Playfair cipher encryption
method def encryption(text):
i = 0
# Adjusting the text by inserting 'X' if there are identical pairs or if the length
is odd for s in range(0, len(text) + 1, 2):
if s < len(text) - 1:
if text[s] == text[s + 1]:
text = text[:s + 1] + 'X' + text[s
+ 1:] if len(text) % 2 != 0: text =
text[:] + 'X'