棋盘密码(Polybius)
- 加密对象:小写字母
- 原理:
- 棋盘密码是一种查表加密法,密码表如下:
1 | 2 | 3 | 4 | 5 | |
1 | a | b | c | d | e |
2 | f | g | h | i,j | k |
3 | l | m | n | o | p |
4 | q | r | s | t | u |
5 | v | w | x | y | z |
- 密文就是字符在密码表里面对应的横纵坐标,如"a"加密为"11", “y"加密为"54”
- 特点:
- 数字没两个一组
- 数字范围为1~5
- 实例:加密字符串"polybius":
查表替换: “p"对应"35”, “o"对应"34”, “l"对应"31”, “y"对应"54”, “b"对应"12”, “i"对应"24”, “u"对应"45”, “s"对应"43”。
故密文为: “35 34 31 54 12 24 45 43”
代码
# write by 2021/7/6 # 棋盘密码 # i 和 j 在同一个格子 CHECKERBOARD = "abcdefghiklmnopqrstuvwxyz" def encrypt_polybius(string): ciphertext = "" for i in string.replace("j", "i").replace(" ", ""): if i in CHECKERBOARD: index = CHECKERBOARD.index(i) ciphertext += str(index // 5 + 1) + str(index % 5 + 1) + " " else: return -1 return ciphertext.strip() def decrypt_polybius(string): plaintext = "" lis = string.split(" ") try: for i in lis: index = (int(i[0])-1)*5+int(i[1])-1 plaintext += CHECKERBOARD[index] if index == 9: plaintext += "(j)" except: return -1 return plaintext if __name__ == '__main__': ciphertext_ = encrypt_polybius("polybius") print(ciphertext_) plaintext_ = decrypt_polybius(ciphertext_) print(f"{plaintext_}: {ciphertext_}")