Search code examples
pythonpython-2.7encryptionvigenere

Vigenere Cipher Python giving foreign characters instead of English


This code is meant to encrypt and decrypt using the Vigenere Cipher technique and when I choose encryption and enter my key word and text the outcome is a bunch of foreign characters printed one at a time on individual lines like this: L Lo lou and so on. And additionally when I choose decryption the printed result is an error stating the 'print index is out of range'. Both of these errors I do not know how to solve, any help I would be greatly appreciative for.

#encryption 
def encrypt():
    crypt = ''
    key_phrase = raw_input("Please enter a key phrase to encrypt by: ")
    key_text = raw_input("Please enter a piece of text to encrypt: ")
    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 decrypt by: ")
    _key_text = raw_input("Please enter a piece of text to include: ")
    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_phrase[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
choice = raw_input("Please enter either 'a' for encryption or 'b' for     decryption: ")
if choice == 'a':
    print encrypt()
else:
    print decrypt()     

Solution

  • You use ASCII codes for upper case but your key and text are in lower case.

    Possible solutions:

    1. Use upper case for key and text during input.

    2. Set key and text to upper case by key_phrase = key_phrase.upper()

    3. Use ASCII code for lower case not for upper case. e.g. range from 97 to 122, not 65 to 90.

    This will work (though it is not the best solution):

    in encrypt:

    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()
    

    in decrypt:

    _key_phrase = raw_input("Please enter a key phrase to decrypt by: ")
    _key_phrase = _key_phrase.upper()
    _key_text = raw_input("Please enter a piece of text to include: ")
    _key_text = _key_text.upper()