维格纳密码Python 2.0

2024-10-01 13:46:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个维格纳密码的编码/解码编程问题。我只能使用列表、字典和循环。 编辑:我添加了我的解密。GetCharList()只获取一个包含字母表的列表。我不知道是什么错,它使decrypt的输出不是原始消息。在

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)

Tags: key列表lenifdefmsgfindsymbol
2条回答

另一种方法是使用ord和{}来消除处理字母的一些复杂性,而不是自己去破解字母表。至少考虑使用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

我不知道维格纳应该怎么工作。但是我很确定

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

num为零。在

相关问题 更多 >