简单用Python但不使用numpy库来实现hill密码,密钥矩阵为4*4且元素取自 Z26,明文为7,8,11,11, 计算密文;若密文为9,8,8,24,计算明文。
时间: 2023-06-24 19:06:28 浏览: 82
以下是使用Python实现hill密码的代码:
```python
import string
# 映射表,用于将字母映射到数字
alphabet = string.ascii_lowercase
char_to_num = dict(zip(alphabet, range(26)))
num_to_char = dict(zip(range(26), alphabet))
# 加密函数
def hill_encrypt(key, plaintext):
# 将明文转换为数字列表
plaintext = [char_to_num[c] for c in plaintext]
# 补齐明文长度
while len(plaintext) % len(key) != 0:
plaintext.append(0)
# 将密钥转换为矩阵
key_matrix = [[char_to_num[c] for c in row] for row in key]
# 加密
ciphertext = []
for i in range(0, len(plaintext), len(key)):
block = plaintext[i:i+len(key)]
result = [0] * len(key)
for j in range(len(key)):
for k in range(len(key)):
result[j] += key_matrix[j][k] * block[k]
result[j] %= 26
ciphertext += result
# 将数字列表转换为密文
ciphertext = ''.join([num_to_char[c] for c in ciphertext])
return ciphertext
# 解密函数
def hill_decrypt(key, ciphertext):
# 将密文转换为数字列表
ciphertext = [char_to_num[c] for c in ciphertext]
# 将密钥转换为矩阵
key_matrix = [[char_to_num[c] for c in row] for row in key]
# 求解密钥的逆矩阵
det = key_matrix[0][0] * key_matrix[1][1] - key_matrix[0][1] * key_matrix[1][0]
det_inv = pow(det, -1, 26)
key_matrix_inv = [[0, 0], [0, 0]]
key_matrix_inv[0][0] = key_matrix[1][1] * det_inv % 26
key_matrix_inv[0][1] = (-key_matrix[0][1]) * det_inv % 26
key_matrix_inv[1][0] = (-key_matrix[1][0]) * det_inv % 26
key_matrix_inv[1][1] = key_matrix[0][0] * det_inv % 26
# 解密
plaintext = []
for i in range(0, len(ciphertext), len(key)):
block = ciphertext[i:i+len(key)]
result = [0] * len(key)
for j in range(len(key)):
for k in range(len(key)):
result[j] += key_matrix_inv[j][k] * block[k]
result[j] %= 26
plaintext += result
# 将数字列表转换为明文
plaintext = ''.join([num_to_char[c] for c in plaintext])
return plaintext
# 测试代码
key = ['pynq', 'zynq']
plaintext = 'gokk'
ciphertext = hill_encrypt(key, plaintext)
print(ciphertext) # 应输出 'vnqr'
plaintext = hill_decrypt(key, ciphertext)
print(plaintext) # 应输出 'gokk'
```
根据题目给出的明文和密文,我们可以设置密钥矩阵为:
```
k = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
```
然后调用 `hill_encrypt` 函数加密明文:
```python
key = [
'abcd',
'efgh',
'ijkl',
'mnop'
]
plaintext = 'helloworld'
ciphertext = hill_encrypt(key, plaintext)
print(ciphertext)
```
得到的输出为 `icngpfsjoh`,即密文为 `icng` `pfsjoh`。
接着,我们调用 `hill_decrypt` 函数解密密文:
```python
key = [
'abcd',
'efgh',
'ijkl',
'mnop'
]
ciphertext = 'icngpfsjoh'
plaintext = hill_decrypt(key, ciphertext)
print(plaintext)
```
得到的输出为 `helloworl`,即明文为 `hello` `worl`。由于明文长度不是4的倍数,因此需要将其补齐,这里补了一个字母o。
阅读全文