栅栏密码(Fence crypto)
栅栏密码(Fence crypto)
-
加密对象: 所有字符
-
原理:
-
该密码是一种移位密码,将明文的顺序按照某种规则打乱
-
该密码需要一个秘钥,即在加密过程中需要使用到的列数,将明文按顺序排成列,例如:列数为4,明文为: “i will beat you this day”,
i w i l l b e a t y o u t h i s d a y -
然后按照列顺序组成明文,如表密文为: ileyt laohdw tuiaib sy
-
-
代码:
# 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 ciphertextdef decrypt_fence(string, key):plaintext = ""length = len(string)min_row = length // keymax_num = length % keytemp = []index = 0for i in range(key):if i < max_num:temp.append(string[index:index+min_row+1])index += min_row + 1else:temp.append(string[index:index+min_row])index += min_row# print(temp)for i in range(length):plaintext += temp[i % key][i // key]return plaintextif __name__ == '__main__':key_ = 4ciphertext_ = encrypt_fence("i will beat you this day", key_)plaintext_ = decrypt_fence(ciphertext_, key_)print(f"{plaintext_} : {ciphertext_}")