移位密码和代换密码,一旦密钥被选中,则每个字母对应的数字都会被加密,变换成对应的唯一数字。 这种密码体制被称为单表代换密码。
维吉尼亚密码是一种多表代换密码,发明者是16世纪的法国人Blaise de Vigenere。
假设m=6,密钥字为CIPHER,对应如下的数字串K=(2,8,15,7,4,17)。要加密的明文为:thiscryptosystemisnotsecure,将明文串转换为对应的数字,每六个为一组,使用密钥字进行模26下的加密运算,如下所示:
则相应的密文为:VPXZGIAXIVWPUBTTMJPWIZIWZT。
代码实现(Python 3)
def vigenere_cipher_encrypt(message:str, keys=()):
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
n = 0
keylen = len(keys)
message = message.upper()
for symbol in message:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
key = keys[n % keylen]
translatedIndex= (symbolIndex + key) % 26
translated = translated + SYMBOLS[translatedIndex]
n = n + 1
else:
translated = translated + symbol
print(translated)
def vigenere_cipher_encrypt_by_keystring(message:str, keystring:str):
keys = translate_keystring(keystring)
vigenere_cipher_encrypt(message, keys)
def vigenere_cipher_decrypt(message:str, keys=()):
SYMBOLS = 'abcdefghijklmnopqrstuvwxyz'
translated = ''
n = 0
keylen = len(keys)
message = message.lower()
for symbol in message:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
translatedIndex= (symbolIndex - keys[n % keylen])%26
translated = translated + SYMBOLS[translatedIndex]
n = n + 1
else:
translated = translated + symbol
print(translated)
def vigenere_cipher_decrypt_by_keystring(message:str, keystring:str):
keys = translate_keystring(keystring)
vigenere_cipher_decrypt(message, keys)
def translate_keystring(keystring:str):
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
keys = []
keystring = keystring.upper()
for symbol in keystring:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
keys.append(symbolIndex)
else:
keys.append(-1)
return tuple(keys)