Enter your text and key to see the Playfair cipher in action.
Examples of PlayFair Cipher implementation in various programming languages.
def create_matrix(key):
key = key.upper().replace("J", "I")
matrix = []
seen = set()
for char in key:
if char not in seen and char.isalpha():
seen.add(char)
matrix.append(char)
for char in range(65, 91):
c = chr(char)
if c != 'J' and c not in seen:
seen.add(c)
matrix.append(c)
return [matrix[i:i+5] for i in range(0, len(matrix), 5)]
def find_position(matrix, char):
for i, row in enumerate(matrix):
if char in row:
return i, row.index(char)
return -1, -1
def prepare_text(text):
text = text.upper().replace("J", "I")
text = "".join([char if char.isalpha() else "" for char in text])
if len(text) % 2 != 0:
text += "X"
return [text[i:i+2] for i in range(0, len(text), 2)]
def playfair_cipher(text, key, encrypt=True):
matrix = create_matrix(key)
pairs = prepare_text(text)
result = []
for pair in pairs:
row1, col1 = find_position(matrix, pair[0])
row2, col2 = find_position(matrix, pair[1])
if row1 == row2:
col1 = (col1 + (1 if encrypt else -1)) % 5
col2 = (col2 + (1 if encrypt else -1)) % 5
elif col1 == col2:
row1 = (row1 + (1 if encrypt else -1)) % 5
row2 = (row2 + (1 if encrypt else -1)) % 5
else:
col1, col2 = col2, col1
result.append(matrix[row1][col1])
result.append(matrix[row2][col2])
return ''.join(result)
# Example usage
plaintext = "HELLO WORLD"
key = "KEYWORD"
encrypted = playfair_cipher(plaintext, key)
decrypted = playfair_cipher(encrypted, key, encrypt=False)
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")