如何将密文解密为明文
Posted
技术标签:
【中文标题】如何将密文解密为明文【英文标题】:How do I decrypt cipher text to plaintext 【发布时间】:2020-06-23 09:04:55 【问题描述】:当用户提供密钥和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
【问题讨论】:
【参考方案1】:尝试修改您的程序以生成具有十六进制编码的密文输出,并接受具有十六进制编码的密文输入。这样,您可以将密文打印为常规文本而不是字节数组,并且用户可以使用键盘将密文作为常规字符串(而不是字节数组)输入。 (您可以使用不同的编码方法,例如 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....
【讨论】:
【参考方案2】:decrypt
的第二个参数不是长度(任何东西)。这是一个可选参数,如果提供,将导致解密尝试将输出放在那里。因此,该参数必须是可写的bytearray
或memoryview
。
把最后一个参数去掉就行了
text = myDes.decrypt(user_cipher_text)
【讨论】:
以上是关于如何将密文解密为明文的主要内容,如果未能解决你的问题,请参考以下文章