# write by 2021/8/5
# 栅栏密码
def encrypt_fence(string, key):
ciphertext = ""
temp = []
for i in range(key):
temp.append("")
for index, i in enumerate(string):
temp[index % key] += i
# print("".join(temp))
ciphertext = "".join(temp)
return ciphertext
def decrypt_fence(string, key):
plaintext = ""
length = len(string)
min_row = length // key
max_num = length % key
temp = []
index = 0
for i in range(key):
if i < max_num:
temp.append(string[index:index+min_row+1])
index += min_row + 1
else:
temp.append(string[index:index+min_row])
index += min_row
# print(temp)
for i in range(length):
plaintext += temp[i % key][i // key]
return plaintext
if __name__ == '__main__':
key_ = 4
ciphertext_ = encrypt_fence("i will beat you this day", key_)
plaintext_ = decrypt_fence(ciphertext_, key_)
print(f"{plaintext_} : {ciphertext_}")