Vigenere Cipher Python 2.0



我在编码/解码编程时遇到了麻烦。我只应该使用列表、字典和循环。编辑:我添加了解密我有。GetCharList()只获取一个包含字母表的列表。我不知道哪里出了问题,它使解密的输出不是原始消息。

def encryptVig(msg, keyword):
    alphabet = getCharList() #Get char list is another function which creates a list containing a - z
    key = keyword.upper()
    keyIndex = 0 
    dicList = []
    for symbol in msg:
        num = alphabet.find(key[keyIndex])
        if num != -1:
            num += alphabet.find(key[keyIndex])
            alphabet.find(key[keyIndex])
            num%= len(alphabet)
            if symbol.isupper():
                dicList.append(alphabet[num])
        elif symbol.islower():
            dicList. append(alphabet[num].lower())
        keyIndex += 1
        if keyIndex == len(key):
            keyIndex = 0
        else:
            dicList.append(symbol)
return " " .join(dicList)
def decryptVig(msg, keyword):
    getCharList()
    key = keyword.upper()
    keyIndex = 0 
    dicList = []
    for symbol in msg:
        num = alphabet.find(key[keyIndex])
        if num != -1:
            num -= alphabet.find(key[keyIndex])
            alphabet.find(key[keyIndex])
            num%= len(alphabet)
            if symbol.isupper():
            dicList.append(alphabet[num])
        elif symbol.islower():
            dicList. append(alphabet[num].lower())
        keyIndex -= 1
        if keyIndex == len(key):
            keyIndex = 0
        else:
            dicList.append(symbol)
return " " .join(dicList)

与其自己破解字母表,另一种方法是使用ordchr来消除处理字母的复杂性。至少可以考虑使用itertools.cycleitertools.izip来构造一个加密/解密对的列表。下面是我的解决方法:

def letters_to_numbers(str):
    return (ord(c) - ord('A') for c in str)
def numbers_to_letters(num_list):
    return (chr(x + ord('A')) for x in num_list)
def gen_pairs(msg, keyword):
    msg = msg.upper().strip().replace(' ', '')
    msg_sequence = letters_to_numbers(msg)
    keyword_sequence = itertools.cycle(letters_to_numbers(keyword))
    return itertools.izip(msg_sequence, keyword_sequence)
def encrypt_vig(msg, keyword):
    out = []
    for letter_num, shift_num in gen_pairs(msg, keyword):
        shifted = (letter_num + shift_num) % 26
        out.append(shifted)
    return ' '.join(numbers_to_letters(out))
def decrypt_vig(msg, keyword):
    out = []
    for letter_num, shift_num in gen_pairs(msg, keyword):
        shifted = (letter_num - shift_num) % 26
        out.append(shifted)
    return ' '.join(numbers_to_letters(out))
msg = 'ATTACK AT DAWN'
keyword = 'LEMON'
print(encrypt_vig(msg, keyword))
print(decrypt_vig(encrypt_vig(msg, keyword), keyword))
>>> L X F O P V E F R N H R
    A T T A C K A T D A W N

我不知道Vigenere应该怎么工作。但是我很确定在

之后
    num = alphabet.find(key[keyIndex])
    if num != -1:
        num -= alphabet.find(key[keyIndex])

num为零

最新更新