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
。
有关encrypt
和decrypt
方法的输出(以及输入)的一件事是,它们使用bytes
对象而不是字符串(str
)。您正在做的是将bytes
对象从调用data.encrypt
返回,使用str
转换为字符串(这不是正确的方法),然后尝试解密字符串而不是bytes
值从encrypt
。
您需要做的是使用str
的encode
方法将文本转换为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
对象中显示单个字节的方式。