pycharm代码改进 hill密码随机输入一段明文加密或者密文解密
时间: 2024-02-27 14:51:38 浏览: 206
hill密码,加密过程
以下是改进后的 Hill 密码加密和解密代码:
```python
import numpy as np
# 加密函数
def hill_encrypt(plain_text, key):
# 将明文转换成数字向量
plain_text = [ord(c) - ord('a') for c in plain_text.lower() if c.isalpha()]
plain_text = np.array(plain_text)
# 将密钥转换成矩阵
key = np.array(key)
# 将数字向量按照密钥的大小分成若干个块
block_size = key.shape[0]
num_blocks = int(np.ceil(len(plain_text) / block_size))
plain_text = np.pad(plain_text, (0, num_blocks * block_size - len(plain_text)), 'constant')
plain_text = plain_text.reshape(-1, block_size)
# 对每个块进行加密
cipher_text = []
for block in plain_text:
cipher_block = np.mod(key @ block, 26)
cipher_text += cipher_block.tolist()
# 将密文转换成字符串
cipher_text = ''.join([chr(c + ord('a')) for c in cipher_text])
return cipher_text
# 解密函数
def hill_decrypt(cipher_text, key):
# 将密文转换成数字向量
cipher_text = [ord(c) - ord('a') for c in cipher_text.lower() if c.isalpha()]
cipher_text = np.array(cipher_text)
# 将密钥转换成矩阵
key = np.array(key)
# 将数字向量按照密钥的大小分成若干个块
block_size = key.shape[0]
num_blocks = int(np.ceil(len(cipher_text) / block_size))
cipher_text = np.pad(cipher_text, (0, num_blocks * block_size - len(cipher_text)), 'constant')
cipher_text = cipher_text.reshape(-1, block_size)
# 对每个块进行解密
plain_text = []
for block in cipher_text:
# 计算矩阵的逆
det = np.linalg.det(key)
inv_key = np.mod(np.round(det * np.linalg.inv(key)), 26)
plain_block = np.mod(inv_key @ block, 26)
plain_text += plain_block.tolist()
# 将明文转换成字符串
plain_text = ''.join([chr(c + ord('a')) for c in plain_text])
return plain_text
# 生成随机明文
def generate_random_text(length):
# 生成随机明文
text = ""
for i in range(length):
text += chr(np.random.randint(ord('a'), ord('z') + 1))
return text
# 生成随机密钥
def generate_random_key(size):
return np.random.randint(0, 26, (size, size))
# 测试代码
key = generate_random_key(2)
plain_text = generate_random_text(10)
cipher_text = hill_encrypt(plain_text, key)
decrypted_plain_text = hill_decrypt(cipher_text, key)
print("明文:", plain_text)
print("密钥:", key)
print("密文:", cipher_text)
print("解密后明文:", decrypted_plain_text)
```
改进后的代码增加了随机生成明文和密钥的函数 `generate_random_text` 和 `generate_random_key`,使用了 `np.random.randint` 函数代替了 Python 的 `random` 库,减少了硬编码。同时,函数中还增加了对明文和密文的过滤,只保留字母字符,避免了在加密和解密过程中出现非法字符的问题。
阅读全文