明文:"Common sense is not so common."
密钥:"PIZZA"
密文:"Rwlloc admst qr moi an bobunm."
说明:表格中的字母都是大写,在输入输出时可以进行大小写转换,使得加解密前后明文和密文相同位置的字母大小写一致。
如果用数字0-25代替字母A-Z,维吉尼亚密码的加密文法可以写成同余的形式:
加密:Ci = (Pi + Ki ) mod 26
解密:Pi = (Ci - Ki )mod 26
其中Pi 是原文字母下标,Ci是密文字母下标,Ki是密钥字母下标。原文,密文以及密钥的关系如下图所示:
源代码贴上来:
import string,os
from itertools import cycle
def vigenereEncrypt(message,key):
size = len(key)
result = []
cnt = 0
for i in message:
if i.upper() in string.ascii_uppercase:
offset = string.ascii_uppercase.find(key[cnt%size])
t = string.ascii_uppercase[(string.ascii_uppercase.find(i.upper())+offset)%26]
if i.isupper():
result.append(t)
else:
result.append(t.lower())
cnt+=1
else:
result.append(i)
return "".join(result)
message = "Common sense is not so common"
print('message:',message)
cipher = vigenereEncrypt(message,"PIZZA")
print('cipher:',cipher)
def vigenereDecrypt(cipher,key):
size = len(key)
result = []
cnt = 0
for i in cipher:
if i.upper() in string.ascii_uppercase:
offset = string.ascii_uppercase.find(key[cnt % size])
t = string.ascii_uppercase[
(string.ascii_uppercase.find(i.upper()) -offset) % 26]
if i.isupper():
result.append(t)
else:
result.append(t.lower())
cnt += 1
else:
result.append(i)
return "".join(result)
re_message = vigenereDecrypt(cipher,"PIZZA")
print('re_message:',re_message)