playfair python加密和解密
时间: 2023-09-24 09:09:58 浏览: 233
playfair加密解密
5星 · 资源好评率100%
以下是 Python 实现的 Playfair 加密和解密:
加密:
```python
def playfair_encrypt(key, plaintext):
# 将明文中的 J 替换为 I
plaintext = plaintext.replace("J", "I")
# 构造 Playfair 方阵
matrix = []
chars = list(key.upper()) + [chr(i) for i in range(65, 91) if chr(i) != "J" and chr(i) not in key.upper()]
for i in range(0, 25, 5):
matrix.append(chars[i:i+5])
# 将明文分块
plaintext_blocks = []
i = 0
while i < len(plaintext):
if i == len(plaintext) - 1 or plaintext[i] == plaintext[i+1]:
plaintext_blocks.append(plaintext[i] + "X")
i += 1
else:
plaintext_blocks.append(plaintext[i:i+2])
i += 2
# 加密每个明文块
ciphertext_blocks = []
for block in plaintext_blocks:
row1, col1 = divmod(matrix.index(block[0]), 5)
row2, col2 = divmod(matrix.index(block[1]), 5)
if row1 == row2:
# 同一行
ciphertext_blocks.append(matrix[row1][(col1 + 1) % 5] + matrix[row2][(col2 + 1) % 5])
elif col1 == col2:
# 同一列
ciphertext_blocks.append(matrix[(row1 + 1) % 5][col1] + matrix[(row2 + 1) % 5][col2])
else:
# 不同行不同列
ciphertext_blocks.append(matrix[row1][col2] + matrix[row2][col1])
# 将密文块拼接成密文
ciphertext = "".join(ciphertext_blocks)
return ciphertext
```
解密:
```python
def playfair_decrypt(key, ciphertext):
# 构造 Playfair 方阵
matrix = []
chars = list(key.upper()) + [chr(i) for i in range(65, 91) if chr(i) != "J" and chr(i) not in key.upper()]
for i in range(0, 25, 5):
matrix.append(chars[i:i+5])
# 解密每个密文块
plaintext_blocks = []
for i in range(0, len(ciphertext), 2):
row1, col1 = divmod(matrix.index(ciphertext[i]), 5)
row2, col2 = divmod(matrix.index(ciphertext[i+1]), 5)
if row1 == row2:
# 同一行
plaintext_blocks.append(matrix[row1][(col1 - 1) % 5] + matrix[row2][(col2 - 1) % 5])
elif col1 == col2:
# 同一列
plaintext_blocks.append(matrix[(row1 - 1) % 5][col1] + matrix[(row2 - 1) % 5][col2])
else:
# 不同行不同列
plaintext_blocks.append(matrix[row1][col2] + matrix[row2][col1])
# 将明文块拼接成明文
plaintext = "".join(plaintext_blocks)
# 将明文中的 X 替换为原来的字母
plaintext = plaintext.replace("X", "")
return plaintext
```
使用示例:
```python
key = "playfair example"
plaintext = "Hide the gold in the tree stump"
ciphertext = playfair_encrypt(key, plaintext)
print(ciphertext)
# 输出:BMNDZBXDNABEKUDMUIXMMOUVIF
```
```python
key = "playfair example"
ciphertext = "BMNDZBXDNABEKUDMUIXMMOUVIF"
plaintext = playfair_decrypt(key, ciphertext)
print(plaintext)
# 输出:HIDETHEGOLDINTHETREXESTUMP
```
阅读全文