Vigenere cipher 'string index out of range'

2019-09-17 21:19发布

my Vigenere cipher works perfectly for encryption but I just need to fix this problem for decryption where I am told, after running the program, that the string index is out of range. Could someone please let me know what i need to change it to, I would be extremely grateful if you could.

edit: I have changed the part of the code that was causing the string index problem but now, when processing decryption, the output is a blank line with 'None' beneath it and no error.

edit: ord(_key_text[letters%len(_key_text)]) i needed to replace _key_text with _key_phrase on this side of the equation in decrypt.

#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条回答
爷的心禁止访问
2楼-- · 2019-09-17 21:33

If your key text is longer than key phrase you'll get an invalid index here : new = ord(_key_phrase[letters]) - ord(_key_text[letters%len(_key_text)]) when letters becomes greater than len(_key_text)

You have key_text on both places in encryption and key text and key phrase in decryption so you have to change one variable here.

查看更多
登录 后发表回答