使用Pycryptodome库进行python,我得到一个TypeError:每当我尝试解密时,只能将字节字符串传递给C代码

时间:2017-05-19 07:11:42

标签: python python-3.x pycrypto pycryptodome

def aes128_decrypt(self, msg):
    iv = os.urandom(16)
    aes_obj = AES.new(self.key, AES.MODE_CBC, iv)
    decrypted_msg = aes_obj.decrypt(msg)
    return decrypted_msg

我正在使用它来解密,并且msg作为bytearray传入。我使用Python 3和pycryptodome库进行AES128加密。我看到的错误是:

msg = bytearray(b'M\xb1\xbfw\xf4o\x15\xff\xda{u\xba)\xcd\x9fu\x80\xb2\x0c*s\x17%6\xfeA\xb84\xab\x89\xff\x16A\xb8')

def expect_byte_string(data):
    if not byte_string(data) and not isinstance(data, Array):
        raise TypeError("Only byte strings can be passed to C code")
        TypeError: Only byte strings can be passed to C code

2 个答案:

答案 0 :(得分:0)

要解密的邮件必须是bytes个对象,而不是bytearray

在第二个剪辑中,尝试将msg直接定义为:

msg = b'M\xb1\xbfw\xf4o\x15\xff\xda{u\xba)\xcd\x9fu\x80\xb2\x0c*s\x17%6\xfeA\xb84\xab\x89\xff\x16A\xb8'

答案 1 :(得分:0)

TypeError:只能将字节字符串传递给C代码

use A prefix of 'b' or 'B' 

bytes(s, encoding = "utf8")  # str to bytes

示例:

# coding: utf-8
from Crypto.Cipher import AES
import base64
pad_it = lambda s: bytes(s+(16 - len(s)%16)*PADDING, encoding='utf8')
key = b'1234567812345678'
iv = b'1234567812345678'
source = 'Test String'
generator = AES.new(key, AES.MODE_CBC, iv)
crypt = generator.encrypt(pad_it(source))
cryptedStr = base64.b64encode(crypt)