接口自动化--数据加密之AES

在接口测试中,会遇到加密的请求数据,例如:常用的base64加密,AES加密,在这里,简述用Python转化AES的加密方法

原理

  • 官网链接:https://pycryptodome.readthedocs.io/en/latest/src/cipher/aes.html
  • 在线加密/解密:https://www.sojson.com/encrypt_aes.html
  • AES加密主要包括两个步骤:密钥扩展和明文加密。
    密钥扩展:将输入的密钥(16字节、24字节和32字节)进行扩展,根据密钥长度的不同,得到扩展后的密钥进行加密的轮数也不相同,个人理解为补码。
  •   例如:对用户名进行AES加密,6位的用户名不满足16个字节,就需要补充位数。


    Python实现:Crypto算法库

算法库详解: https://segmentfault.com/a/1190000016851912

安装
Crypto不是自带的模块,需要下载。http://www.voidspace.org.uk/python/modules.shtml#pycrypto

安装好引用的时候,提示找不到Crypto,找了很多资料,原因是
C:\Python27\Lib\site-packages在这个路径下面有一个文件夹叫做crypto,把它的首字母改成大写,即是Crypto
就没有问题了

简单使用

from Crypto.Cipher import AES 
import base64 
secret = "12345678912345678912345678912345"   #由用户输入的16位或24位或32位长的初始密码字符串 
cipher = AES.new(secret)            #通过AES处理初始密码字符串,并返回cipher对象 
s = cipher.encrypt("1234567891234567")     #输入需要加密的字符串,注意字符串长度要是16的倍数。16,32,48.. 
print s                     #输出加密后的字符串 
print base64.b64encode(s)            #输出加密后的字符串的base64编码。 
print cipher.decrypt(s)             #解密

接口自动化中实现

class AesMethod:
    def __init__(self):
        self.key=key
    def pkcs7padding(self,text):
        """
        明文使用PKCS7填充,如果块长度是16,数据长度9,那么还差7个字节,就在后面补充7个0x07
        数据:  FF FF FF FF FF FF FF FF FF
        填充后:FF FF FF FF FF FF FF FF FF 07 07 07 07 07 07 07
        最终调用AES加密方法时,传入的是一个byte数组,要求是16的整数倍,因此需要对明文进行处理
        :param text: 待加密内容(明文)
        :return:填充后的数据
        """
        bs = AES.block_size  # 16
        length = len(text)
        bytes_length = len(bytes(text, encoding='utf-8'))
        # tips:utf-8编码时,英文占1个byte,而中文占3个byte
        padding_size = length if(bytes_length == length) else bytes_length
        padding = bs - padding_size % bs
        # tips:chr(padding)看与其它语言的约定,有的会使用'\0'
        padding_text = chr(padding) * padding
        return text + padding_text

    def aes_encrypt(self, data):
        key_bytes=bytes(self.key, encoding='utf-8')
        cipher = AES.new(key_bytes,mode=1)
        # 处理明文
        content_padding = self.pkcs7padding(data)
        # 加密
        encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))
        # 重新编码
        result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
        return result

猜你喜欢

转载自www.cnblogs.com/Testking/p/11991153.html