介绍
维吉尼亚密码是一种古典密码算法,也被称为多表密码。
维吉尼亚密码曾多次被发明。该方法最早记录在吉奥万·巴蒂斯塔·贝拉索( Giovan Battista Bellaso)于1553年所著的书《吉奥万·巴蒂斯塔·贝拉索先生的密码》(La cifra del. Sig. Giovan Battista Bellaso)中。然而,后来在19世纪时被误传为是法国外交官布莱斯·德·维吉尼亚(Blaise De Vigenère)所创造,因此现在被称为“维吉尼亚密码”。
在维吉尼亚密码中,密钥是一个与明文长度相同的字符串,用于对每个明文字符进行加密。加密过程中,将明文字符与密钥字符对应,然后使用凯撒密码的方法进行加密。具体来说,将明文字符与密钥字符相加(按字母表顺序),并对26取模,得到密文字符。解密过程则是将密文字符与密钥字符相减,并对26取模,得到明文字符。
维吉尼亚密码的优点是可以实现较强的安全性,因为它使用了一个变长的密钥,使得破解难度增加。然而,维吉尼亚密码也有一些缺点,例如当密钥长度较短时,仍然容易受到频率分析等攻击方法的破解。
加密
def vigenere_encrypt(plaintext, key):
ciphertext = ""
key_index = 0
for char in plaintext:
if char.isalpha():
# 将明文字符转换为0-25的数字
plaintext_num = ord(char.upper())
key_num = ord(key[key_index % len(key)].upper()) - ord('A')
# 加密字符
encrypted_num = (plaintext_num + key_num) % 26
# 将加密后的数字转换为字符
encrypted_char = chr(encrypted_num + ord('A'))
ciphertext += encrypted_char
key_index += 1
else:
ciphertext += char
return ciphertext
解密
def vigenere_decrypt(ciphertext, key):
plaintext = ""
key_len = len(key)
for i in range(len(ciphertext)):
# 计算密钥字符的索引
key_index = i % key_len
# 计算解密后的字符
char = chr((ord(ciphertext[i]) - ord(key[key_index])) % 26 + ord('A'))
# 将解密后的字符加入到明文中
plaintext += char
return plaintext
主程序
flag = 'n'
while flag == 'n':
action = input('''维吉尼亚密码
加密(1)/解密(2): ''')
print("{:-^50s}".format("Split Line"))
if action == '1':
plaintext = input('明文: ')
key = input('密钥: ')
ciphertext = vigenere_encrypt(plaintext, key)
print("密文:", ciphertext)
elif action == '2':
ciphertext = input('密文: ')
key = input('密钥: ')
plaintext = vigenere_decrypt(ciphertext, key)
print("明文:", plaintext)
flag = (input('是否退出(y/n)'))
print("{:-^50s}".format("Split Line"))
大量文本测试
以马太福音为明文,bible为密钥: