如何使用 DES3 解密密文?

How to decrypt cipher text using DES3?

from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import DES3
import binascii
from Crypto.Random import get_random_bytes

#iv = b"23456789"
iv = get_random_bytes(8)
#key = input('Please enter a 8 byte key: ').encode('utf-8')

#new_key = pad(DES3.adjust_key_parity(key),24)
print('Please select option:\n1. Encryption\n2. Decryption\n3. Exit')


while True:
    user_choice = input("Choose a option: ")
    if user_choice == "1":
        data = input('Enter the text: ').encode('utf-8')  # 9 bytes
        new_key = DES3.adjust_key_parity(get_random_bytes(24))
        
        cipher1 = DES3.new(new_key, DES3.MODE_CFB,iv)
        ct = cipher1.encrypt(data).hex()
        prt_key = new_key.hex()
        print(new_key)
        print(binascii.unhexlify(prt_key))
        print(f'The encryption key is: {prt_key}')
        print(f'The cipher text is: {ct}')

    elif user_choice == "2":
        get_key = input('Enter your encryption key: ')
        get_hex_key = binascii.unhexlify(get_key)
        print(get_hex_key)
        hex_value = input('Enter the cipher text: ')
        cip_txt = binascii.unhexlify(hex_value) # #cip_txt = bytes.fromhex(f'{hex_value}')
        cipher2 = DES3.new(get_hex_key, DES3.MODE_CFB, iv)
        pt = cipher2.decrypt(cip_txt)
        print(f"The decrypted text is: {pt.decode('utf-8')}")


    elif user_choice == "3":
        print("Quitting The Program....")
        break

    else:
        print("Please Choose a correct option")

所以当我 运行 代码 它解密成功,但是当我选择 2 而不是加密时,出现错误:

Please select option:
    1. Encryption
    2. Decryption
    3. Exit
    Choose a option: 1
    Enter the text: hey
    b',\x85\x0b\x01n/p^\xf4@[\x10Fb\xce\xb67[\x08\xec\x97O\x97\xbc'
    b',\x85\x0b\x01n/p^\xf4@[\x10Fb\xce\xb67[\x08\xec\x97O\x97\xbc'
    The encryption key is: 2c850b016e2f705ef4405b104662ceb6375b08ec974f97bc
    The cipher text is: a44c2c
    Choose a option: 2
    Enter your encryption key: 2c850b016e2f705ef4405b104662ceb6375b08ec974f97bc
    b',\x85\x0b\x01n/p^\xf4@[\x10Fb\xce\xb67[\x08\xec\x97O\x97\xbc'
    Enter the cipher text: a44c2c
    The decrypted text is: hey

错误:

Please select option:
1. Encryption
2. Decryption
3. Exit
Choose a option: 2
Enter your encryption key: 1337518a8f3dd5458a01d502a780c416166e025468ae7929
b'\x137Q\x8a\x8f=\xd5E\x8a\x01\xd5\x02\xa7\x80\xc4\x16\x16n\x02Th\xaey)'
Enter the cipher text: 54032077
Traceback (most recent call last):
  File "C:\Users\Manish\DownloadsDES_enc&dec_CFB.py", line 36, in <module>
    print(f"The decrypted text is: {pt.decode('utf-8')}")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8c in position 3: invalid start byte

我正在尝试创建一个可以加密和解密密文的程序,所以当我 运行 首先生成密文的代码时,它也可以解密它,但是当我 运行 代码和 select 选项 2 它无法解密文本。

如果您解密随机字节或使用错误的密钥,那么您将在 return 中得到随机字节。如果您不希望发生这种情况,您需要经过身份验证的密码或密文上的 MAC,并在解密前进行验证。

当您尝试使用 UTF-8 解码随机字节时,很有可能 UTF-8 编码无效,并且当遇到具有无效值的字节时停止解码。