背景:在测试中很多请求会对请求体进行一个加密的方式,如现在我们一些测试项,需要对请求进行加密
加密的方法
import sys, os sys.path.append(project_path) import time,base64 from Crypto.Cipher import AES class AESUtil: '''AES加密工具''' __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size @staticmethod def encrypt(text,iv,key): '''AES加密''' cipher = AES.new(key, AES.MODE_CBC,iv) x = AESUtil.__BLOCK_SIZE_16 - (len(text) % AESUtil.__BLOCK_SIZE_16) if x != 0: text = text + chr(x)*x text = text.encode("utf-8") msg = cipher.encrypt(text) msg = base64.b64encode(msg)
print("加密")
print(msg) return msg @staticmethod def decryt(str1,iv,key): msg=base64.b64decode(str1) # print(type(msg)) cipher = AES.new(key, AES.MODE_CBC,iv) plain_text = cipher.decrypt(msg) plain_text=plain_text.decode("utf-8")
print("解密")
print(plain_txt) return plain_text
使用方式
if __name__ == "__main__": import json data={"appkey": "265e52144f0d3ad6a599aedd", "uid": 90890999, "can_read": 1} data=AESUtil.encrypt(json.dumps(data),b'DXXXXXXXXDD25',b'DXXXXXX') AESUtil.decryt(data,,b'DXXXXXXXXDD25',b'DXXXXXX')
加密与解密的效果