Playfair Cipher

The best-known multiple-letter encryption cipher is the Playfair, which treats digrams in the plaintext as single units and translates these units into ciphertext digrams.The Playfair algorithm is based on the use of a 5 × 5 matrix of letters constructed using a keyword. Here is an example, solved by Lord Peter Wimsey

In this case, the keyword is MONARCHY. The matrix is constructed by filling in the letters of the keyword (minus duplicates) from left to right and from top to bottom, and then filling in the remainder of the matrix with the remaining letters in alphabetic order. The letters I and J count as one letter.



Plaintext is encrypted two letters at a time, according to the following rules:

1. Repeating plaintext letters that are in the same pair are separated with a filler letter, such as x, so that balloon would be treated as ba lx lo on.

2. Two plaintext letters that fall in the same row of the matrix are each replaced by the letter to the right, with the first element of the row circularly following the last. For example, ar is encrypted as RM.

3. Two plaintext letters that fall in the same column are each replaced by the letter beneath, with the top element of the column circularly following the last. For example, mu is encrypted as CM.

4. Otherwise, each plaintext letter in a pair is replaced by the letter that lies in its own row and the column occupied by the other plaintext letter. Thus, hs becomes BP and ea becomes IM (or JM, as the encipherer wishes).

The Playfair cipher is a great advance over simple monoalphabetic ciphers.For one thing, whereas there are only 26 letters, there are 26 × 26 = 676 digrams, so that identification of individual digrams is more difficult. Furthermore, the relative frequencies of individual letters exhibit a much greater range than that of digrams, making frequency analysis much more difficult. For these reasons, the Playfair cipher was for a long time considered unbreakable. It was used as the standard field system by the British Army in World War I and still enjoyed considerable use by the U.S. Army and other Allied forces during World War II.

Despite this level of confidence in its security, the Playfair cipher is relatively easy to break, because it still leaves much of the structure of the plaintext language intact. A few hundred letters of ciphertext are generally sufficient.

Example: Encrypt the plaintext=HELLOWORLD using key=PLAYFAIRCIPHER

Step 1: Create a 5x5 Key Square


We'll use the keyword "PLAYFAIRCIPHER" and construct the key square:
P  L A Y  F
I  R C H  E
B D G K M
N O Q S  T
U V W X  Z

Step 2: Prepare the Plaintext

Let's encrypt the message "HELLO WORLD". First, split the message into pairs of letters. For identical letters, insert 'X' to separate them.

Plaintext: HELLO WORLD
Pairs: HE LX LO WO RL DX (since we add 'X' for the repeated 'L')

Step 3: Encrypt the Pairs

Encrypt each pair using the following rules:
  • Same Row: If both letters are in the same row, replace them with the letters immediately to their right (wrap around to the start if needed).
  • Same Column: If both letters are in the same column, replace them with the letters immediately below them (wrap around to the top if needed).
  • Rectangle: If neither of the above, form a rectangle. Replace each letter with the letter in the same row but in the column of the other letter.

Encryption Process:

  • HE: "H" and "E" are in the same row. Replace with "E" and "I".
  • LX: "L" and "X" form a rectangle. Replace with "Y" and "V".
  • LO: "L" and "O" are in the same column. Replace with "R" and "V"
  • WO: Forming a rectangle, "W" becomes "V" and "O" becomes "Q".
  • RL:"R" and "L" are in the same column. Replace with "D" and "R".
  • DX: "D" and "X" form a rectangle. Replace with "K" and "V".

Step 4: Write the Encrypted Message

Combine the encrypted pairs to form the final ciphertext.

Ciphertext: EI YV RV VQ DR KV  

Python Code Playfair Cipher

def generate_key_square(keyword):
    """Generates a 5x5 key square using the given keyword."""
    alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
    key = []
    for char in keyword.upper():
        if char not in key and char in alphabet:
            key.append(char)
    for char in alphabet:
        if char not in key:
            key.append(char)
    for i in range(0, 25, 5):
        print(key[i:i+5])
    return [key[i:i+5] for i in range(0, 25, 5)]

def preprocess_text(text):
    """Prepares the text by removing spaces, handling duplicates, and adding 'X' if necessary."""
    text = text.upper().replace("J", "I").replace(" ", "")
    i = 0
    while i < len(text):
        if i < len(text) - 1 and text[i] == text[i + 1]:
            text = text[:i + 1] + 'X' + text[i + 1:]
        i += 2
    if len(text) % 2 != 0:
        text += 'X'
    return text

def find_position(key_square, char):
    """Finds the row and column of a character in the key square."""
    for row in range(5):
        for col in range(5):
            if key_square[row][col] == char:
                return row, col
    return None

def playfair_encrypt(plaintext, keyword):
    """Encrypts plaintext using the Playfair cipher with the given keyword."""
    key_square = generate_key_square(keyword)
    plaintext = preprocess_text(plaintext)
    ciphertext = []

    for i in range(0, len(plaintext), 2):
        char1, char2 = plaintext[i], plaintext[i + 1]
        row1, col1 = find_position(key_square, char1)
        row2, col2 = find_position(key_square, char2)

        if row1 == row2:
            # Same row: replace with the letters immediately to the right
            ciphertext.append(key_square[row1][(col1 + 1) % 5])
            ciphertext.append(key_square[row2][(col2 + 1) % 5])
        elif col1 == col2:
            # Same column: replace with the letters immediately below
            ciphertext.append(key_square[(row1 + 1) % 5][col1])
            ciphertext.append(key_square[(row2 + 1) % 5][col2])
        else:
            # Rectangle: swap columns
            ciphertext.append(key_square[row1][col2])
            ciphertext.append(key_square[row2][col1])

    return ''.join(ciphertext)

# Example usage:
keyword = "PLAYFAIRCIPHER"
plaintext = "HELLO WORLD"
ciphertext = playfair_encrypt(plaintext, keyword)
print("Ciphertext:", ciphertext)

Output:
['P', 'L', 'A', 'Y', 'F']
['I', 'R', 'C', 'H', 'E']
['B', 'D', 'G', 'K', 'M']
['N', 'O', 'Q', 'S', 'T']
['U', 'V', 'W', 'X', 'Z']
Ciphertext: EIYVRVVQDRKV

Construct a Playfair matrix with the key="decrypt". Encrypt the message "meet at our usual place" with the constructed matrix.List out rules also ( University Question).

['D', 'E', 'C', 'R', 'Y']
['P', 'T', 'A', 'B', 'F']
['G', 'H', 'I', 'K', 'L']
['M', 'N', 'O', 'Q', 'S']
['U', 'V', 'W', 'X', 'Z']
Ciphertext: NDTHBAMWDXMZFIFGIARV

Comments

Popular posts from this blog

Cryptographic Algorithms CST 393 KTU CS Honour Notes Semester V -Dr Binu V P

Syllabus CST 393 Cryptographic Algorithms

Computer Security Concept- CIA Triad