Playfair cipher is a manual digraph substitution cipher that encrypts text two letters at a time using a 5 by 5 square built from a keyword. Charles Wheatstone invented it in 1854, and it carries the name of Lord Playfair, who promoted it. Because it works on pairs, plain letter-frequency counting does not break it directly.
Build the key square first. Write the keyword, drop repeated letters, then fill the rest of the alphabet in order. A 5 by 5 grid holds only 25 cells, so I and J share one cell, and J is read as I.
Then prepare the message: remove spaces, turn J into I, and split it into pairs. If a pair would hold two equal letters, insert an X between them. If the last pair has one letter, add an X. Each pair is encrypted by one of three rules:
Decryption uses the same rules in the opposite direction: left for rows, up for columns, and the same rectangle swap. After decrypting, you remove padding X letters by judgment, because the algorithm cannot tell a real X from a filler.
The Python run below builds the square for the keyword PLAYFAIR EXAMPLE and encrypts a message. The grid and ciphertext are printed as produced.
import string
A = string.ascii_uppercase
def square(key):
s = []
for c in (key + A).replace('J', 'I'):
if c in A and c not in s: s.append(c)
return s
def pf(p, key):
s = square(key); p = p.replace('J', 'I'); pairs = []; i = 0
while i < len(p):
a = p[i]; b = p[i+1] if i + 1 < len(p) else 'X'
if a == b: pairs.append((a, 'X')); i += 1
else: pairs.append((a, b)); i += 2
out = ''
for a, b in pairs:
ra, ca = divmod(s.index(a), 5); rb, cb = divmod(s.index(b), 5)
if ra == rb: out += s[ra*5 + (ca+1) % 5] + s[rb*5 + (cb+1) % 5]
elif ca == cb: out += s[((ra+1) % 5)*5 + ca] + s[((rb+1) % 5)*5 + cb]
else: out += s[ra*5 + cb] + s[rb*5 + ca]
return out
print(pf("HIDETHEGOLDINTHETREESTUMP", "PLAYFAIREXAMPLE"))
print(pf("BALLOON", "MONARCHY"))
BMODZBXDNABEKUDMUIXMMOUVIF
IBSUPMNA
For HIDETHEGOLDINTHETREESTUMP the square is P L A Y F, I R E X M, B C D G H, K N O Q S, T U V W Z. The pair HI is a rectangle and becomes BM. BALLOON splits as BA LX LO ON because the double L gets an X between.
Playfair has 600 possible digraphs, from 25 letters paired with the 24 others, since a pair never repeats a letter. A simple substitution cipher has only 26 single letters to disguise, so Playfair spreads the frequencies much more thinly. Digraph frequency analysis still works with enough ciphertext.