Vigenere密码'字符串索引超出范围'用于解密

时间:2015-09-15 20:36:13

标签: python python-2.7 encryption vigenere

我的Vigenere密码完美地用于加密,但我只需要解决这个问题进行解密,在运行程序后我被告知字符串索引超出范围。有人可以让我知道我需要改变它,如果可以,我将非常感激。

编辑:我已经更改了导致字符串索引问题的代码部分,但是现在,在处理解密时,输出是一个空白行,其中包含“无”字样。在它下面没有错误。

编辑:ord(_key_text [letters%len(_key_text)])我需要在解密的等式的这一边用_key_phrase替换_key_text。

#encryption
def encrypt():
    crypt = ''
    key_phrase = raw_input("Please enter a key phrase to encrypt by: ")
    key_phrase = key_phrase.upper()
    key_text = raw_input("Please enter a piece of text to encrypt: ")
    key_text = key_text.upper()
    if len(key_text) == 0: 
        print("Key must be of length 1 or more."); exit()
    if not key_text.isalpha() or not key_phrase.isalpha():
        print("Both text and key must be composed of letters only."); exit()
    for letters in range(0, len(key_text)):
        new = ord(key_text[letters]) + ord(key_text[letters%len(key_text)]) - 65
       if new > 90:
            new -= 26
        crypt += chr(new)
    print crypt

#decryption
def decrypt():
    decrypt = ''
    _key_phrase = raw_input("Please enter a key phrase to encrypt by: ")
    _key_phrase = _key_phrase.upper()
    _key_text = raw_input("Please enter a piece of text to encrypt: ")
    _key_text = _key_text.upper()
    if len(_key_text) == 0: 
        print("Key must be of length 1 or more."); exit()
    if not _key_text.isalpha() or not _key_phrase.isalpha():
        print("Both text and key must be composed of letters only."); exit()
    for letters in range(0, len(_key_text)):
        new = ord(_key_text[letters]) - ord(_key_text[letters%len(_key_text)]) + 65
        if new < 65:
            new += 26
        decrypt == chr(new)
    print decrypt

#asking the user to enter a or b for en/decryption and whether they wish to continue
choice = raw_input("Please enter either 'a' for encryption or 'b' for decryption: ")
if choice == 'a':
    print encrypt()
else:
    print decrypt()

1 个答案:

答案 0 :(得分:1)

如果您的关键字长于关键字,则会在此处获得无效索引: new = ord(_key_phrase[letters]) - ord(_key_text[letters%len(_key_text)])letters变得大于len(_key_text)

您在key_text以及encryptionkey text的两个地方都有key phrase解密,因此您必须在此处更改一个变量。