#!/usr/bin/env python # coding=utf-8 from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex import base64 import json import requests import hashlib import time import sys # 調用的時候先使用 init的方法,而後再調用對應的接口 class cweisrequest(): def __init__(self): self.mode = AES.MODE_CBC #加密函數,若是text不是16的倍數【加密文本text必須是16的倍數】那就補足爲16的倍數 def cwiesencrypt(self, text): cryptor = AES.new(self.key, self.mode, self.key) # print cryptor #這裏祕鑰key長度必須爲16(AES-128)、24(AES-192)、或32(AES-256) length = 16 count = len(text) add = length - (count % length) text = text + ('\0' * add) self.ciphertext = cryptor.encrypt(text) return base64.b64encode(self.ciphertext) #解密後去掉補足的空格strip()去掉 def cweisdecrypt(self,text): cryptor = AES.new(self.key, self.mode, self.key) # plain_text = cryptor.decrypt(a2b_hex(text)) plain_text = cryptor.decrypt(text) return plain_text.rstrip('\0') def init(self, appid, appsecret, baseurl): self.key = appsecret[8:24].upper() self.appid = appid self.baseurl = baseurl def img2Base64(self,imgpath): with open(imgpath,"rb") as f: # b64encode是編碼,b64decode是解碼 return base64.b64encode(f.read()) def cweispost(self,paramDict, url): #將字典數據轉成json sJsonParam = json.dumps(paramDict) #對json數據使用aes加密 sParamValue = self.cwiesencrypt(sJsonParam) # print sParamValue #對ase加密以後的數據使用md5加密 lolValue = hashlib.md5(sParamValue).hexdigest().upper() # print lolValue # 獲得時間戳 timestamp = int(time.time() * 1000) # print timestamp # 序列化 sequence = [str(timestamp), self.appid, lolValue] #逆序 sequence.sort(reverse=True) # 拼接 signValue = "".join(sequence) # 對獲得的拼接字符串用sha1加密 signature = hashlib.sha1(signValue).hexdigest().upper() # print signature newParamDict = { "appid": self.appid, "lol": lolValue, "timestamp": timestamp, "sParam": sParamValue, "signature": signature } urlValue = self.baseurl + url # print urlValue,newParamDict #模擬http請求 response = requests.post(urlValue, data=newParamDict, verify=False) #獲得請求的結果 pageValue = response.content #對返回的結果用aes解密 # print pageValue return self.cweisdecrypt(base64.b64decode(pageValue)) # #一、獲取聯網覈查圖片(老接口) def getImgByCIdAndName(self, cId, cName, busFlowId=0): paramDict = { "cId": cId, "cName": cName, "busFlowId": busFlowId } return self.cweispost(paramDict, "getImgByCIdAndName")