原理
維吉尼亞密碼,它將凱撒密碼的所有26種排列放到一個表中,形成26行26列的加密字母表。此外,維吉尼亞密碼必須有一個由字母組成的密鑰,至少有一個字母,最多與明文字母有相同數量的字母。
在凱撒密碼中,每個字母都會進行一定偏移值轉換,例如,當偏移值是3時,則B被轉換為E,C轉換成F......。在維吉尼亞密碼加密中,則是由具有不同偏移的凱撒密碼構成的。
要生成密碼,需要使用表格方法,此表(如圖所示)包含26行字母表,每一行從上一行到左行被一位偏移。加密時使用哪一行字母表是基於密鑰的,在加密過程中密鑰會不斷變化。
例如,假設明文為:
BTTACKATDAFG
選擇一個關鍵字並重復它以獲得密鑰,例如,當關鍵字是LIMN時,鍵是:
LIMNLIMNLIMN
在明文中的第一個字母B,對應於密鑰中的第一個字母L,使用加密字母表中的L行字母進行加密,得到第一個字母的密文M。同樣,第二個明文字母是T,它用表中的I行加密,得到第二個密文B。通過類比,我們可以得到:
明文:BTTACKATDAFG 鍵:LIMNLIMNLIMN 密文:MBFNNSMGOIRT
解密的過程是加密的逆過程。例如,密鑰的第一個字母對應的L行字母表,發現密文的第一個字母M位於B列,因此明文的第一個字母是B。密鑰的第二個字母對應於I行字母表,而密文的第二個字母B位於該行的T列中,因此明文的第二個字母是T。等等,你可以得到明文。轉自:http://www.metools.info/code/c71.html
加密與解密
# -*- coding:utf-8 -*- import string letters = string.ascii_letters def encode_s(plaintext, key): encode = '' j = 0 # 非字母字符數量 for i,value in enumerate(plaintext): if value.isalpha(): n = (letters.find(plaintext[i]) + letters.find(key[i-j])) % 26 # 移位后的字母位置(大小寫字母處理為相同情況) if value.isupper(): n += 26 # 大寫字母要比小寫字母高26位 encode += letters[n] else: encode += value j += 1 return encode def decode_s(ciphertext, key): decode = '' j = 0 # 非字母字符數量 for i, value in enumerate(ciphertext): if value.isalpha(): n = (letters.find(ciphertext[i]) - letters.find(key[i - j])) % 26 # 移位后的字母位置(大小寫字母處理為相同情況) if value.isupper(): n += 26 # 大寫字母要比小寫字母高26位 decode += letters[n] else: decode += value j += 1 return decode # 處理秘鑰和明文長度相同 def keyprocess(key,plaintext): n = len(key) m = len(plaintext) if n > m: return key[:len(plaintext)],plaintext elif n < m: i = m // n j = m % n return key*i+key[:j],plaintext if __name__ == '__main__': text1 = 'comegreatwall' key = 'crypto' key,text1 = keyprocess(key,text1) print (encode_s(text1,key)) text2 = 'efktzfgrrltzn' print (decode_s(text2,key))