python函数实现栅栏加密解密
时间: 2024-11-22 16:08:39 浏览: 6
python实现凯撒密码加密解密
5星 · 资源好评率100%
Python中可以使用Fence cipher(栅栏密码)这种简单的替换式加密技术来加密和解密信息。Fence cipher通过将明文按行或列排列成矩阵,然后按照特定规则移动字符来实现加密。下面是一个基本的实现示例:
```python
def fence_encrypt(text, rows):
# 检查输入是否合法
if not text or not isinstance(text, str) or rows <= 0:
return "Invalid input"
encrypted_text = []
matrix = [[] for _ in range(rows)]
# 将文本拆分为单个字符并放入矩阵
row_index = 0
for char in text:
matrix[row_index].append(char)
row_index += 1
if row_index == rows:
row_index = 0
# 按照矩阵行顺序组合字符
for i in range(len(matrix)):
for j in range(i, len(matrix[0])):
encrypted_text.append(matrix[j][i])
return ''.join(encrypted_text)
def fence_decrypt(encrypted_text, rows):
if not encrypted_text or not isinstance(encrypted_text, str) or rows <= 0:
return "Invalid input"
original_matrix = [[] for _ in range(rows)]
decrypted_text = []
# 逆向填充矩阵
col_index = 0
for char in encrypted_text:
original_matrix[col_index].append(char)
col_index += 1
if col_index == rows:
col_index = 0
# 按照矩阵列顺序组合字符,恢复原始文本
for i in range(len(original_matrix)):
for j in range(i, len(original_matrix[0])):
decrypted_text.append(original_matrix[i][j])
return ''.join(decrypted_text)
# 示例
plaintext = "Hello, World!"
rows = 3
encrypted = fence_encrypt(plaintext, rows)
decrypted = fence_decrypt(encrypted, rows)
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
阅读全文