python加密解密算法_Python-AES加密算法接口测试

前言

先前已经学过了Python-SHA256加密算法接口测试,今天我跟大家讲解一下AES加密算法的接口如何写python脚本进行测试。

一:安装pycryptodome模块

pip install pycryptodome

二:定义AES加密的方法,本次使用ECB模式加密

import base64

from Crypto.Cipher import AES

from Crypto.Util.Padding import pad, unpad

#自定义填充模式-zeropadding

#字符长度不足16(128位)

def add_to_16(value):

while len(value)%16 !=0:

value += '\0'

return value.encode()#转成字节形式

#定义加密方法

def encrypt_ecb(pt,key='hello123321olleh'):

#1初始化加密器:128位key,ECB模式加密

aes=AES.new(add_to_16(key),AES.MODE_ECB)

#2.处理数据块-128位,pkcs7模式

block=pad(pt.encode('utf8'),16)

#3.加密数据块

tmp=aes.encrypt(block)

#4.base64编码数据

ct=base64.encodebytes(tmp).decode()

return ct

三:定义解密的方法

#定义解密方法

def decrypt_ecb(ct,key='hello123321olleh'):

# 1.初始化加密器:128位key,ECB模式加密

aes = AES.new(add_to_16(key), AES.MODE_ECB)

# 2.解码base64

block=base64.decodebytes(ct.encode('utf8'))

#3.解密数据块

tmp = aes.decrypt(block)

# print(tmp)

#4.反填充数据-转成字符串

pt=unpad(tmp,16).decode('utf8')

return pt

四:代码如下

import base64

from Crypto.Cipher import AES

from Crypto.Util.Padding import pad, unpad

#自定义填充模式-zeropadding

#字符长度不足16(128位)

def add_to_16(value):

while len(value)%16 !=0:

value += '\0'

return value.encode()#转成字节形式

#定义加密方法

def encrypt_ecb(pt,key='hello123321olleh'):

#1初始化加密器:128位key,ECB模式加密

aes=AES.new(add_to_16(key),AES.MODE_ECB)

#2.处理数据块-128位,pkcs7模式

block=pad(pt.encode('utf8'),16)

#3.加密数据块

tmp=aes.encrypt(block)

#4.base64编码数据

ct=base64.encodebytes(tmp).decode()

return ct

#定义解密方法

def decrypt_ecb(ct,key='hello123321olleh'):

# 1.初始化加密器:128位key,ECB模式加密

aes = AES.new(add_to_16(key), AES.MODE_ECB)

# 2.解码base64

block=base64.decodebytes(ct.encode('utf8'))

#3.解密数据块

tmp = aes.decrypt(block)

# print(tmp)

#4.反填充数据-转成字符串

pt=unpad(tmp,16).decode('utf8')

return pt

#完成加密接口测试

if __name__ == '__main__':

import requests

payload = '''

{

"action":"add_case",

"data":{

"title": "test12345",

"summary": "test11111111111111111",

"tag": "test",

"protocol": "HTTP",

"method": "GET",

"path": "/",

"params": "test"

}

}

'''

# 加密原始报文

ct = encrypt_ecb(payload)

body = {'code': ct}

# 发送加密报文

resp = requests.post('http://localhost:9090/api/aes', data=body)

code=resp.json()['code']

print(decrypt_ecb(code))

你可能感兴趣的:(python加密解密算法)