移位密碼和代換密碼,一旦密鑰被選中,則每個字母對應的數字都會被加密,變換成對應的唯一數字。 這種密碼體制被稱為單表代換密碼。
維吉尼亞密碼是一種多表代換密碼,發明者是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)