Encrypting and decrypting a password raises ValueError

In Python 3.x, input will return a string. You can read about it in the PyDocs. When you gave Python the input Banana, it is confused. You can’t convert Banana to a float type. If you are looking at converting the string into a set of indexes for your program, you can try this (note the 3 new functions I added and implemented into your code):

encryptionlist = (('a','q'),
                  ('b','w'),
                  ('c','e'),
                  ('d','r'),
                  ('e','t'),
                  ('f','y'),
                  ('g','u'),
                  ('h','i'),
                  ('i','o'),
                  ('j','p'),
                  ('k','a'),
                  ('l','s'),
                  ('m','d'),
                  ('n','f'),
                  ('o','g'),
                  ('p','h'),
                  ('q','j'),
                  ('r','k'),
                  ('s','l'),
                  ('t','z'),
                  ('u','x'),
                  ('v','c'),
                  ('w','v'),
                  ('x','b'),
                  ('y','n'),
                  ('z','m'))

print('This program will encrypt and decrypt user passwords')

def letter_index(letter):
    return ord(letter) - 97

def encrypt(text):
    lowered_text = text.lower()
    encrypted_text = [letter_index(x) for x in lowered_text]
    encrypted_text = "".join([encryptionlist[x][1] for x in encrypted_text])
    return encrypted_text

def decrypt(text):
    lowered_text = text.lower()
    # the decryption process will yield worst case speed of O(n)
    # if you were to loop through the whole thing.
    # A faster way to sort it by the value e.g.
    sorted_encryptionlist = sorted(encryptionlist, key=lambda x: x[1])
    decrypted_text = [letter_index(x) for x in lowered_text]
    decrypted_text = "".join([sorted_encryptionlist[x][0] for x in decrypted_text])
    return decrypted_text


#Program Menu
ans = True

while True:
    # Get user input
    print('1. Enter 1 to encrypt a password: ')
    print('2. Enter 2 to decrypt a password: ')
    print('3. Exit/Quit')
    ans = input('What do you want to do? ')

    if ans == "1":
        print("\nEnter 1 to encrypt a password: ")

        Password = input('Enter Password: ')

        print('Your new encryptid password is:', encrypt(Password))
    if ans == "2":
        print("\nEnter 2 to decrypt a password: ")

        Password = input('Enter Password: ')

        print('Your new decrypted password is:', decrypt(Password))
    elif ans == "3":
        print("\nGoodbye")
        break
    else:
        print("\nNot Valid Choice Try Again")

Of course, this is a weak encryption, if you want better encryption (the stuff used by professionals), take a look at pycrypto.

Leave a Comment