c语言或python playfair解密,程序运行后将结果保存在txt文件
时间: 2023-05-17 08:07:32 浏览: 95
这是一个编程类的问题,我可以回答。以下是一个 Python 的 Playfair 解密程序,它将结果保存在名为 output.txt 的文本文件中:
```python
import re
def decrypt(ciphertext, key):
# 生成 Playfair 矩阵
matrix = [['' for x in range(5)] for y in range(5)]
key = re.sub(r'[^a-zA-Z]', '', key).upper()
key = key.replace('J', 'I')
key += 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
key = ''.join(sorted(set(key), key=key.index))
i, j = 0, 0
for ch in key:
matrix[i][j] = ch
j += 1
if j == 5:
i += 1
j = 0
# 解密
plaintext = ''
ciphertext = re.sub(r'[^a-zA-Z]', '', ciphertext).upper()
ciphertext = re.sub(r'([A-Z])\1', r'\1X\1', ciphertext)
if len(ciphertext) % 2 == 1:
ciphertext += 'X'
for i in range(0, len(ciphertext), 2):
a, b = ciphertext[i], ciphertext[i+1]
arow, acol = find(matrix, a)
brow, bcol = find(matrix, b)
if arow == brow:
plaintext += matrix[arow][(acol-1)%5] + matrix[brow][(bcol-1)%5]
elif acol == bcol:
plaintext += matrix[(arow-1)%5][acol] + matrix[(brow-1)%5][bcol]
else:
plaintext += matrix[arow][bcol] + matrix[brow][acol]
return plaintext
def find(matrix, ch):
for i in range(5):
for j in range(5):
if matrix[i][j] == ch:
return i, j
ciphertext = input('请输入密文:')
key = input('请输入密钥:')
plaintext = decrypt(ciphertext, key)
with open('output.txt', 'w') as f:
f.write(plaintext)
print('解密结果已保存在 output.txt 文件中。')
```
你可以将这个程序保存为 playfair.py 并在命令行中运行它,输入密文和密钥即可。
阅读全文