栅栏密码python代码
时间: 2024-09-21 11:06:48 浏览: 70
栅栏密码(Fence Pattern)是一种简单的加密技术,它将明文按照一定的规则隔行排列形成一个新的矩阵。下面是一个简单的Python代码示例,演示如何创建和解密栅栏密码:
```python
def encrypt(text, rows):
encrypted_text = [''] * rows
step = 2 if rows % 2 == 0 else 1
for i in range(len(text)):
column = i // step
encrypted_text[column] += text[i]
return '\n'.join(encrypted_text)
def decrypt(encrypted_text, rows):
original_text = ''
step = 2 if rows % 2 == 0 else 1
lines = encrypted_text.split('\n')
for line in lines:
for i in range(0, len(line), step):
original_text += line[i]
return original_text
# 示例
plaintext = "Hello, World!"
rows = 3 # 根据需求设置行数
encrypted = encrypt(plaintext, rows)
decrypted = decrypt(encrypted, rows)
print("Encrypted Text:")
print(encrypted)
print("\nDecrypted Text:")
print(decrypted)
阅读全文