关键字密码(Nihilist)
- 加密对象:小写字母
- 原理:
- 是棋盘密码的变种,相对于棋盘密码,改密码的密码表是变化的,相对于关键字而变化
- 关键字就是一
- 种秘钥,由字母组成,由加密双方约定而成。密码表有25个位置,依次不重复的填入秘钥,在不重复的填入a~z.
- 如:秘钥为linux,则密码表为:
1 |
2 | 3 | 4 | 5 | |
1 | l | i | n | u | x |
2 | a | b | c | d | e |
3 | f | g | h | k | m |
4 | o | p | q | r | s |
5 | t | v | w | y | z |
- 在将明文的每个字符通过查表找出行号和列号,行号在前,列号在后就组成了密文,最后将所有字符的密文以空格隔开组成最后的密文
- 如:在"linux"为关键字的情况
- 下,加密"abc"
- a -> 21
- b -> 22
- c -> 23
- 故密文为: “21 22 23”
- 代码
# write by 2021/7/6 # 关键字密码,一种棋盘密码的变种 def create_table(key): key = key + "abcdefghiklmnopqrstuvwxyz" table = "" for i in key.replace("j", "i"): if i not in table: table += i return table def encrypt_nihilist(string, key): ciphertext = "" table = create_table(key) for i in string.replace("j", "i").replace(" ", ""): if i in table: index = table.index(i) ciphertext += str(index // 5 + 1) + str(index % 5 + 1) + " " else: return -1 return ciphertext.strip() def decrypt_nihilist(string, key): plaintext = "" table = create_table(key) lis = string.split(" ") try: for i in lis: index = (int(i[0]) - 1) * 5 + int(i[1]) - 1 plaintext += table[index] if table[index] == "i": plaintext += "(j)" except: return -1 return plaintext if __name__ == '__main__': ciphertext_ = encrypt_nihilist("linux", "linux") plaintext_ = decrypt_nihilist(ciphertext_, "linux") print(f"{plaintext_}: {ciphertext_}")