Python实现Playfair密码算法
时间: 2023-11-05 08:30:44 浏览: 110
Playfair密码算法是一种古老的加密技术,它使用一个5×5的矩阵来加密和解密文本。以下是使用Python实现Playfair密码算法的示例代码:
```python
# 定义 Playfair 加密函数
def playfair_encrypt(plain_text, key):
# 生成密钥矩阵
key = key.replace(" ", "").upper()
key_matrix = list(key)
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
for letter in alphabet:
if letter not in key_matrix:
key_matrix.append(letter)
# 将明文转换成双字母对
plain_text = plain_text.upper().replace(" ", "")
plain_text_pairs = []
i = 0
while i < len(plain_text):
if i == len(plain_text) - 1 or plain_text[i] == plain_text[i+1]:
plain_text_pairs.append(plain_text[i] + "X")
i += 1
else:
plain_text_pairs.append(plain_text[i:i+2])
i += 2
# 加密双字母对
cipher_text = ""
for pair in plain_text_pairs:
row1, col1 = divmod(key_matrix.index(pair[0]), 5)
row2, col2 = divmod(key_matrix.index(pair[1]), 5)
if row1 == row2:
cipher_text += key_matrix[row1*5+(col1+1)%5] + key_matrix[row2*5+(col2+1)%5]
elif col1 == col2:
cipher_text += key_matrix[((row1+1)%5)*5+col1] + key_matrix[((row2+1)%5)*5+col2]
else:
cipher_text += key_matrix[row1*5+col2] + key_matrix[row2*5+col1]
return cipher_text
# 定义 Playfair 解密函数
def playfair_decrypt(cipher_text, key):
# 生成密钥矩阵
key = key.replace(" ", "").upper()
key_matrix = list(key)
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
for letter in alphabet:
if letter not in key_matrix:
key_matrix.append(letter)
# 解密双字母对
plain_text = ""
for i in range(0, len(cipher_text), 2):
row1, col1 = divmod(key_matrix.index(cipher_text[i]), 5)
row2, col2 = divmod(key_matrix.index(cipher_text[i+1]), 5)
if row1 == row2:
plain_text += key_matrix[row1*5+(col1-1)%5] + key_matrix[row2*5+(col2-1)%5]
elif col1 == col2:
plain_text += key_matrix[((row1-1)%5)*5+col1] + key_matrix[((row2-1)%5)*5+col2]
else:
plain_text += key_matrix[row1*5+col2] + key_matrix[row2*5+col1]
# 去掉添加的 X 字符
plain_text = plain_text.replace("X", "")
return plain_text
# 测试
plain_text = "hello world"
key = "playfair example"
cipher_text = playfair_encrypt(plain_text, key)
print(cipher_text)
print(playfair_decrypt(cipher_text, key))
```
在上面的示例中,`playfair_encrypt`函数使用给定的密钥矩阵加密明文,而`playfair_decrypt`函数使用相同的密钥矩阵解密密文。注意,为了使明文的长度为偶数,如果有两个连续的相同字母,我们在它们之间添加一个 X 字符。在解密时,我们需要去掉这些添加的 X 字符。
阅读全文