PLAYFAIR ENCRYPTION - PE


def generate_playfair_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 "ABCDEFGHIKLMNOPQRSTUVWXYZ":
    if char not in seen:
        seen.add(char)
        matrix.append(char)

return [matrix[i:i + 5] for i in range(0, 25, 5)]

def prepare_text(text):
text = text.upper().replace("J", "I").replace(" ", "")
result = ""
i = 0
while i < len(text):
a = text[i]
b = ''
if i + 1 < len(text):
b = text[i + 1]
if a == b:
result += a + 'X'
i += 1
else:
result += a + b
i += 2
else:
result += a + 'X'
i += 1
return result

def find_position(matrix, char):
for row in range(5):
for col in range(5):
if matrix[row][col] == char:
return row, col
return None

def encrypt_playfair(plaintext, key):
matrix = generate_playfair_matrix(key)
plaintext = prepare_text(plaintext)
ciphertext = ""

for i in range(0, len(plaintext), 2):
    a, b = plaintext[i], plaintext[i + 1]
    row1, col1 = find_position(matrix, a)
    row2, col2 = find_position(matrix, b)

    if row1 == row2:
        ciphertext += matrix[row1][(col1 + 1) % 5]
        ciphertext += matrix[row2][(col2 + 1) % 5]
    elif col1 == col2:
        ciphertext += matrix[(row1 + 1) % 5][col1]
        ciphertext += matrix[(row2 + 1) % 5][col2]
    else:
        ciphertext += matrix[row1][col2]
        ciphertext += matrix[row2][col1]

return ciphertext

key_input = input("Enter the key: ")
message_input = input("Enter the message to encrypt: ")

encrypted_text = encrypt_playfair(message_input, key_input)
print("Encrypted message:", encrypted_text)