python提供了普莱菲尔密码的加解密包:pycipher
下载地址:
安装:python setup.py install
基本使用:
from pycipher import Playfairprint Playfair('CULTREABDFGHIKMNOPQSVWXYZ').encipher('THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG')print Playfair('CULTREABDFGHIKMNOPQSVWXYZ').decipher('UKDNLHTGFLWUSEPWHLISNPCGCRGAUBVZAQIV')
输出:
UKDNLHTGFLWUSEPWHLISNPCGCRGAUBVZAQIV
THEQUICKBROWNFOXIUMPSOVERTHELAZYDOGX# *-* coding=utf-8*-*import stringdef key_deal(key): strs = '' key = string.lower(key) for i in key: if i in strs: pass else: strs = strs + i return strsdef get_matrix(key): matrix = [([''] * 5) for i in range(5)] temp = key_deal(key) # print temp charset = string.lowercase dic = {chr(i+96): i for i in range(1, 27)} a = -1 b = -1 k = 0 m = 0 for j in range(5): # 列 for i in range(5): # 行 if k < len(temp): if dic.get(temp[k]) == 9 or dic.get(temp[k]) == 10: a = i b = j matrix[i][j] = temp[k] # print i, j, a, b, k, temp[k], matrix[i][j] k += 1 continue else: matrix[i][j] = temp[k] # print i, j, a, b, k, temp[k], matrix[i][j] k += 1 continue else: while m < len(dic): if dic.get(charset[m]) == 9 or dic.get(charset[m]) == 10: if a != -1 or b != -1: matrix[a][b] = matrix[a][b] + charset[m] m += 1 # matrix[i][j]还没定,需要继续 else: matrix[i][j] = charset[m] a = i b = j # print i, j, a, b, m, charset[m], matrix[i][j] m += 1 break else: if charset[m] in temp: m += 1 else: matrix[i][j] = charset[m] # print i, j, a, b, m, charset[m], matrix[i][j] m += 1 break # for i in range(5): # for j in range(5): # print i, j, matrix[i][j] # return matrixif __name__ == '__main__': key = 'CULTURE' matrix = get_matrix(key) plaintext = 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG' strs = string.lower(''.join(plaintext.split(' '))) if len(strs) % 2 != 0: strs += 'x' print strs