该密码是一种移位密码,将明文的顺序按照某种规则打乱
该密码需要一个秘钥,即在加密过程中需要使用到的列数,将明文按顺序排成列,例如:列数为4,明文为: “i will beat you this day”,
iwillbeatyouthisday然后按照列顺序组成明文,如表密文为: 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 // 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 plaintextif __name__ == '__main__': key_ = 4 ciphertext_ = encrypt_fence("i will beat you this day", key_) plaintext_ = decrypt_fence(ciphertext_, key_) print(f"{plaintext_} : {ciphertext_}")