Crypto.AES 报错 | TypeError: Object type <class 'str'> cannot be passed to C code

1 源代码:

    def decrypt(self, enc):
        """
        Requires hex encoded param to decrypt
        """
        enc = a2b_hex(enc)
        iv = enc[:16]
        enc = enc[16:]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return unpad(cipher.decrypt(enc).decode("utf-8"))

 

2 报错信息:

1、报错信息
    cipher = AES.new(self.key, AES.MODE_CBC, iv)
  File "D:\Python37\Lib\Crypto\Cipher\AES.py", line 232, in new
    return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
  File "D:\Python37\Lib\Crypto\Cipher\__init__.py", line 79, in _create_cipher
    return modes[mode](factory, **kwargs)
  File "D:\Python37\Lib\Crypto\Cipher\_mode_cbc.py", line 274, in _create_cbc_cipher
    cipher_state = factory._create_base_cipher(kwargs)
  File "D:\Python37\Lib\Crypto\Cipher\AES.py", line 103, in _create_base_cipher
    result = start_operation(c_uint8_ptr(key),
  File "D:\Python37\Lib\Crypto\Util\_raw_api.py", line 144, in c_uint8_ptr
    raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <class 'str'> cannot be passed to C code

 3 报错代码:

cipher = AES.new(self.key, AES.MODE_CBC, iv)

4 报错原因:

AES.new() 这个方法中的第一个参数的类型为byte型,因为我们的key值是string 型的,所以得转换一下类型。

5 改正:

 def decrypt(self, enc):
        """
        Requires hex encoded param to decrypt
        """
        enc = a2b_hex(enc)
        iv = enc[:16]
        enc = enc[16:]
        cipher = AES.new(self.key.encode(), AES.MODE_CBC, iv)   #改动点在这里
        return unpad(cipher.decrypt(enc).decode("utf-8"))

 

posted on 2021-04-20 11:21  学弟1  阅读(2900)  评论(0编辑  收藏  举报

导航