Python+requests+pytest+allure封装接口自动化5-MD5、RSA、AES加密方式封装

本文介绍了如何在Python中实现MD5哈希加密以及AES和RSA的加解密操作。对于AES,展示了使用pycryptodome库进行ECB和CBC模式的加密和解密。同时,也详细说明了RSA非对称加密的使用,包括公钥和私钥的生成及数据加密解密、签名验证的过程。
摘要由CSDN通过智能技术生成

一、MD5加密方式封装

在common目录中新建一个encry_decry.py文件

def md5(string):
    return hashlib.md5(string.encode(encoding='UTF-8')).hexdigest()

二、AES加密封装

aes加解密:对称加密算法,对称指的意思就是加密和解密用到的私钥是一样的,在做接口测试时,需

要找开发要私钥

rsa加解密:非对称解密算法,非对称指的是加密和解密用到的钥匙不一样,对于rsa来说他有公钥和私

钥,如果用公钥加密则用私钥解密,如果用私钥加密则用公钥解密

注意:

要实现aes和rsa需要用到第三方库:

windows 安装vc++14 可能需要,那就升级下pip再重新装
pip install pycryptodome -i https://pypi.douban.com/simple
mac下
python3 -m pip install pycryptodome -i https://pypi.douban.com/simple

装完之后如果代码还报错,那么记得修改一下下述位置


class AesEncrypt:
    """
    AES加密
    windows 安装vc++14 可能需要,那就升级下pip再重新装
    pip install pycryptodome -i https://pypi.douban.com/simple

    mac下 pip install pycryptodome -i https://pypi.douban.com/simple
    """

    def __init__(self, key):
        self.key = key  # 初始化密钥
        self.length = AES.block_size  # 初始化数据块大小
        self.aes = AES.new(self.key.encode("utf8"), AES.MODE_SIV)  # 初始化AES,ECB模式的实例
        # 截断函数,去除填充的字符
        self.unpad = lambda date: date[0:-ord(date[-1])]

    def pad(self, text):
        """
        填充函数,使被加密数据的字节码长度是block_size的整数倍
        """
        count = len(text.encode('utf-8'))
        add = self.length - (count % self.length)
        entext = text + (chr(add) * add)
        return entext

    def encrypt(self, encrData):  # 加密函数
        res = self.aes.encrypt(self.pad(encrData).encode("utf8"))
        msg = str(base64.b64encode(res), encoding="utf8")
        return msg

    def decrypt(self, decrData):  # 解密函数
        res = base64.decodebytes(decrData.encode("utf8"))
        msg = self.aes.decrypt(res).decode("utf8")
        return self.unpad(msg)


class AesEncrypt1:
    """
    AES加密
    windows 安装vc++14 可能需要,那就升级下pip再重新装
    pip install pycryptodome -i https://pypi.douban.com/simple

    mac下 pip install pycryptodome -i https://pypi.douban.com/simple
    """

    def __init__(self, key):
        self.key = key  # 初始化密钥
        self.length = AES.block_size  # 初始化数据块大小
        # 截断函数,去除填充的字符
        self.unpad = lambda date: date[0:-ord(date[-1])]
        self.iv = 'absqievlj12hai12'

    def pad(self, text):
        """
        填充函数,使被加密数据的字节码长度是block_size的整数倍
        """
        count = len(text.encode('utf-8'))
        add = self.length - (count % self.length)
        entext = text + (chr(add) * add)
        return entext

    def encrypt(self, encrData):  # 加密函数
        aes = AES.new(self.key.encode("utf8"), AES.MODE_CBC, self.iv.encode('utf8'))
        res = aes.encrypt(self.pad(encrData).encode("utf8"))
        msg = str(base64.b64encode(res), encoding="utf8")
        return msg

    def decrypt(self, decrData):  # 解密函数
        aes = AES.new(self.key.encode("utf8"), AES.MODE_CBC, self.iv.encode('utf8'))
        res = base64.decodebytes(decrData.encode("utf8"))
        msg = aes.decrypt(res).decode("utf8")
        return self.unpad(msg)

三、RSA加密封装


class RsaEncrypt():
    """
    初始化时必须传递公钥和私钥存储的文件路径
    """

    def __init__(self, public_file, private_file):
        self.public_file = public_file
        self.private_file = private_file

    def generate_key(self):
        """
        这个方法是生成公钥和私钥的,在实际企业测试过程中,开发会提供公钥和私钥,我们不用自己生成
        :return:
        """
        random_generator = Random.new().read
        rsa = RSA.generate(2048, random_generator)
        # 生成私钥
        private_key = rsa.exportKey()
        print(private_key.decode('utf-8'))
        # 生成公钥
        public_key = rsa.publickey().exportKey()
        print(public_key.decode('utf-8'))

        with open(self.private_file, 'wb')as f:
            f.write(private_key)

        with open(self.public_file, 'wb')as f:
            f.write(public_key)
            print('生成')

    # 从秘钥文件中获取密钥
    def get_key(self, key_file):
        with open(key_file) as f:
            data = f.read()
            key = RSA.importKey(data)
        return key

    # rsa 公钥加密数据
    def encrypt_data(self, msg):
        public_key = self.get_key(self.public_file)
        cipher = PKCS1_cipher.new(public_key)
        encrypt_text = base64.b64encode(cipher.encrypt(bytes(msg.encode("utf8"))))
        return encrypt_text.decode('utf-8')

    # rsa 私钥解密数据
    def decrypt_data(self, encrypt_msg):
        private_key = self.get_key(self.private_file)
        cipher = PKCS1_cipher.new(private_key)
        back_text = cipher.decrypt(base64.b64decode(encrypt_msg), 0)
        return back_text.decode('utf-8')

    # rsa 私钥签名数据
    def rsa_private_sign(self, data):
        private_key = self.get_key(self.private_file)
        signer = PKCS1_signature.new(private_key)
        digest = SHA.new()
        digest.update(data.encode("utf8"))
        sign = signer.sign(digest)
        signature = base64.b64encode(sign)
        signature = signature.decode('utf-8')
        return signature

    # rsa 公钥验证签名
    def rsa_public_check_sign(self, text, sign):
        publick_key = self.get_key(self.public_file)
        verifier = PKCS1_signature.new(publick_key)
        digest = SHA.new()
        digest.update(text.encode("utf8"))
        return verifier.verify(digest, base64.b64decode(sign))
Python是一种广泛使用的编程语言,因其易学易用、灵活性和可扩展性而备受欢迎。requestsPython的一个库,它提供了一种简单且易于使用的方式来发送HTTP请求。pytestPython的另一个库,它提供了一种用于编写和运行测试的框架。allure是一个测试报告生成工具,可以为测试结果提供美观和易读的报告。 在接口自动化测试中,可以使用Pythonrequests库来发送HTTP请求,并使用pytest框架来编写和运行测试。可以使用Excel来存储测试数据、预期结果和实际结果。使用allure工具可以生成美观的测试报告。 以下是使用Python requestspytestallure进行接口自动化测试的一般步骤: 1. 安装Pythonrequestspytestallure 2. 创建一个Excel文件,输入测试数据、预期结果和实际结果 3. 创建一个pytest测试文件,并使用requests库发送HTTP请求,比较预期结果和实际结果 4. 在pytest测试文件中添加allure装饰器,以便生成测试报告 5. 运行pytest测试文件并生成allure测试报告 例如,以下是一个使用Python requestspytestallure进行接口自动化测试的示例代码: ```python import requests import pytest import allure import openpyxl @allure.title("测试接口") @pytest.mark.parametrize("test_input, expected", [(1, "success"), (2, "fail")]) def test_api(test_input, expected): # 从Excel文件中获取测试数据和预期结果 wb = openpyxl.load_workbook("testdata.xlsx") sheet = wb.active test_data = sheet.cell(row=test_input, column=1).value expected_result = sheet.cell(row=test_input, column=2).value # 发送HTTP请求 response = requests.get("http://example.com/api", params=test_data) actual_result = response.text # 比较预期结果和实际结果 assert actual_result == expected_result, f"预期结果:{expected_result},实际结果:{actual_result}" # 添加allure描述 allure.attach("请求参数", str(test_data)) allure.attach("预期结果", str(expected_result)) allure.attach("实际结果", str(actual_result)) ``` 在上面的代码中,使用了pytest的parametrize装饰器来传递测试数据和预期结果。使用openpyxl库从Excel文件中获取测试数据和预期结果。使用requests库发送HTTP请求并比较预期结果和实际结果。使用allure的装饰器来添加测试描述。最后,运行pytest测试文件并生成allure测试报告。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值