在接口测试中,会遇到加密的请求数据,例如:经常使用的base64加密,AES加密,在这里,简述用Python转化AES的加密方法html
例如:对用户名进行AES加密,6位的用户名不知足16个字节,就须要补充位数。
算法库详解: http://www.javashuo.com/article/p-duswtfre-gk.htmlpython
安装 Crypto不是自带的模块,须要下载。http://www.voidspace.org.uk/python/modules.shtml#pycrypto算法
安装好引用的时候,提示找不到Crypto,找了不少资料,缘由是 C:\Python27\Lib\site-packages在这个路径下面有一个文件夹叫作crypto,把它的首字母改为大写,便是Crypto 就没有问题了json
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