classPlayfair:#创建一个类 #同行右移,同列下移,矩形对角 def__init__(self, key): # 生成矩阵(I/J合并) s = [] for c in (key.upper().replace('J', 'I') + "ABCDEFGHIKLMNOPQRSTUVWXYZ"): if c notin s: s.append(c) self.m = [s[i:i + 5] for i inrange(0, 25, 5)] #生成步长为5的序列,得到5*5的矩阵 self.p = {c: (i // 5, i % 5) for i, c inenumerate(s)} #生成字典,字母与坐标配对
defencrypt(self, txt): txt = ''.join(c for c in txt.upper().replace('J', 'I') if c.isalpha()) # 插入X处理重复和奇偶 i = 0 pairs = [] while i < len(txt): a = txt[i] b = txt[i + 1] if i + 1 < len(txt) else'X' if a == b: pairs.append(a + 'X') i += 1 else: pairs.append(a + b) i += 2 return''.join(self._pair(a, b) for a, b in pairs)
defdecrypt(self, txt): txt = txt.upper().replace('J', 'I') #将输入转大写,同时因为i j合并,将j换成i pairs = [txt[i:i + 2] for i inrange(0, len(txt), 2)] result = [] for a, b in pairs: r1, c1 = self.p[a] r2, c2 = self.p[b] if r1 == r2: result.append(self.m[r1][(c1 - 1) % 5] + self.m[r2][(c2 - 1) % 5]) elif c1 == c2: result.append(self.m[(r1 - 1) % 5][c1] + self.m[(r2 - 1) % 5][c2]) else: result.append(self.m[r1][c2] + self.m[r2][c1]) return''.join(result).replace('X', '') # 简化处理
# 使用 key=input("请输入密钥:") p = Playfair(key) etext=input("请输入待加密文本:") c = p.encrypt(etext) print(f"密文: {c}") dtext=input("请输入待解密文本:") d = p.decrypt(dtext) print(f"明文: {d}")