我如何在python中加密用户输入? [重复]

问题描述 投票:0回答:2

此问题已经在这里有了答案:

我正在尝试用python编写代码来加密用户输入。因此,例如,如果我写“ name”,则输出应为“ obnf”。但是问题在于现在的输出仅为“ o”,因此只有第一个字母通过循环,其余的字母被忽略了。有什么建议么?这是我的代码

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))
python encryption caesar-cipher
2个回答
1
投票

插入器只能被遍历一次,然后耗尽。请使用list

考虑str.maketrans()str.translate()进行快速替换。


-1
投票

下面的代码解决了这个问题:

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)

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.