请求头鉴权、请求参数加密、返回值解密

(1)进行接口测试的时候,写好接口测试用例,然后模拟请求的时候,会出现请求头鉴权。给你了key值那么可以

import hashlib
import time
import base64


def get_sha1(str_data):
sha1_str = hashlib.sha1(str(str_data)).hexdigest()
print sha1_str
return sha1_str


def get_md5(imsi):
imsi_md5 = hashlib.md5()
imsi_md5.update(str(imsi))
imsi_md5_str = imsi_md5.hexdigest()
print imsi_md5_str
return imsi_md5_str



def authenticate(owner_id="", api_id="", api_key=""):
time.sleep(1)
header = {}
time_stamp = str(int(time.time()))
sign_str = str(api_id) + str(api_key) + time_stamp
sign = hashlib.sha1(sign_str.encode("utf8")).hexdigest()
token_str = ",".join([str(owner_id), str(api_id), time_stamp, sign])
token = base64.b64encode(token_str.encode("ascii")).decode("utf-8")
header["Authorization"] = "Bearer {0}".format(token)
return header



以上说明的是 对某个值 进行sha 加密 和获取md5值 下面这个函数 是请求头 鉴权获取token的







(2)请求参数加密:

首先来写 加密方法和解密方法:


from Crypto.Cipher import AES
from Crypto import Random
import urllib


class AESCipher:
def __init__(self, key):
self.key = key.decode("base64")
print key

def encrypt(self, raw):
"""
Returns hex encoded encrypted value!
"""
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) # 对要加密的内容按16位进行补位

iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_ECB, iv)
raw = pad(raw)
return str(cipher.encrypt(raw)).encode("base64").strip()

def decrypt(self, enc):
"""
Requires hex encoded param to decrypt
"""
enc = urllib.unquote(enc).decode('utf-8') # 特殊字符(+ = ..)转换一下
enc = enc.decode("base64")
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_ECB, iv)
dec_str = cipher.decrypt(enc).strip('\x10')
return dec_str



加解密函数封装完成 那么实际当中进行调用就行:肯定有加密的key值
key=""
asc = aes_cipher.AESCipher(key=key)
enc_str = asc.encrypt(json.dumps(data))  请求的时候 data=base64.b64decode(enc_str)
要进行base64一下


这样就对请求参数进行加密了 按照给的key值


那么结果解密 也是一样


for_bs = ret.encode('base64')
aes = aes_cipher.AESCipher(decry_key)
dec = aes.decrypt(for_bs)


好了,分享完毕,大家试试吧!







猜你喜欢

转载自www.cnblogs.com/testling/p/11822300.html
今日推荐