为什么Vigenere密码只能正确加密部分邮件?

时间:2017-08-30 00:17:46

标签: python vigenere

为什么Vigenere密码只能正确加密部分消息?我们开始编写一个Caesar密码,并使用为Caesar创建的辅助函数毕业到Vigenere密码。我的alphabet_position和rotate_character函数似乎正在工作,但我的Vigenere加密函数只能正确返回部分加密消息。
例如, 打印加密(' BaRFoo',Baz) 应该回来了:' CaQGon' 实际上已退回:' CakGo \ x88'

到目前为止,我的代码如下:

import string

def alphabet_position(letter):
    return (ord(letter))

def rotate_character(char,rot):
    encoded = ""
    # loop over characters for ord
    char_ord = alphabet_position(char)
    # non-alphabet characters
    if (char_ord > 90 and char_ord < 97) or char_ord < 65 or char_ord >122:
        encoded = encoded + char
        return encoded
    else:
        # set each according to whether upper or lower case
        # ord of "Z" is 90, so 91 for upper range and ord of "A" is 65 so 
        uppercase boundary
        if char.isupper():
            asciirange = 91
            asciibound = 65
        else:
            # ord of "z" is 122 so 123 for upper range and ord of "a" is 97 
            so lowercase boundary
            asciirange = 123
            asciibound = 97

    enc_char = ((char_ord + rot) % asciirange)
    if enc_char < asciibound:
       enc_char = (enc_char + asciibound)
       encoded = encoded + (chr(enc_char))
    else:
       encoded = encoded + (chr(enc_char))
    return (encoded)

def encrypt(text,keyword):
    encoded_text = ""
    key_start = 0
    # find rot
    alpha = string.ascii_letters
    for char in text:
        # check if char is a letter
        if char.isalpha():
            key_num = (alphabet_position(keyword[key_start]))
            # convert key_num to a letter to find its index
            rot = alpha.find(chr(key_num))
            encoded_text += (rotate_character(char,rot))
            if key_start == (len(keyword)-1):
                key_start = 0
            else:
                key_start += 1
         else:
             encoded_text += char

    return encoded_text

1 个答案:

答案 0 :(得分:0)

for index, char in enumerate(text):
    print index, char

抱歉,我不确定这是你要求的,但我试试;) 希望它有所帮助。