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   学弟1  阅读(3000)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示