最近在对接管家婆,文档上只有 java php .net 的例子,写了一个python的例子,里面部分数据按需填写。
加解密代码借鉴于知乎
python里面json对象转字符串,分号和逗号默认会有空格,会导致加密和签名不通过
2020-12-16 增加部分接口调用代码
import base64
import copy
import hashlib
import requests
import time
import json
from Crypto.Cipher import AES
class GuanjiapoOpenApiRequest:
class GuanjiapoOpenApiException(Exception):
pass
DEFAULT_APP_KEY = {
'app_key': '',
}
DEFAULT_SIGN_KEY = {
'sign_key': '',
}
DEFAULT_KEY = {
'key': '',
}
DEFAULT_IV = {
'iv': '',
}
GUANJIAPO_OPEN_API_URL = {
'get_authcode': 'http://apigateway.wsgjp.com.cn/api/login',
'get_token': 'http://apigateway.wsgjp.com.cn/api/token',
}
def __init__(self, key, iv):
self.key = key.encode('utf-8')
self.iv = iv.encode('utf-8')
def pkcs7padding(self, text):
"""明文使用PKCS7填充 """
bs = 16
length = len(text)
bytes_length = len(text.encode('utf-8'))
padding_size = length if (bytes_length == length) else bytes_length
padding = bs - padding_size % bs
padding_text = chr(padding) * padding
return text + padding_text
def aes_encrypt(self, content):
""" AES加密 """
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
# 处理明文
content_padding = self.pkcs7padding(content)
# 加密
encrypt_bytes = cipher.encrypt(content_padding.encode('utf-8'))
# 重新编码
result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
return result
def aes_decrypt(self, content):
"""AES解密 """
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
content = base64.b64decode(content)
text = cipher.decrypt(content).decode('utf-8')
return text
@classmethod
def str_md5(cls, data):
"""md5加密"""
m = hashlib.md5(data.encode(