pyDes decrypt "data must be a multiple of 8 bytes"



i现在,我的编程习惯不是很好。我已经从THIR网站上修改了基本PYDES代码:

import os, sys, binascii
text = input ("Text to be encrypted...")
key = input ("Key...")
sys.path.append (os.path.abspath ("").split (":") [0] + ":\Python\Libraries\pyDes")
import pyDes
def toKey (string):
    b = string
    a = 0
    if len (b) > 16:
        while len (b) != 16:
            b = b [:-1]
    elif len (b) < 16:
        while len (b) != 16:
            b += b [a]
            a += 1
    return b
key = toKey (key)
data = pyDes.triple_des(key, pyDes.CBC, "", pad=None, padmode=pyDes.PAD_PKCS5)
print ("Before: " + text)
encrypted = str (data.encrypt (text)) [2:-1]
print ("Encrypted: " + encrypted)
decrypted = str (data.decrypt (encrypted)) [2:-1]
print ("Decrypted: " + decrypted)

当我运行程序时,加密效果很好,但是,解密会引发错误:

Traceback (most recent call last):
  File "E:PythonExamplesEncrypt.py", line 23, in <module>
    decrypted = str (data.decrypt (encrypted)) [2:-1]
  File "E:PythonLibrariespyDespyDes.py", line 836, in decrypt
    block = self.__key3.crypt(iv,    DECRYPT)
  File "E:PythonLibrariespyDespyDes.py", line 572, in crypt
    raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytesn.")
ValueError: Invalid data length, data must be a multiple of 8 bytes

对不起,如果这真的很烦人且简单: - (

问题似乎是您使用str(...)[2:-1]bytes值转换为字符串。

也许您在尝试以下代码

之后就解决了使用此问题。
encrypted = data.encrypt (text)
print ("Encrypted: " + encrypted)

发现它报告了错误 TypeError: Can't convert 'bytes' object to str implicitly

有关encryptdecrypt方法的输出(以及输入)的一件事是,它们使用bytes对象而不是字符串(str)。您正在做的是将bytes对象从调用data.encrypt返回,使用str转换为字符串(这不是正确的方法),然后尝试解密字符串而不是bytes值从encrypt

您需要做的是使用strencode方法将文本转换为bytes对象,然后再将其传递给data.encrypt。您需要指定一个字符集来执行此编码,例如utf-8。从decrypt取回输出后,使用bytes对象的decode方法将其转换回字符串。

但是,在任何字符集中,加密数据都不可能可读。(这很可能不是形成良好的UTF-8,所以不要尝试将其转换为。)如果您想看看它的外观,也许最好的办法就是使用内置 - 在repr函数中,但仅在打印值时使用它。

进行了这些更改后,这是代码的最后几行的样子:

charset = "utf-8"
encrypted = data.encrypt(text.encode(charset))
print ("Encrypted: " + repr(encrypted))
decrypted = data.decrypt(encrypted).decode(charset)
print ("Decrypted: " + decrypted)

这是示例运行的输出:

Text to be encrypted...example1234
Key...5678
Before: example1234
Encrypted: b'xf1xed6cR9px18ux1exf7xcbx98xe40xed'
Decrypted: example1234

加密数据中的xNN序列是Python在不在ASCII范围内的bytes对象中显示单个字节的方式。

相关内容

最新更新