You are on page 1of 8

Department of Computer Engineering

Experiment No: 03
Roll No: A678
Date: /02/23
Aim: To Implement Playfair Cipher

Theory:
Playfair cipher is an encryption algorithm to encrypt or encode a message. It is the same as a
traditional cipher. The only difference is that it encrypts a digraph (a pair of two letters) instead of
a single letter. It initially creates a key-table of 5*5 matrix. The matrix contains alphabets that act as
the key for encryption of the plaintext. Note that any alphabet should not be repeated. Another point
to note that there are 26 alphabets and we have only 25 blocks to put a letter inside it. Therefore, one
letter is excess so, a letter will be omitted (usually J) from the matrix. Nevertheless, the plaintext
contains J, then J is replaced by I. It means treat I and J as the same letter, accordingly.

Advantages of Playfair Cipher

1. Diverse ciphertext if we scrutinize the Algorithm, we can notice at every Stage we are getting
diverse ciphertext, thus more trouble to cryptanalyst.
2. Brute force attack does not affect it.
3. Cryptanalyze (the process of decoding cipher without knowing key) is not possible.
4. Overcomes the limitation of simple Playfair square cipher.
5. Easy to perform the substitution.

Limitations of Playfair Cipher

The limitations of the Playfair cipher are as follows:

o Only 25 alphabets are supported.


o It does not support numeric characters.
o Only either upper cases or lower cases are supported.

o The use of special characters (such as blank space, newline, punctuations, etc.) is prohibited.

o It does not support other languages, except English.

o Encryption of media files is also not supported.

1
Department of Computer Engineering

Playfair Cipher Encryption Rules

1. First, split the plaintext into digraphs (pair of two letters). If the plaintext has the odd number of
letters, append the letter Z at the end of the plaintext. It makes the plaintext of even For example,
the plaintext MANGO has five letters. So, it is not possible to make a digraph. Since, we will
append a letter Z at the end of the plaintext, i.e. MANGOZ.

2. After that, break the plaintext into digraphs (pair of two letters). If any letter appears twice (side
by side), put X at the place of the second occurrence. Suppose, the plaintext is COMMUNICATE
then its digraph becomes CO MX MU NI CA TE. Similarly, the digraph for the plaintext JAZZ
will be JA ZX ZX, and for plaintext GREET, the digraph will be GR EX ET.

3. To determine the cipher (encryption) text, first, build a 5*5 key-matrix or key-table and filled it
with the letters of alphabets, as directed below:

o Fill the first row (left to right) with the letters of the given keyword (ATHENS). If the keyword
has duplicate letters (if any) avoid them. It means a letter will be considered only once. After
that, fill the remaining letters in alphabetical order. Let's create a 5*5 keymatrix for the
keyword ATHENS.

Note that in the above matrix any letter is not repeated. The letters in the first row (in green color)
represent the keyword and the remaining letters sets in alphabetical order.

4. There may be the following three conditions:

i) If a pair of letters (digraph) appears in the same row

In this case, replace each letter of the digraph with the letters immediately to their right. If there is no
letter to the right, consider the first letter of the same row as the right letter. Suppose, Z is a letter
whose right letter is required, in such case, T will be right to Z.

2
Department of Computer Engineering

ii) If a pair of letters (digraph) appears in the same column

In this case, replace each letter of the digraph with the letters immediately below them. If there is no
letter below, wrap around to the top of the same column. Suppose, W is a letter whose below letter
is required, in such case, V will be below W.

iii) If a pair of letters (digraph) appears in a different row and different column

In this case, select a 3*3 matrix from a 5*5 matrix such that pair of letters appear in the 3*3 matrix.
Since they occupy two opposite corners of a square within the matrix. The other corner will be a
cipher for the given digraph.

In other words, we can also say that intersection of H and Y will be the cipher for the first letter and

Suppose, a digraph is HY and we have to find a cipher for it. We observe that both H and Y are
placed in different rows and different columns. In such cases, we have to select a 3*3 matrix in such
a way that both H and Y appear in the 3*3 matrix (highlighted with yellow color). Now, we will
consider only the selected matrix to find the cipher.

3
Department of Computer Engineering

Now to find the cipher for HY, we will consider the diagonal opposite to HY, i.e. LU. Therefore,
the cipher for H will be L, and the cipher for Y will be U.

Program :

plainText=[]
keyMatrix = []
cipherTextList =[]
def index_2d(keyMatrix, v):
for i, x in enumerate(keyMatrix):
if v in x:
return [i, x.index(v)]
def keyMatrixGeneration(keyMatrix,reducedAlphabet):
alphacounter = 0
alpha = len(reducedAlphabet)
#print(alpha,'[alpha]')
while alphacounter < alpha and len(reducedAlphabet[alphacounter:alphacounter+5]) :
tempReducedAlphabet = []
#print(reducedAlphabet[0:5],'[reducedAlphabet temp]')
tempReducedAlphabet.append(reducedAlphabet[alphacounter:alphacounter+5])
alphacounter+=5
keyMatrix.extend(tempReducedAlphabet)
if alphacounter > alpha and len(reducedAlphabet[alphacounter-5:]):
tempReducedAlphabet = []
tempReducedAlphabet.append(reducedAlphabet[alphacounter-5:])
keyMatrix.append(tempReducedAlphabet)
return keyMatrix
def playFairCipher(plainText,key):
# create key matrix
#print(key,'[key]')
#print('[playFairCipher def]')
cipherText = ''

4
Department of Computer Engineering

keyList = list(key.strip(' '))


keyListSet = set(keyList) # use this to find difference in alphabet and key
reducedKeyList = []
for ch in keyList:
if ch not in reducedKeyList:
reducedKeyList.append(ch)
tempKey = []
#print(keyListSet,reducedKeyList)

k = len(reducedKeyList)
counter = 0
alphabet = list('abcdefghijklmnopqrstuvwxyz')
alphabetSet = set(alphabet)
keycount = 5
#print(k)
if k==5:
#print('k==5')
keyMatrix.append(reducedKeyList[0:5])
elif k>5:
while keycount<=k:

keyMatrix.append(reducedKeyList[keycount-5:keycount])
keycount+=5
if keycount > k:
keyMatrix.append(reducedKeyList[keycount-5:])

else:
keyMatrix.append(reducedKeyList)

print(keyMatrix,'[before keyMatrix]')
reducedAlphabetSet = alphabetSet-keyListSet
#print(reducedAlphabetSet,'[reducedAlphabetSet]')
reducedAlphabet = list(reducedAlphabetSet)
reducedAlphabet.sort()
#print(reducedAlphabet,'[reducedAlphabet list]')
if 'i'and 'j' in reducedAlphabet:
reducedAlphabet.remove('j')
if 'i' not in reducedAlphabet and 'j' not in reducedAlphabet:
ind = index_2d(keyMatrix,'j')
print(ind,keyMatrix[ind[0]][ind[1]])

5
Department of Computer Engineering

keyMatrix[ind[0]].remove(keyMatrix[ind[0]][ind[1]])
lengthCheck = False
keyN = 0
# generation of key matrix
for i in range(0,len(keyMatrix)):
if len(keyMatrix[i])<5:
lengthCheck=True
keyN = i
if lengthCheck==True:
tempReducedAlphabet = []
tempReducedAlphabet.extend(reducedAlphabet[0:5-len(keyMatrix[keyN])])
#print(tempReducedAlphabet,'[tempReducedAlphabet]')
keyMatrix[keyN].extend(tempReducedAlphabet)
for i in tempReducedAlphabet:
reducedAlphabet.remove(i)
#print(reducedAlphabet,'[reducedAlphabet]')
keyMatrixGeneration(keyMatrix,reducedAlphabet)
else:
keyMatrixGeneration(keyMatrix,reducedAlphabet)
print(keyMatrix,'[keymatrix]')
# matching plainText with key matrix
for i in range(0,len(plainText)):
first=[]
second=[]
first.extend(index_2d(keyMatrix,plainText[i][0]))
second.extend(index_2d(keyMatrix,plainText[i][1]))
if first[0]!=second[0] and first[1]!=second[1]:
cipherText += keyMatrix[first[0]][second[1]]+ keyMatrix[second[0]][first[1]]
elif first[0]==second[0]:
if first[1]+1<len(keyMatrix[first[0]]):
cipherText+=keyMatrix[first[0]][first[1]+1]
else:
cipherText+=keyMatrix[first[0]][0]
if second[1]+1<len(keyMatrix[second[0]]):
cipherText+=keyMatrix[first[0]][second[1]+1]
else:
cipherText+=keyMatrix[first[0]][0]
else:
if first[0]+1<len(keyMatrix):
cipherText+=keyMatrix[first[0]+1][first[1]]

6
Department of Computer Engineering

else:
cipherText+=keyMatrix[0][first[1]]
if second[0]+1<len(keyMatrix):
cipherText+=keyMatrix[second[0]+1][second[1]]
else:
cipherText+=keyMatrix[0][second[1]]

#print(first,'[first]')

return cipherText
def plainTextConversion(s,key):

i=0

sList = list(s.strip())
n = len(sList)
while(n>0):
temp=[]
checkSame=False
#print(sList,'sList')
for j in range(0,2):
if j<len(sList) and sList[j] not in temp :
temp.append(sList[j])
checkSame = False
elif j<len(sList) and sList[j] in temp :
temp.append('x')
checkSame = True
else:
checkSame = False
continue
#print(temp,'temp')
sList.remove(sList[0])
# print(checkSame)
if len(temp)>1 and checkSame == False:
sList.remove(sList[0])
plainText.append(temp)
n=n-2
elif len(temp)>1 and checkSame == True:
#do noting
plainText.append(temp)

7
Department of Computer Engineering

n=n-1
elif len(temp)<1 and checkSame == True:
# do nothing
plainText.append(temp)
else:
temp.append('x')
plainText.append(temp)
n=n-2

#print(n,'n')

#print(plainText,'plainText')

print(plainText,'final')
res = playFairCipher(plainText,key)
return res

if __name__ == '__main__':
s = input ('enter plainText : ')
key = input('enter key text : ')
s = ''.join(s.split())
key = ''.join(key.split())
print(s,'[s]')
result = plainTextConversion(s,key)
print (result)

O/P :

Conclusion : Thus, we have successfully studied and implemented program for


PlayFair Cipher using Python language.

You might also like