# 进行分组,如果相邻字母相同就在该组的第一个字母后加入X后重新分组, 如果第一个字母为X则加Q i = 0 sum = 0# 计算字母数 while i < len(plaintext): ifnot plaintext[i].isalpha(): i += 1 else: if i == len(plaintext) - 1: sum += 1 break whilenot plaintext[i+1].isalpha() and i < len(plaintext): i += 1 if plaintext[i] == plaintext[i+1]: ch = 'X'if plaintext[i] != 'X'else'Q' plaintext = plaintext[:i+1] + ch + plaintext[i+1:] i += 2 sum += 2
# 如果明文处理后为奇数就在最后加入X ifsum % 2: for i inrange(len(plaintext)-1, -1, -1): if plaintext[i].isalpha(): ch = 'X'if plaintext[i] != 'X'else'Q' plaintext += ch break
ciphertext = "" i = 0 while i < len(plaintext): ifnot plaintext[i].isalpha(): ciphertext += plaintext[i] i += 1 continue x0, y0 = self.get_index(plaintext[i])
tmp = "" whilenot plaintext[i+1].isalpha() and i < len(plaintext): tmp += plaintext[i+1] i += 1
if __name__ == "__main__": key = "playfair example" plaintext = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" playfair = Playfair(key) ciphertext = playfair.encrypt(plaintext) print(ciphertext) # ZBX OTRBN CIQVS LQE RTIFK QADI UDM AYWF OVQG plaintext = playfair.decrypt(ciphertext) print(plaintext) # THE QUICK BROWN FOX IUMPS OVER THE LAZY DOGX
The quick brown fox jumps over the lazy dog! ihxo{smzdodcikmodcismzd
解题思路
根据所给题目描述我们猜测The quick brown fox jumps over the lazy dog!就是所给密钥,我们用我们上述给的脚本直接进行解密,当然,要注意我们的脚本用的是大写,记得转换为小写即可
from Playfair import Playfair
key = "The quick brown fox jumps over the lazy dog!"
ciphertext = "ihxo{smzdodcikmodcismzd}"
playfair = Playfair(key)
plaintext = playfair.decrypt(ciphertext)
print(plaintext.lower())