-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest3.py
More file actions
56 lines (45 loc) · 1.87 KB
/
test3.py
File metadata and controls
56 lines (45 loc) · 1.87 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
44
45
46
47
48
49
50
51
52
53
54
55
56
import numpy as np
# Function to generate the key matrix
def generate_key_matrix(key, n):
key_matrix = np.zeros((n, n), dtype=int)
k = 0
for i in range(n):
for j in range(n):
key_matrix[i][j] = ord(key[k]) % 65
k += 1
return key_matrix
# Function to encrypt plaintext
def hill_cipher_encrypt(plaintext, key_matrix, n):
plaintext = plaintext.upper().replace(" ", "")
plaintext = [ord(char) % 65 for char in plaintext]
plaintext = np.array(plaintext)
padding_length = n - len(plaintext) % n
if padding_length != n:
plaintext = np.append(plaintext, np.zeros(padding_length, dtype=int))
ciphertext = ""
for i in range(0, len(plaintext), n):
block = np.array(plaintext[i:i+n])
encrypted_block = np.dot(key_matrix, block) % 26
ciphertext += "".join([chr(char + 65) for char in encrypted_block])
return ciphertext
# Function to decrypt ciphertext
def hill_cipher_decrypt(ciphertext, key_matrix, n):
inverse_key_matrix = np.linalg.inv(key_matrix)
inverse_key_matrix = np.round(inverse_key_matrix * np.linalg.det(key_matrix)).astype(int) % 26
decrypted_text = ""
for i in range(0, len(ciphertext), n):
block = np.array([ord(char) % 65 for char in ciphertext[i:i+n]])
decrypted_block = np.dot(inverse_key_matrix, block) % 26
decrypted_text += "".join([chr(char + 65) for char in decrypted_block])
return decrypted_text
# Example usage
key = "GYBNQKURP"
plaintext = "HELLO"
n = 3 # Size of the key matrix (must be a perfect square)
key_matrix = generate_key_matrix(key, n)
print("Key Matrix:")
print(key_matrix)
ciphertext = hill_cipher_encrypt(plaintext, key_matrix, n)
print("Encrypted:", ciphertext)
decrypted_text = hill_cipher_decrypt(ciphertext, key_matrix, n)
print("Decrypted:", decrypted_text)