請求頭鑒權、請求參數加密、返回值解密


(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)


好了,分享完畢,大家試試吧!








免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM