維吉尼亞密碼的Python實現


代換密碼體制的一般定義為M=C=K=Z26,其中M為明文空間、C為密文空間、K為密鑰空間、Z26為26個整數(對應26個英文字母)組成的空間;要求26個字母與模26的剩余類集合{0,1,2,…,25}建立一一對應的關系。

1移位密碼

移位密碼的加密實現上就是將26個英文字母向后循環移動k位,其加解密可分別表示為:

c=Ek(m)=m+k(mod 26)

m=Dk(c)=c-k(mod 26)

其中,m、c、k是滿足0≤m,c,k≤25的整數。

2、維吉尼亞密碼

Vigenenre密碼是最著名的多表代換密碼,是16世紀法國著名密碼學家Vigenenre發明的。Vigenenre密碼使用一個詞組作為密鑰,密鑰中每一個字母用來確定一個代換表,每一個密鑰字母被用來加密一個明文字母,第一個密鑰字母加密第一個明文字母,第二個密鑰字母加密第二個明文字母,等所有密鑰字母使用完后,密鑰再次循環使用,於是加解密前需先將明密文按照密鑰長度進行分組。密碼算法可表示如下:

設密鑰K=(k1,k2,…,kd),明文M=(m1,m2,…,mn),密文C=(c1,c2,…,cn);

加密變換為:ci=Eki(mi)=mi+ki(mod 26)

解密變換為:mi=Dki(ci)=ci-ki(mod 26)

通常通過查詢維吉尼亞表進行加解密。

 

以下為維吉尼亞密碼的Python實現。

 


 

 

 1 #-*-coding:utf-8-*-
 2 #維吉尼亞
 3 
 4 '''
 5 fileName : main.py
 6 '''
 7 
 8 import VigenereEncrypto
 9 import VigenereDecrypto
10 
11 print u"維吉尼亞加密"
12 
13 plainText = raw_input ("Please input the plainText : ")
14 key = raw_input ("Please input the key : ")
15 
16 plainTextToCipherText = VigenereEncrypto (plainText , key)
17 print u"加密后得到的暗文是 : " + plainTextToCipherText
18 
19 print u"維吉尼亞解密"
20 
21 cipherText = raw_input ("Please input the cipherText : ")
22 key = raw_input ("Please input the key : ")
23 
24 cipherTextToPlainText = VigenereDecrypto (cipherText , key)
25 print u"解密后得到的明文是 : " + cipherTextToPlainText

 


 

 

 1 #-*-coding:utf-8-*-
 2 #維吉尼亞加密
 3 
 4 '''
 5 fileName : VigenereEncrypto.py
 6 '''
 7 
 8 def VigenereEncrypto (input , key) :
 9     ptLen = len(input)
10     keyLen =  len(key)
11 
12     quotient = ptLen // keyLen    #
13     remainder = ptLen % keyLen    #
14 
15     out = ""
16 
17     for i in range (0 , quotient) :
18         for j in range (0 , keyLen) :
19             c = int((ord(input[i*keyLen+j]) - ord('a') + ord(key[j]) - ord('a')) % 26 + ord('a'))
20             #global output
21             out += chr (c)
22 
23     for i in range (0 , remainder) :
24         c =  int((ord(input[quotient*keyLen+i]) - ord('a') + ord(key[i]) - ord('a')) % 26 + ord('a'))
25         #global output
26         out += chr (c)
27 
28     return out

 

 


 

 

 1 #-*-coding:utf-8-*-
 2 #維吉尼亞解密
 3 
 4 '''
 5 fileName : VigenereDecrypto.py
 6 '''
 7 
 8 def VigenereDecrypto (output , key) :
 9     ptLen = len (output)
10     keyLen = len (key)
11 
12     quotien = ptLen // keyLen
13     remainder = ptLen % keyLen
14 
15     inp = ""
16 
17     for i in range (0 , quotient) :
18         for j in range (0 , keyLen) :
19             c = int((ord(output[i*keyLen+j]) - ord('a') + 26 - (ord(key[j]) - ord('a')) % 26 + ord('a')))
20             #global input
21             inp += chr (c)
22 
23     for i in range (0 , remainder) :
24         c = int((ord(output[quotient*keyLen + i]) - ord('a') + 26 - (ord(key[i]) - ord('a')) % 26 + ord('a')))
25         #global input
26         inp += chr (c)
27 
28     return inp

 


 

 

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM