维吉尼亚密码加解密与破解
维吉尼亚密码是一种多表替换密码,密钥的周期使用决定使用哪张替换表。这也导致密钥的周期性特征泄露到了明文中,只要猜测出密钥长度,即可按照单表替换的分析方式进行破译,如分析字母频率,维吉尼亚密码的破解就是根据这个思路完成的。
1. 维吉尼亚密码的加密。
这是一份简化加密算法,只对大小写字母进行了区分,过滤了标点符号等其他字符。
def Encrypt(message,key):
cipher = ''
not_char = 0
for i in range(len(message)):
offset = ord(key[(i-not_char)%len(key)]) - ord('a')
if (message[i].isupper()):
cipher += chr(((ord(message[i]) - ord('A') + offset) % 26 ) + ord('A'))
elif (message[i].islower()):
cipher += chr(((ord(message[i]) - ord('a') + offset) % 26 ) + ord('a'))
else:
cipher += message[i]
not_char += 1
return cipher
2. 维吉尼亚密码的解密。
解密算法就是对密文字符再进行一次偏移,可以减去之前的偏移量,也可以利用取模运算的特性,增大偏移得到明文。
def Decrypt(message,key):
cipher = ''
not_char = 0
for i in range(len(message)):
offset = ord(key[(i-not_char)%len(key)]) - ord('a')
offset = 26 - offset
if (message[i].isupper()):
cipher += chr(((ord(message[i]) - ord('A') + offset) % 26 ) + ord('A'))
elif (message[i].islower()):
cipher += chr(((ord(message[i]) - ord('a') + offset) % 26 ) + ord('a'))
else:
cipher += message[i]
not_char += 1
return cipher
3. 测试结果。
test ('Congratulations','fun')
Encode: Congratulations->Hiallnyoyfnvthf
Decode: Hiallnyoyfnvthf->Congratulations
4. 维吉尼亚密码的破解。
根据维吉尼亚密码的漏洞:密钥的周期性特征泄露到了明文中。我们可以先爆破出密钥长度,然后再利用单表替换的破解方法猜测出密钥。
如何判断密钥长度是正确的,这里采用了重合指数,重合指数??与??′之间的差异,衡量计算子密文与英文的吻合程度。
def guess_len(message):
KCL = []
num = limit(26)
diff_kcl = []
for j i