环境:python3.9.13
import base64,hashlib
from Crypto.Cipher import AES
class AESCipher():
def __init__(self, key):
self.key = hashlib.md5(key.encode('utf8')).hexdigest().encode('utf8')
# 最后面一定要加上.encode('utf8')意思是str转换为byte
# 否则会出现TypeError: Object type <class 'str'> cannot be passed to C code
self.BLOCK_SIZE = 32 # Bytes
self.pad = lambda s: s + (self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE) * \
chr(self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE)
self.unpad = lambda s: s[:-ord(s[len(s) - 1:])]
# 加密
def encrypt(self, raw):
raw = self.pad(raw)
cipher = AES.new(self.key, AES.MODE_ECB)
return base64.b64encode(cipher.encrypt(raw))
# 解密,针对微信用此方法即可
def decrypt(self, enc):
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_ECB)
return self.unpad(cipher.decrypt(enc)).decode('utf8')
key= '81....................' # API v3密钥
req_info = 'Y+ysoSVQ0N2BI7A9..........yNwPFsjw=='# 微信发来的带解密数据
print('解密后的结果', AESCipher(key).decrypt(req_info))
解析后报错了啊。
到底是哪里出了问题啊?网上只能找到这些资料,官方也没有搞个demo,难受,搞了几天了。。。。要疯了
python开发者可以使用已经封装好的“微信支付 V3 API Python SDK”
https://github.com/minibear2021/wechatpayv3