【问题标题】:TypeError: argument must be string or read-only buffer, not bytearrayTypeError:参数必须是字符串或只读缓冲区,而不是字节数组
【发布时间】:2019-10-08 14:50:11
【问题描述】:

我正在使用 DES ECB 构建解密器

from Crypto.Cipher import DES

code = 'cb9108614c943d96bedd2bae934c5aa3d5c4318f81cc81f255127292f2935bbc0a8990f36c1ffa20a0639ed8a6989bacc36bd11f6b2ecdab'
key = b'5199D19B'
code= bytearray.fromhex(code)

print(code)

ciphert = DES.new(key, DES.MODE_ECB)
code = ciphert.decrypt(code)
code = code.decode('ISO-8859-1')

print(code)

但我不断收到此错误

文件“test.py”,第 17 行,在

code = ciphert.decrypt(code)

文件“build/bdist.macosx-10.14-intel/egg/Crypto/Cipher/blockalgo.py”,第 295 行,在解密中

TypeError: 参数必须是字符串或只读缓冲区,而不是字节数组

我已经为此工作了几个小时,但无法找到另一种存储变量的方法。

有什么想法吗?

【问题讨论】:

    标签: python pycrypto


    【解决方案1】:

    我想这就是你想要的:

    >>> from Crypto.Cipher import DES
    >>> code = 'cb9108614c943d96bedd2bae934c5aa3d5c4318f81cc81f255127292f2935bbc0a8990f36c1ffa20a0639ed8a6989bacc36bd11f6b2ecdab'
    >>> key = b'5199D19B'
    >>> ciphert = DES.new(key, DES.MODE_ECB)
    >>> ciphert.decrypt(code.decode('hex'))
    'Well done, you have been able to decode the message. \x00\x00\x00'
    

    通常当将密文传递给加密库中的“解码”函数时,它应该作为bytes 对象传递(因为密文通常可以包含任意字节)。无论出于何种原因,它都不接受 bytearray 对象——必须单独实现。

    code.decode('hex') 执行您想要的相同操作 - 它将一串十六进制数字转换为它们的实际字节值。

    Python 3 更新:

    在 Python 3 上 code.decode('hex') 将不起作用。而是使用bytes.fromhex(code)(类似于bytearray.fromhex,但只返回一个不可变的bytes 实例)。

    【讨论】:

    • @user1438644 不,这不起作用。在 Python 3 上,将 str 转换为字节时,您必须提供编码。 OP 正在尝试将一串十六进制数字转换为它们的字节值。
    • 显然这只是我使用的python版本。它适用于 3 但不适用于 2.7
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2019-02-17
    相关资源
    最近更新 更多