前面讲的不管是单码加密还是多码加密都属于单图加密,什么是单图加密和多图加密呢,简单来说单图加密就是一个字母加密一个字母,而多图加密就是一个字符组加密一个字符组。比如双图加密就是两个字母加密两个字母,这种加密的好处在于更加难被破解,单图对于一个字母加密最多26种(26个字母),而双图加密就有26*26种。Playfair就是一种经典的双图加密法。
Playfair先将密钥去除重复的字母和 j ,接着依次填入一个5*5的矩阵中,如矩阵还有空,则按字母表的顺序(除去 j )填满矩阵,比如密钥“telegream”形成下面的矩阵。
t e l g r
a m b c d
f h i k n
o p q s u
v w x y z
加密是要遵循下述规则:
- 若明文出现相同字母在一组,则在重复的明文字母中插入一个填充字母(一般为x,q)进行分隔后重新分组
- 若分组到最后一组时只有一个字母,则补充字母
- 若明文字母在矩阵中同行,则循环取其右边下一个字母为密文
- 若明文字母在矩阵中同列,则循环取其下边下一个字母为密文
- 若明文字母在矩阵中不同行不同列,则取其同行且与同组另一字母同列的字母为密
下面是python实现版本,写得有点乱
#对Playfair进行初始化
def init(key):
table = [[0 for i in range(5)]for j in range(5)]
index = [[0 for i in range(2)] for i in range(26)]
sign = [0 for i in range(26)]
colum = 0
j = 0
for i in range(len(key)):
if(key[i] == 'j' or sign[ord(key[i]) - 97] == 1):
continue
table[colum][j] = key[i]
index[ord(key[i]) - 97][0] = colum
index[ord(key[i]) - 97][1] = j
sign[ord(key[i]) - 97] = 1
j += 1
if(j == 5):
j = 0
colum += 1
i = 0
while colum < 5:
while j < 5:
while sign[i] == 1 or i == 9:
i += 1
table[colum][j] = chr(i + 97)
index[i][0] = colum
index[i][1] = j
j += 1
i += 1
colum += 1
j = 0
return table,index
#进行加密
def encrypt(tab,index,str):
ciphertext = ''
while str[0] == 'j':
str = str[:len(str)]
for i in range(1,len(str),1):
if(str[i] == 'j'):
str = str[:i] + 'i' + str[i + 1:]
continue
if(str[i - 1] == str[i]):
if(str[i - 1] == 'q'):
str = str[:i] + 'x' + str[i:]
str = str[:i] + 'q' + str[i:]
if(len(str) % 2):
str += 'x'
for i in range(0,len(str),2):
temp1 = ord(str[i]) - 97
temp2 = ord(str[i + 1]) - 97
x1 = index[temp1][0]
x2 = index[temp2][0]
y1 = index[temp1][1]
y2 = index[temp2][1]
if(x1 != x2 and y1 != y2):
ciphertext += tab[x1][y2]
ciphertext += tab[x2][y1]
elif x1 == x2:
if y1 == 4:
ciphertext += tab[x1][0]
else:
ciphertext += tab[x1][y1 + 1]
if y2 == 4:
ciphertext += tab[x2][0]
else:
ciphertext += tab[x2][y2 + 1]
else:
if x1 == 4:
ciphertext += tab[0][y1]
else:
ciphertext += tab[x1 + 1][y1]
if x2 == 4:
ciphertext += tab[0][y2]
else:
ciphertext += tab[x2 + 1][y2]
return ciphertext
#用telegram作为密钥加密明文s
def main():
tab,index = init('telegram')
s = 'nexttimejaytrysomethingdifferent'
print(encrypt(tab,index,s)) main()
参考资料
经典密码学与现代密码学