我正在尝试通过python进行DES加密/解密,但是解密代码出错
from Crypto import Random
from Crypto.Cipher import DES3
def DesEncrypt(message , passphrase):
cipher = DES3.new(passphrase)
encrypted_data = cipher.encrypt(message)
return encrypted_data
加密工作正常,但我不知道它是否正确。无论如何我都无法解密密码
def DESdecrypt(encrypted, passphrase):
while len(encrypted) % 8 !=0:
encrypted += " "
return encrypted
cipher = DES3.new(passphrase)
encrypted_data = cipher.decrypt(encrypted)
return encrypted_data
while循环使密码长度为8的倍数
pycryptodome
,因此可能某些选项可能与您的安装不同。我特意选择了一个16字节的消息,以便它是8字节的倍数,并且密钥是24字节,因为这是首选长度。
from Crypto.Cipher import DES3
def DesEncrypt(message , passphrase):
cipher = DES3.new(passphrase, DES3.MODE_ECB)
encrypted_data = cipher.encrypt(message)
return encrypted_data
def DESdecrypt(encrypted, passphrase):
cipher = DES3.new(passphrase, DES3.MODE_ECB)
message = cipher.decrypt(encrypted)
return message
message = '0123456789abcdef'.encode('utf-8')
key = '123456789012345678901234'
cipher_text = DesEncrypt(message, key)
plain_text = DESdecrypt(cipher_text, key)
print(plain_text.decode('utf-8'))
输出:
0123456789abcdef
请注意,要加密的消息首先如何编码为utf-8
(转换为字节),然后再解码以将其返回为unicode。