-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHill Cipher Encryption
More file actions
43 lines (30 loc) · 1.33 KB
/
Hill Cipher Encryption
File metadata and controls
43 lines (30 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import numpy as np
def generate_key(n):
# Generate a random n x n matrix as the key
return np.random.randint(0, 26, size=(n, n))
def matrix_to_string(matrix):
return ''.join(''.join(chr((x % 26) + ord('A')) for x in row) for row in matrix)
def string_to_matrix(text, n):
return [[ord(char) - ord('A') for char in text[i:i+n]] for i in range(0, len(text), n)]
def encrypt_hill(message, key):
n = len(key)
# Pad the message if its length is not a multiple of n
message += 'X' * (n - len(message) % n) if len(message) % n != 0 else ''
message_matrix = string_to_matrix(message, n)
key_matrix = np.array(key)
encrypted_matrix = np.dot(message_matrix, key_matrix) % 26
encrypted_text = matrix_to_string(encrypted_matrix)
return encrypted_text
if __name__ == "__main__":
# Get plaintext input from the user
plaintext = input("Enter the plaintext message: ").upper()
# Generate a random key matrix
key_size = int(input("Enter the size of the key matrix (e.g., 2 for 2x2, 3 for 3x3): "))
key = generate_key(key_size)
# Encrypt the message using Hill cipher
ciphertext = encrypt_hill(plaintext, key)
# Display the results
print("\nGenerated Key Matrix:")
print(key)
print("\nOriginal Message:", plaintext)
print("Encrypted Message:", ciphertext)