Jmeter 二次开发 函数助手 AES加解密
- 1. 环境准备
- 2. 关键技术说明
- 2.1 离线导包
- 2.2 示例代码
- 3. 代码包
- 4. 结果演示
1. 环境准备
- IDE :IntelliJ IDEA 2021.1.1 x64
- JAVA环境 :jdk1.8.0_251
- 离线导包:导入Jmeter安装目录下lib/ext下的ApacheJmeter_function.jar 和 ApacheJmeter_cotre
2. 关键技术说明
2.1 离线导包
重点:
- 程序依赖的jar包需要放在ext路径下
- 程序依赖的class需要放在 ApacheJmeter_function 中,和新开发的class放在同级
2.2 示例代码
以AES CBC加密为例
package org.apache.jmeter.functions;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;public class AES_CBC_Encrypt extends AbstractFunction {//自定义function的描述private static final List<String> desc = new LinkedList<>();//function名称private static final String KEY = "__AES_CBC_Encrypt";static {desc.add("json_input");desc.add("secret_input");desc.add("iv_input");}private CompoundVariable json_input;private CompoundVariable secret_input;private CompoundVariable iv_input;// 函数的逻辑执行主体/** {@inheritDoc} */@Overridepublic String execute(SampleResult previousResult, Sampler currentSampler)throws InvalidVariableException {String bodyData = String.valueOf(json_input.execute());String secret_key = String.valueOf(secret_input.execute());String iv_key = String.valueOf(iv_input.execute());return AES_CBC.encryptCBC(bodyData, secret_key, iv_key);}// 用来接收和处理GUI界面的参数的传值/** {@inheritDoc} */@Overridepublic void setParameters(Collection<CompoundVariable> collection) throws InvalidVariableException {checkParameterCount(collection, 3);Object[] values = collection.toArray();json_input = (CompoundVariable) values[0];secret_input = (CompoundVariable) values[1];iv_input = (CompoundVariable) values[2];}// 用来定义函数的名称,把自定义的内容显示在函数对话框中/** {@inheritDoc} */@Overridepublic String getReferenceKey() {return KEY;}// 用来设置GUI界面的函数对话框,把自己定义的参数给显示在jmeter的GUI界面上/** {@inheritDoc} */@Overridepublic List<String> getArgumentDesc() {return desc;}public static void main(String[] args) { // AES支持三种长度的密钥:128位、192位、256位。// 代码中这种就是128位的加密密钥,16字节 * 8位/字节 = 128位。String srt = "123456778";String iv_seed = "1234567887654321";System.out.println("密钥key:" + srt);System.out.println("iv:" + iv_seed);System.out.println("--------AES_CBC加密解密---------");String cbcResult = AES_CBC.encryptCBC(aes, srt, iv_seed);System.out.println("aes_cbc加密结果:" + cbcResult);System.out.println();System.out.println("---------解密CBC---------");String cbcDecrypt = AES_CBC.decryptCBC(cbcResult, srt, iv_seed);System.out.println("aes解密结果:" + cbcDecrypt);System.out.println();}
}
3. 代码包
https://download.csdn.net/download/weixin_39451323/88218178
4. 结果演示
加密:
${__AES_CBC_Encrypt({"token":"0e84b297-d8f2-4779-b7f1-60966ed19ce1"},qwertyuiiuytrewq,1234567887654321)}
解密:
${__AES_CBC_Decrypt(RwHL3jF01WDd9T3tKRUi2XIWuPJ/a5H78mExd8I3/fArE6778r7EsbSUwjx7cncAkkfrfc6QV53NrStWBnissA==,qwertyuiiuytrewq,1234567887654321)}
参考资料:jmeter官方函数https://github.com/ufctester/apache-jmeter/tree/master/src/functions/org/apache/jmeter/functions