Crypto

#!/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))


# #1、获取联网核查图片(老接口)
	def getImgByCIdAndName(self, cId, cName, busFlowId=0):
		paramDict = {
				"cId": cId,
				"cName": cName,
				"busFlowId": busFlowId
		}
		return self.cweispost(paramDict, "getImgByCIdAndName")

  

posted @ 2018-10-10 11:07  wly_561  阅读(198)  评论(0编辑  收藏  举报