使用 AES 算法对字符串进行解密,Python 代码片段如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import base64
from Crypto.Cipher import AES

def aes_decrypt(encrypted_str):
"""使用AES加密算法对encrypted_str进行解密"""
bt = encrypted_str.encode()
base64_code = base64.b64decode(bt)
aes = AES.new(key=encoding_aes_key.encode(), mode=AES.MODE_CBC, iv=iv.encode())
decrypted = aes.decrypt(base64_code)

# 移除padding并解码
padding_length = decrypted[-1]
removed_padding = decrypted[:-padding_length]

# 返回明文字符串
return removed_padding.decode()

在本地运行没有异常,在测试服务器上运行时出现 TypeError: ‘iv’ is an invalid keyword argument for this function 异常,具体日志信息如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Traceback (most recent call last):
File "app.py", line 7, in <module>
import ynservice
File "/data/wechat-api/ynservice.py", line 153, in <module>
process(t_d)
File "/data/wechat-api/ynservice.py", line 89, in process
decrypted_str = aes_decrypt(encoding_content)
File "/data/wechat-api/ynservice.py", line 54, in aes_decrypt
aes = AES.new(key=encoding_aes_key.encode(), mode=AES.MODE_CBC, iv=iv.encode())
File "/usr/local/lib64/python3.6/site-packages/Crypto/Cipher/AES.py", line 95, in new
return AESCipher(key, *args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/Crypto/Cipher/AES.py", line 59, in __init__
blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
self._cipher = factory.new(key, *args, **kwargs)
TypeError: 'iv' is an invalid keyword argument for this function

通常,该问题一般都是与 pycrypto 的软件包冲突有关。

这里先尝试卸载 pycrypto 包,再安装 pycryptodome 包即可,相关命令如下:

1
2
3
4
5
# 缷载pycrypto包
pip3 uninstall pycrypto

# 安装pycryptodome包
pip3 install pycryptodome

(END)