HILL CIPHER ENCRYPTION - PE
import numpy as np
def mod26(matrix):
"""Ensure that all elements are within the range of 0 to 25 for Hill Cipher (mod 26)"""
return np.mod(matrix, 26)
def prepare_text(text, size):
"""Prepares the text by padding it to fit the matrix size"""
text = text.replace(" ", "").upper()
# Ensure the length of the text is a multiple of the matrix size
if len(text) % size != 0:
text += 'X' * (size - len(text) % size) # Padding with 'X' if needed
return text
def create_key_matrix(size, elements):
"""Creates the key matrix from user input"""
matrix = np.array(elements).reshape(size, size)
return matrix
def encrypt_hill_cipher(key_matrix, plaintext, size):
"""Encrypt the plaintext using the Hill cipher"""
plaintext = prepare_text(plaintext, size)
ciphertext = ""
for i in range(0, len(plaintext), size):
block = plaintext[i:i+size]
block_vector = np.array([ord(char) - ord('A') for char in block])
# Perform matrix multiplication (dot product)
encrypted_block = np.dot(key_matrix, block_vector)
# Apply modulo 26 operation
encrypted_block = mod26(encrypted_block)
# Convert back to characters
encrypted_text = ''.join(chr(num + ord('A')) for num in encrypted_block)
ciphertext += encrypted_text
return ciphertext
size = 3 # We are using a 3x3 matrix for Hill Cipher
elements = [6, 24, 1, 13, 16, 10, 20, 17, 15] # The 3x3 key matrix elements
plaintext = "PAYNOW"
Create the key matrix
key_matrix = create_key_matrix(size, elements)
Encrypt the plaintext
encrypted_text = encrypt_hill_cipher(key_matrix, plaintext, size)
print("Encrypted message:", encrypted_text)