API接口加密,解决自动化中登录问题

一、加密方式

  • AES:对称加密,快
  • RAS:非对称加密,慢
  • AES+RAS:安全+高效

加密过程:字符串=====》字节流====》加密的字节流(算法),解密有可能出现乱码,所以不能直接转成字符串,一般采用base64,base64的结果一定是ASCII范围内的字节,所以一定可以转成字符串

字符串转成字节流:encode

字节流转成字符串:decode

二、接口加密

请求:加密,响应:解密

  1. 加密API请求错误
  • 格式不正确
  • 加密格式不正确
  • 请求参数值不正确

三、第三方库实现加密

  1. 安装pycryptodome:pip3 install pycryptodome

四、加密方式

以下加密信息,测试端和接口端必须一致

  • 加密算法
  • 密钥
  • 加密模式
  • IV变量

五、加密代码

加密算法

python 复制代码
import base64
import json
from Crypto.Cipher import AES
import base64

#AEX加密
key = b"sanmu's aes_key!"   #16位字节作为密钥
mode=AES.MODE_EAX   #EAX加密模式
IV=b"0"*16

class Encoder:
    @staticmethod
    def encrypt(data:dict)->str:
        """
        AES加密
        1.接收字典
        2.字典转字符串
        3.字符串转字节
        4.字节进行加密
        5.对加密结果进行bas64
        6.编码结果转字符串
        :param data:
        :return:
        """
        encoder = AES.new(key, AES.MODE_EAX,nonce=IV)
        content_str=json.dumps(data)
        content_byte=content_str.encode('utf-8')
        content_en = encoder.encrypt_and_digest(content_byte)
        return base64.b64encode(content_en).decode("utf-8")


    @staticmethod
    def decrypt(data:str)->dict:
        """
        AES解密
        1.接收字符串
        2.字符串转字节
        3.base64解码
        4.AES解密
        5.解密结果转字符串
        6.字符串转字典
        :param data:
        :return:
       """
        encoder = AES.new(key, AES.MODE_EAX,nonce=IV)
        content_byte=base64.b64decode(data)
        content_de=encoder.decrypt(content_byte)
        content_str=content_de.decode("utf-8")
        content=json.loads(content_str)
        return content

test_api.py
import requests
from libs import  Encoder

login_info={
    'username':'sanmu',
    'password':'123456'
}

data={
    "content":Encoder.encrypt(login_info),  #内容是AES加密的,是字符串
    "cipher":"AES"
}

print(data)
'''
url='https://api.tttt.one/rest-v1/encrypt/with_json'
resp=requests.post(url,json=data)
print(resp.json())

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

相关推荐
念越6 小时前
蓝桥杯17届功能测试模拟1期题目及解析(1)
功能测试·蓝桥杯·测试用例·场景法
todoitbo7 小时前
用虚拟局域网打通 Win/Mac/Linux 三端:跨设备协作的实用方案
linux·运维·macos
Sylvia-girl8 小时前
Linux下的基本指令1
linux·运维·服务器
CDN3609 小时前
360CDN SDK 游戏盾:轻量化接入 + 强防护实测
运维·游戏·网络安全
Stewie121389 小时前
Docker 面试题
运维·docker·容器
星纬智联技术10 小时前
GEO E2E 自动化验证测试文章
运维·自动化·geo
做怪小疯子10 小时前
蚂蚁暑期 319 笔试
算法·职场和发展
jarreyer10 小时前
CentOS 7 无法使用 yum 安装软件
linux·运维·centos
脆皮的饭桶11 小时前
结合使用,实现IPVS的高可用性、利用VRRP Script 实现全能高可用
运维·服务器·网络
紫丁香11 小时前
pytest_自动化测试3
开发语言·python·功能测试·单元测试·集成测试·pytest