使用python加密库解密DES

问题描述 投票:-1回答:1

我正在尝试通过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的倍数

python cryptography des
1个回答
-1
投票
我已经安装了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。

© www.soinside.com 2019 - 2024. All rights reserved.