0

i am trying to write a code in python, that encrypt the user input. so for example if i write "name" the output should be "obnf". but the problem is that now the output is only "o", so only the first letter is going through the loop and the rest is left out. Any suggestions? here is my code

userInput = input("write something: ")


letters = iter(["A","B","C","D", "E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","X","Y","Z","0","1","2","3","4","5","6","7","8","9","a","b","c", "d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"])


def Encoding(user_input):
    encrypted_msg = ""
    for i in range(len(user_input)):
        char = user_input[i]
        if char in letters:
            encrypted_msg += next(letters)
    return encrypted_msg

print(Encoding(userInput))
tbhaxor
  • 1,659
  • 2
  • 13
  • 43
SysRQ95
  • 5
  • 3
  • This is a Caesar Cypher encryption with the shift being 1. The duplicate has 19 answers you can choose from which will shed light on what exactly you're doing wrong. BTW, your code is not entirely correct. Instead of using `next` in iteration, consider converting to a list and finding the index of where the character is in your letters array, then increment by 1 to access the final character. – rayryeng Nov 15 '19 at 17:03

2 Answers2

1

An interator can only be traversed once, then it is exhausted. Use a list instead.

Consider str.maketrans() and str.translate() for quick substitution.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
-1

The code below solves the problem:

from cryptography.fernet import Fernet


def encoding(user_input, key):
    return Fernet(key).encrypt(bytes(bytearray(user_input, encoding='UTF-8')))


def decoding(encrypted_input, key):
    return Fernet(key).decrypt(encrypted_input).decode("UTF-8")


if __name__ == '__main__':
    userInput = input("write something: ")

    key = Fernet.generate_key()
    encryptedInput = encoding(userInput, key)
    print(encryptedInput)

    decryptedInput = decoding(encryptedInput, key)
    print(decryptedInput)

Cheers!

Carlos Souza
  • 351
  • 6
  • 13