# Playfair

The playfair is a digraph substitution cypher using a key to encrypt messages. In order to encrypt, the letters of the key are placed on a 5x5 square, dropping any duplicate letters and padding with the letters of the alphabet to complete the square.

Encryption follows the rules of the plaintext:

• If both letters of the plaintext are the same (or only one letter remains), substitute the second letter or add an "X" (or "Q") after the first letter. Encrypt the new pair and continue.
• If the letters appear on the same row, slide them to the immediate right (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row).
• If the letters appear on the same column, slide them down (wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column).
• If the letters are not on the same row or column, then they form a rectangle on the square. Replace them by the letters on the opposite corners of the rectangle. The first letter of the encrypted pair is the one that lies on the same row as the first letter of the plain-text pair.

Taking the key as good day, the square becomes:

G O D A Y
B C E F G
H I J K L
M N P Q R
S T U V W

Encrypting the message: live long and prosper ( LI VE LO NG AN DP RO SP ER ):

• LI forms a row:
H I J K L

so slide and wrap to HJ:

H I -> J K L ->
• VE forms a rectangle:
    E F
J K
P Q
U V

so take the opposite corners, first letter is V so we obtain UF:

    E -> F
J    K
P    Q
U <- V
• LO forms a rectangle:
  O  -> Y
C     G
I <-  L

so we obtain IY.

• NG forms a rectangle:
  C <-  G
I     L
N  -> R

so we obtain RC.

• AN forms a rectangle:
  O <- A
C    F
I    K
N -> Q

so we obtain OQ.

• DP forms a column:
    D
|
E
J
P
|
U

so we obtain EU.

• RO forms a rectangle:
  O  -> Y
C     G
I     L
N <-  R


so we obtain NY.

• SP forms a rectangle:


M  <- P
S ->  U

so we obtain UM.

• ER forms a rectangle:
    E -> G
J    L
P <- R


so we obtain GP.

Thus, the final cyphertext reads: HJ UF IY RC OQ EU NY UM GP.

To decrypt, perform the inverse operation of the last three rules and drop any extra "X" or "Q" that do not make sense in the final message. 