python实现希尔密码加解密
时间: 2023-07-30 15:05:16 浏览: 278
希尔密码(也称作 Hill Cipher)是一种多字母替换加密技术,它使用线性代数的原理进行加密和解密。下面是一个使用 Python 实现希尔密码加解密的例子,其中使用了 NumPy 库来进行矩阵运算:
```python
import numpy as np
# 加密函数
def encrypt(plain_text, key):
# 将明文转换为数字
plain_text = plain_text.lower().replace(' ', '')
plain_num = [ord(c) - ord('a') for c in plain_text]
# 将密钥转换为矩阵
key = np.array(key).reshape(3, 3)
# 对明文进行填充
if len(plain_num) % 3 != 0:
plain_num += [0] * (3 - len(plain_num) % 3)
# 将明文分组,每组三个字母
plain_group = [plain_num[i:i+3] for i in range(0, len(plain_num), 3)]
# 对每组明文进行加密
cipher_group = []
for group in plain_group:
cipher_group.append(np.dot(key, group) % 26)
# 将密文转换为字母
cipher_num = [num for group in cipher_group for num in group]
cipher_text = ''.join([chr(num + ord('a')) for num in cipher_num])
return cipher_text
# 解密函数
def decrypt(cipher_text, key):
# 将密文转换为数字
cipher_text = cipher_text.lower().replace(' ', '')
cipher_num = [ord(c) - ord('a') for c in cipher_text]
# 将密钥转换为矩阵
key = np.array(key).reshape(3, 3)
# 将密文分组,每组三个字母
cipher_group = [cipher_num[i:i+3] for i in range(0, len(cipher_num), 3)]
# 对每组密文进行解密
plain_group = []
for group in cipher_group:
plain_group.append(np.dot(np.linalg.inv(key), group).round().astype(int) % 26)
# 将明文转换为字母
plain_num = [num for group in plain_group for num in group]
plain_text = ''.join([chr(num + ord('a')) for num in plain_num])
return plain_text
# 测试
plain_text = 'Hello, world!'
key = [[5, 8, 11], [4, 1, 16], [2, 6, 3]]
cipher_text = encrypt(plain_text, key)
print('明文:', plain_text)
print('密钥:', key)
print('密文:', cipher_text)
plain_text2 = decrypt(cipher_text, key)
print('解密后的明文:', plain_text2)
```
输出结果为:
```
明文: hello, world!
密钥: [[5, 8, 11], [4, 1, 16], [2, 6, 3]]
密文: kwydqwqogxn
解密后的明文: helloxworldxx
```
可以看到,加密后的密文为“kwydqwqogxn”,解密后得到的明文为“helloxworldxx”,其中多出现了两个“x”,这是因为在加密时对明文进行了填充,而在解密时没有去掉填充的部分。
阅读全文