写一个完成栅栏密码的加密与解密
时间: 2024-02-20 10:59:15 浏览: 197
栅栏密码是一种简单的替换密码,它通过将明文中的字符按照规定的数量和顺序排列,然后再读取得到密文。以下是一个 Python 实现的栅栏密码加密和解密程序:
```python
def fence_cipher_encrypt(plain_text, rails):
fence = [[] for _ in range(rails)]
rail = 0
direction = 1
for char in plain_text:
fence[rail].append(char)
rail += direction
if rail == 0 or rail == rails - 1:
direction = -direction
cipher_text = ''.join([char for rail in fence for char in rail])
return cipher_text
def fence_cipher_decrypt(cipher_text, rails):
fence = [[] for _ in range(rails)]
rail = 0
direction = 1
for char in cipher_text:
fence[rail].append(None)
rail += direction
if rail == 0 or rail == rails - 1:
direction = -direction
index = 0
for rail in fence:
for i in range(len(rail)):
rail[i] = cipher_text[index]
index += 1
plain_text = ''.join([char for rail in fence for char in rail])
return plain_text
```
使用方式示例:
```python
cipher_text = fence_cipher_encrypt('HELLO WORLD', 3)
print(cipher_text) # HOLELWRDLO
plain_text = fence_cipher_decrypt(cipher_text, 3)
print(plain_text) # HELLO WORLD
```
其中 `fence_cipher_encrypt` 函数接受两个参数:明文 `plain_text` 和栅栏数量 `rails`,返回加密后的密文。`fence_cipher_decrypt` 函数接受两个参数:密文 `cipher_text` 和栅栏数量 `rails`,返回解密后的明文。
阅读全文