python爬虫进行AES解密遇到的问题

965 阅读1分钟

1、TypeError: Object type <class 'str'> cannot be passed to C code

报错如下:

  File "C:\Python311\Lib\site-packages\Crypto\Util\_raw_api.py", line 143, 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

AES.new 方法的参数,需要为 bytes/bytearray/memoryview 类型,报错代码中传递的是字符串类型,将其转为 bytes 类型

在这里插入图片描述

解决办法:key、iv 参数都进行encode编码,即可解决

key = key.encode()
iv = iv.encode()

或者加上utf-8编码

key = key.encode('utf-8')
iv = iv.encode('utf-8')

参考链接:

1、爬虫的Crypto加密出现 TypeError: Object type class ‘str‘ cannot be passed to C code
2: 报错解决:TypeError: Object type class 'str' cannot be passed to C code
3: TypeError: Object type <class ‘str‘> cannot be passed to C code
4、Crypto.AES 报错 | TypeError: Object type

2、UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfb in position 2: invalid start byte

报错:

    decrypt_res = decrypted.decode('utf-8')
                  ^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfb in position 2: invalid start byte

解决思路:error参数值改为ignore 修改字符集参数,一般这种情况出现得较多是在国标码(GBK)和utf8之间选择出现了问题。 出现异常报错是由于设置了decode()方法的第二个参数errors为严格(strict)形式造成的,因为默认就是这个参数,将其更改为ignore等即可。例如: line.decode("utf8","ignore")

#正确代码:
decrypt_res = decrypted.decode('utf-8', 'ignore')

参考链接:
1、Python3解决UnicodeDecodeError: 'utf-8' codec can't decode byte..问题最快解决方案

3、AES算法CBC模式加密字符串后再解密出现乱码问题

解决方法:
每次加解密都需要重新生成一个 AES 对象

参考链接:
1、解决AES算法CBC模式加密字符串后再解密出现乱码问题