python实现维吉尼亚加密法

Vigenere加密/解密时,把英文字母映射为0-25的数字再进行运算,并按n个字母为一组进行变换.算法定义如下:
设密钥 k =(k1,k2,k3…,kn),明文 m = (m1,m2,….mn),则加密算法为:
Ek(m) = (c1,c2,…cn)
其中:c1 = (mi+ki)(mod 26),i=1,2,3…..n
解密算法为:
mi = (ci - ki)(mod 26), i = 1,2,…..n。

import  string,os

def     vigenereEncrypt(msg,key):
        size = len(key)
        result = []
        cnt = 0
        for i in msg:
            if i.upper() in string.uppercase:
                #offset相当于是 ki
                offset = string.uppercase.find(key[cnt%size])
                t = string.uppercase[(string.uppercase.find(i.upper())+offset)%26]  #这里相当于是c1 = (mi+ki)(mod 26) ,t = c1
                if i.isupper():
                    result.append(t)
                else:
                    result.append(t.lower())
                cnt+=1
            else:
                result.append(i)
        return "".join(result)
def     main():

        msg = "Common sense is not so common"
        cipher = vigenereEncrypt(msg,"PIZZA")#key = "PIZZA:

        print cipher
if     __name__=="__main__":
        main()

python实现维吉尼亚加密法_第1张图片

你可能感兴趣的:(python,密码学)