Vigenere cipher 'string index out of range' for decryption

拥有回忆 提交于 2020-01-07 01:49:27

问题


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:


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.



来源:https://stackoverflow.com/questions/32595168/vigenere-cipher-string-index-out-of-range-for-decryption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!