周期置换密码
参考教材:《现代密码学教程》P47 3.1.2
加密解密过程
周期置换密码是将明文p串按固定长度m分组.然后对每组中的子串按1,2…,m的某个置换重新排列位置从而得到密文,其中密钥σ包含分组长度信息。
解密时同样对密文c按长度m分组,并按σ的逆置换σ-1把每组子串重新排列位置从而得到明文p。
以例3.3为例
和上次提及的列置换密码类似
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
import re class timeCode: __key = [] # 密钥 __apaMsg = "" # 明文 __secMsg = "" #密文 __lenKey = 0 #密钥长度 周期值 def getKey( self ,s): # 密钥形成函数 Key = {} antiKey = {} s = re.split(r '[()]' ,s) #以()分界 while ' ' in s: # 消除' ' s.remove('') temp = [] for i in range ( len (s)): for j in range ( len (s[i]) - 1 ): Key[ int (s[i][j])] = int (s[i][j + 1 ]) #密钥字典 antiKey[ int (s[i][j + 1 ])] = int (s[i][j]) #反密钥字典 temp.append( int (s[i][j])) #钥匙收录 Key[ int (s[i][ - 1 ])] = int (s[i][ 0 ]) #解决最后一个的问题 antiKey[ int (s[i][ 0 ])] = int (s[i][ - 1 ]) temp.append( int (s[i][ - 1 ])) maxtemp = max (temp) #密钥长度 self .__lenKey = maxtemp lenKey = {i + 1 for i in range (maxtemp)} sameKey = lenKey - set (temp) #找到没有变化的密钥 for i in sameKey: Key[i] = i antiKey[i] = i self .__key.append(Key) self .__key.append(antiKey) def enCode( self ,p): #加密函数 self .__apaMsg = p Key = self .__key[ 0 ] time = self .__lenKey p = p.replace( ' ' ,'') #去除空格 if len (p) % time ! = 0 : p + = ' ' * (time - len (p) % time) #末尾补齐 n = len (p) / / time M = [p[i * time:(i + 1 ) * time] for i in range (n)] #分组生成 M = [M[i][Key[j + 1 ] - 1 ] for i in range (n) for j in range (time)] #矩阵转换 M = ''.join(M) #列表转换为字符串 self .__secMsg = M return M def deCode( self ,q): self .__apaMsg = p m = self .__lenKey n = len (q) / / m Key = self .__key[ 1 ] M = [q[i * m:(i + 1 ) * m] for i in range (n)] M = [M[i][Key[j + 1 ] - 1 ] for i in range (n) for j in range (m)] M = ''.join(M) self .__secMsg = M return M def Print ( self ): print ( self .__key, self .__apaMsg, self .__secMsg, self .__lenKey) s = '(15623)' p = 'State Key Laboratory of Networking and Switching' a = timeCode() a.getKey(s) q = a.enCode(p) a.deCode(q) a. Print () |
以上就是python密码学周期置换密码学习的详细内容,更多关于python密码学周期置换密码的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/Jarrycow/article/details/105575517