0

伙计们,我正在编写一个简单的 cli 工具来加密文本并根据传递的参数进行解密。当我只使用文本时它工作正常。但是当我传递一些符号时它表现得很奇怪。

我的源代码

import argparse
from cryptography.fernet import Fernet


def generate_key():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)
    return key


def load_key():
    """
    Loads the key named 'secret.key' from current directory
    """
    return open("secret.key", "rb").read()


def encrypt_message(message):
    """
    Encrypts a message
    """
    key = load_key()
    encoded_msg = message.encode()
    f = Fernet(key)
    encrypted_message = f.encrypt(encoded_msg)

    with open("encrypted.txt", "wb") as encrypted_file:
        encrypted_file.write(encrypted_message)

    return encrypted_message


def decrypt_message(encrypted_msg):
    """
    Decrypt an encrypted message
    """
    key = load_key()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_msg)
    return decrypted_message.decode()


def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", "--en_crypt", help="Pass the text to encrypt as an argument")
    parser.add_argument("-d", "--de_crypt", help="Pass the text to decrypt as an argument", action="store_true")
    parser.add_argument("-k", "--key", help="Generate the 'secret.key' file", action="store_true")
    args = parser.parse_args()

    if args.en_crypt:
        enc = encrypt_message(args.en_crypt)
        print(enc)

    if args.de_crypt:
        with open("encrypted.txt", "rb") as file:
            txt = file.read()
        print(decrypt_message(txt))

    if args.key:
        result = generate_key()
        print("Key Generated -> " + str(result))


if __name__ == "__main__":
    Main()

MY TEST-CASE 1 - (这是成功解密传递的文本)

$ python3 01_crypt.py -k
Key Generated -> b'N5Ll6414I8nvcMlBytk8VwdFC4oVZZZMTCVTLpQ9big='
$ python3 01_crypt.py -e "Some Sample Text to Encrypt"
b'gAAAAABfVMU3JxZOrwLIudKLAqzq5IhivhhkyvJ6TMDxM-MmVQywo4AiZ1zGK5F5gO5JFXfHznV5zPjz6sD8qhOpIR_60Hq4_YLVIV0ztPAWBjln6reg1S0='
$ python3 01_crypt.py -d
Some Sample Text to Encrypt

我的测试用例 2 - (这没有按预期工作)

$ python3 01_crypt.py -k
Key Generated -> b'UDUpsIP-Ltjz8XGm-BUSwApXYE_L8eFl6rmE1yBbYW4='
$ python3 01_crypt.py -e "P@$$w0rD"
b'gAAAAABfVMX4tSIU4T1CM5Sw9jGR_O2cuIhccEM4htVTkerQD0YxWuCoUZeDWOeMIfpcP4HV7vYKmrxD22sf7yk27hGCdx0jQA=='
$ python3 01_crypt.py -d
P@4103w0rD

根据测试用例 2,我的预期输出应该与加密的输出相同,P@$$w0rD但它显示为P@4103w0rD

我不知道为什么会这样。我错过了什么重要的东西吗?请指教。提前致谢!

附加说明

当我在没有它的情况下尝试相同的设施时,argparse它会按预期工作。请查看下面的代码,

from cryptography.fernet import Fernet


def key_generate():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)
    return key


def load_keys():
    """
    Loads the generated key named 'secret.key' from current directory
    """
    return open("secret.key", "rb").read()


def encrypt_message(message):
    """
    Encrypts a message
    """
    key = load_keys()
    encoded_msg = message.encode()
    f = Fernet(key)
    encrypted_message = f.encrypt(encoded_msg)
    return encrypted_message


def decrypt_message(encrypted_msg):
    """
    Decrypt an encrypted message
    """
    key = load_keys()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_msg)
    # print(type(encrypted_msg))
    return decrypted_message.decode()


if __name__ == "__main__":
    key_generate()
    load_keys()

    PLAINTEXT = "P@$$w0rD"
    print("Plain Text", PLAINTEXT)

    ENCRYPTED_TEXT = encrypt_message(PLAINTEXT)
    print("Encrypted Text", ENCRYPTED_TEXT)

    DECRYPTED_TEXT = decrypt_message(ENCRYPTED_TEXT)
    print("Decrypted Text", DECRYPTED_TEXT)

输出

$python3 02_decrypt.py 
Plain Text P@$$w0rD
Encrypted Text b'gAAAAABfVMfzv7H--aTCaUBdHVs05VRbFmuqpnrt-7k1NCTY9FrGMZKH8y2pkKqZsu5oxRqRgp5DzyRHZhfmA9p_cgNniWfsNw=='
Decrypted Text P@$$w0rD

上述行为让我怀疑,argparse可能是罪魁祸首。请指教。

4

1 回答 1

1

Argparse 没有错,您对 shell 的使用是错误的。

python3 01_crypt.py -e "P@$$w0rD" 

让您的 Unix shell 替换当前的 PID$$(恰好是 4103)。

使用单引号来避免替换。

python3 01_crypt.py -e 'P@$$w0rD' 
于 2020-09-06T11:43:25.020 回答