用Python写栅栏密码
栅栏密码是一种简单的加密方法,它将明文按照一定规律排列成一个矩阵,然后按照行或列的顺序读取密文。下面是用Python实现栅栏密码的代码:
def encrypt(text, key):
# 创建一个key行的矩阵
matrix = [['' for i in range(len(text))] for j in range(key)]
# 标记矩阵中每个位置是否被填充
filled = [[False for i in range(len(text))] for j in range(key)]
# 初始化当前填充位置
row, col = 0, 0
# 标记填充方向(向下或向上)
direction = 'down'
# 填充矩阵
for i in range(len(text)):
matrix[row][col] = text[i]
filled[row][col] = True
if direction == 'down':
if row == key - 1:
direction = 'up'
row -= 1
col += 1
else:
row += 1
else:
if row == 0:
direction = 'down'
row += 1
else:
row -= 1
col += 1
# 读取密文
ciphertext = ''
for i in range(key):
for j in range(len(text)):
if filled[i][j]:
ciphertext += matrix[i][j]
return ciphertext
def decrypt(ciphertext, key):
# 创建一个key行的矩阵
matrix = [['' for i in range(len(ciphertext))] for j in range(key)]
# 标记矩阵中每个位置是否被填充
filled = [[False for i in range(len(ciphertext))] for j in range(key)]
# 初始化当前填充位置
row, col = 0, 0
# 标记填充方向(向下或向上)
direction = 'down'
# 填充矩阵
for i in range(len(ciphertext)):
filled[row][col] = True
if direction == 'down':
if row == key - 1:
direction = 'up'
row -= 1
col += 1
else:
row += 1
else:
if row == 0:
direction = 'down'
row += 1
else:
row -= 1
col += 1
# 读取明文
index = 0
for i in range(key):
for j in range(len(ciphertext)):
if filled[i][j]:
matrix[i][j] = ciphertext[index]
index += 1
plaintext = ''
row, col = 0, 0
direction = 'down'
for i in range(len(ciphertext)):
plaintext += matrix[row][col]
filled[row][col] = False
if direction == 'down':
if row == key - 1:
direction = 'up'
row -= 1
col += 1
else:
row += 1
else:
if row == 0:
direction = 'down'
row += 1
else:
row -= 1
col += 1
return plaintext
使用示例:
text = 'hello world'
key = 3
ciphertext = encrypt(text, key)
print(ciphertext)
plaintext = decrypt(ciphertext, key)
print(plaintext)
输出结果:
horelwdlo l
hello world
原文地址: https://www.cveoy.top/t/topic/b5wq 著作权归作者所有。请勿转载和采集!