如何将密文解密为明文

How do I decrypt cipher text to plaintext

当用户提供密钥和 cipher_text

时,我想像往常一样将密文解密为明文

这是我的代码:

from Crypto.Cipher import DES

key = input('Enter your key: ').encode('utf-8')
myDes = DES.new(key, DES.MODE_ECB)
print('Please select option:\n1. Encryption\n2. Decryption\n3. Exit')

while True:
    user_choice = input("Choose a option: ")
    if user_choice == "1":
        plain_text = input("Please enter your text: ")
        modified_plain_text = plain_text.encode("utf-8")
        cipher_text = myDes.encrypt(plain_text.encode("utf-8"))
        print(f"Encrypted text: {cipher_text}")

    elif user_choice == "2":
        user_cipher_text = input(
            "Please enter your cipher text: ").encode('utf-8')
        text = myDes.decrypt(user_cipher_text, DES.block_size)

    elif user_choice == "3":
        print("Quitting The Program....")
        break
    else:
        print("Please Choose a correct option")

但是当我 运行 它时,我得到一个错误:

Traceback (most recent call last):
  File "C:\Users\Manish\Downloads\DES.py", line 17, in <module>
    text = myDes.decrypt(user_cipher_text,DES.block_size)
  File "C:\python38\lib\site-packages\Crypto\Cipher\_mode_ecb.py", line 183, in decrypt
    raise TypeError("output must be a bytearray or a writeable memoryview")
TypeError: output must be a bytearray or a writeable memoryview

尝试修改您的程序以生成十六进制编码的密文输出,并接受十六进制编码的密文输入。这样,您可以将密文打印为常规文本而不是字节数组,并且用户可以使用键盘将密文作为常规字符串(而不是字节数组)输入。 (您可以使用不同的编码方法,例如 base64 而不是十六进制)。我还清理了其他一些东西:

from Crypto.Cipher import DES
import binascii

key = input('Enter your key: ').encode('utf-8')
myDes = DES.new(key, DES.MODE_ECB)
print('Please select option:\n1. Encryption\n2. Decryption\n3. Exit')

while True:
    user_choice = input("Choose a option: ")
    if user_choice == "1":
        plain_text = input("Please enter your text: ")
        cipher_text = myDes.encrypt(plain_text.encode("utf-8"))
        print("Encrypted text:", cipher_text.hex())

    elif user_choice == "2":
        user_cipher_text = input("Please enter your cipher text: ")
        text = myDes.decrypt(binascii.unhexlify(user_cipher_text))
        print("Decrypted text:", text.decode('utf-8'))

    elif user_choice == "3":
        print("Quitting The Program....")
        break
    else:
        print("Please Choose a correct option")

请注意,键和输入必须是 8 字节的倍数。如果是这样,那么这将按预期运行:

$ python3 sajjan.py 
Enter your key: asdfghjk
Please select option:
1. Encryption
2. Decryption
3. Exit
Choose a option: 1
Please enter your text: testtest
Encrypted text: 3049caf9d8c9b7cb
Choose a option: 3
Quitting The Program....
$ python3 sajjan.py 
Enter your key: asdfghjk
Please select option:
1. Encryption
2. Decryption
3. Exit
Choose a option: 2
Please enter your cipher text: 3049caf9d8c9b7cb
Decrypted text: testtest
Choose a option: 3
Quitting The Program....

decrypt 的第二个参数不是(任何东西的)长度。这是一个可选参数,如果提供,将导致 decrypt 尝试将输出放在那里。因此,该参数必须是可写的 bytearraymemoryview

把最后一个参数去掉就可以了

text = myDes.decrypt(user_cipher_text)