通过jmeter客户端去访问服务端程序,需要用到私钥、公钥和密钥,还有服务端公钥
image.png
定义ApiEncryptUtil.java文件为OpenApi通信协议加解密工具类,以下代码:
package com.niiwoo.sdk.test;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;
/**
* OpenApi通信协议加解密工具类
*
*
*/
public class ApiEncryptUtil {
private final static Random random = new Random();
public static void main(String[] args) throws Exception {
Map map = generateRSAKeyPairs();
System.out.println("publicKey:===>"+map.get("publicKey"));
System.out.println("privateKey:===>"+map.get("privateKey"));
System.out.println(KeyCreate(24));
}
/**
* 生成RSA公、私钥对
*
* @return
* @throws NoSuchAlgorithmException
*/
public static Map generateRSAKeyPairs() throws NoSuchAlgorithmException {
Map keyPairMap = new HashMap();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = generator.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
keyPairMap.put("publicKey", Base64.encodeBase64String(publicKey.getEncoded()));
keyPairMap.put("privateKey", Base64.encodeBase64String(privateKey.getEncoded()));
return keyPairMap;
}
public static byte[] signByPrivateKey(byte[] data, PrivateKey privateKey)
throws Exception {
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(privateKey);
sig.update(data);
byte[] ret = sig.sign();
return ret;
}
public static PrivateKey getPrivateKeyFromString(String base64String)
throws InvalidKeySpecException, NoSuchAlgorithmException {
byte[] bt = Base64.decodeBase64(base64String.getBytes());
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bt);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
return privateKey;
}
/**
* 生成16位AES随机密钥
* @return
*/
public static String getAESRandomKey(){
long longValue = random.nextLong();
return String.format("%016x", longValue);
}
public static String KeyCreate(int KeyLength) {
String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*:_+<>?~#$@";
Random random = new Random();
StringBuffer Keysb = new StringBuffer();
// 生成指定位数的随机秘钥字符串
for (int i = 0; i < KeyLength; i++) {
int number = random.nextInt(base.length());
Keysb.append(base.charAt(number));
}
return Keysb.toString();
}
}
Eclipse客户端执行代码生成私钥、公钥和密钥
image.png
服务端公钥是在配置文件已经配置好了
image.png
使用生成的私钥、公钥和密钥替换在jmeter上的配置,修改验签TianChengSampler.java文件
/**
*TianCheng Sampler ,for tiancheng uap2.0
*/
package org.apache.niiwoo;
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.PrintStream;
//import java.io.UnsupportedEncodingException;
//import java.net.MalformedURLException;
//import java.net.URISyntaxException;
//import java.net.URL;
//import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.Collections;
import java.util.HashMap;
//import java.util.HashSet;
//import java.util.Iterator;
//import java.util.List;
import java.util.Map;
//import java.util.Set;
//import java.util.concurrent.Callable;
//import java.util.concurrent.ExecutionException;
//import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.Date;
import java.util.UUID;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.jmeter.config.Argument;
//import org.apache.jmeter.config.Arguments;
//import org.apache.jmeter.config.ConfigTestElement;
//import org.apache.jmeter.engine.event.LoopIterationEvent;
//import org.apache.jmeter.protocol.http.control.AuthManager;
//import org.apache.jmeter.protocol.http.control.CacheManager;
//import org.apache.jmeter.protocol.http.control.Cookie;
//import org.apache.jmeter.protocol.http.control.CookieManager;
//import org.apache.jmeter.protocol.http.control.DNSCacheManager;
//import org.apache.jmeter.protocol.http.control.HeaderManager;
//import org.apache.jmeter.protocol.http.parser.BaseParser;
//import org.apache.jmeter.protocol.http.parser.LinkExtractorParseException;
//import org.apache.jmeter.protocol.http.parser.LinkExtractorParser;
//import org.apache.jmeter.protocol.http.sampler.ResourcesDownloader.AsynSamplerResultHolder;
//import org.apache.jmeter.protocol.http.util.ConversionUtils;
//import org.apache.jmeter.protocol.http.util.EncoderCache;
//import org.apache.jmeter.protocol.http.util.HTTPArgument;
//import org.apache.jmeter.protocol.http.util.HTTPConstants;
//import org.apache.jmeter.protocol.http.util.HTTPConstantsInterface;
//import org.apache.jmeter.protocol.http.util.HTTPFileArg;
//import org.apache.jmeter.protocol.http.util.HTTPFileArgs;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
//import org.apache.jmeter.testelement.TestElement;
//import org.apache.jmeter.testelement.TestIterationListener;
//import org.apache.jmeter.testelement.TestStateListener;
//import org.apache.jmeter.testelement.ThreadListener;
//import org.apache.jmeter.testelement.property.BooleanProperty;
//import org.apache.jmeter.testelement.property.CollectionProperty;
//import org.apache.jmeter.testelement.property.IntegerProperty;
//import org.apache.jmeter.testelement.property.JMeterProperty;
//import org.apache.jmeter.testelement.property.PropertyIterator;
//import org.apache.jmeter.testelement.property.StringProperty;
//import org.apache.jmeter.testelement.property.TestElementProperty;
//import org.apache.jmeter.threads.JMeterContext;
//import org.apache.jmeter.threads.JMeterContextService;
//import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
//import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
//import org.apache.oro.text.MalformedCachePatternException;
//import org.apache.oro.text.regex.Pattern;
//import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.niiwoo.commons.Base64;
import org.apache.niiwoo.commons.ThreeDes;
import org.apache.niiwoo.commons.EncryptUtil;
import org.apache.niiwoo.commons.RSA;
import org.apache.niiwoo.commons.HttpRequestUtil;
import com.alibaba.fastjson.JSONObject;
/**
*TianCheng Sampler class
*/
public class TianChengSampler extends AbstractSampler {
private static final long serialVersionUID = 240L;
private static final Logger log = LoggingManager.getLoggerForClass();
// The name of the property used to hold our data
public static final String DATA = "TianChengSampler.data"; //$NON-NLS-1$
public static final String serverURL = "TianChengSampler.serverURL"; //$NON-NLS-1$
public static final String orgCode = "TianChengSampler.orgCode"; //$NON-NLS-1$
public static final String userName = "TianChengSampler.userName"; //$NON-NLS-1$
public static final String userPassword = "TianChengSampler.userPassword"; //$NON-NLS-1$
public static final String functionCode = "TianChengSampler.functionCode"; //$NON-NLS-1$
public static final String clientPrivateKey = "TianChengSampler.clientPrivateKey"; //$NON-NLS-1$
public static final String clientPublicKey = "TianChengSampler.clientPublicKey"; //$NON-NLS-1$
public static final String serverPublicKey = "TianChengSampler.serverPublicKey"; //$NON-NLS-1$
public static final String threeDesKey = "TianChengSampler.threeDesKey"; //$NON-NLS-1$
private static AtomicInteger classCount = new AtomicInteger(0); // keep track of classes created
// (for instructional purposes only!)
public TianChengSampler() {
classCount.incrementAndGet();
trace("TianChengSampler()");
}
/**
* 发送HTTP请求
*
* @throws Exception
*/
public String postHttpRequest() throws Exception
{
String data = getData(); // Sampler data
String server_url = getServerURL();
String org_code = getOrgCode();
String username = getUserName();
String password = getUserPassword();
String function_code = getFunctionCode();
String client_private_key = getClientPrivateKey();
//String client_public_key = getClientPublicKey();
String server_public_key = getServerPublicKey();
String three_des_key = getThreeDesKey();
UUID uuid = UUID.randomUUID();
String transNo = uuid.toString();
Map root = new HashMap();
Map header = new HashMap();
Map securityInfo = new HashMap();
header.put("orgCode", org_code.toString());
header.put("transNo", transNo);
header.put("transDate", new Date().toString());
header.put("userName", username.toString());
header.put("userPassword", EncryptUtil.md5(password.toString()));
header.put("functionCode", function_code.toString());
String headerStr = JSONObject.toJSONString(header);
//使用pcks8编码格式的私钥
String sigValue = RSA.sign(headerStr, client_private_key);
securityInfo.put("signatureValue", sigValue);
byte[] encBusiData = ThreeDes.encryptMode(three_des_key.getBytes(), data.getBytes("UTF-8"));
root.put("header", headerStr);
root.put("busiData", Base64.getBase64ByByteArray(encBusiData));
root.put("securityInfo", securityInfo);
String message = JSONObject.toJSONString(root);
log.debug("向BOSS发送请求:" + message);
String res = HttpRequestUtil.sendJsonWithHttp(server_url, message);
//System.out.println("响应Message:" + res);
JSONObject msgJSON = JSONObject.parseObject(res);
String head = msgJSON.getString("header");
if(!JSONObject.parseObject(head).getString("rtCode").equals("E0000000"))
{
log.debug("消息返回失败");
String retMessage = "返回失败,错误码rtCode:";
switch(JSONObject.parseObject(head).getString("rtCode")) {
case "E0000001":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 请求消息为空!";
break;
case "E0000002":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 验签失败!";
break;
case "E0000003":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 请求数据解析失败!";
break;
case "E0000004":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 请求的用户不存在!";
break;
case "E0000005":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 用户名密码错误!";
break;
case "E0000006":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 交易流水重复!";
break;
case "E0000007":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", base64解码失败!";
break;
case "E0000008":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 3des解码失败!";
break;
case "E0000009":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 错误的请求方式!";
break;
case "E0000010":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 用户余额不足!";
break;
case "E0000011":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 内部响应超时!";
break;
case "E0000012":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 功能号格式错误!";
break;
case "E0000013":
retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 系统正在升级中,请稍后再试!";
break;
default : retMessage += ", 未定义的错误码!";
}
return retMessage;
}
//验证签名
String securityInfo1 = msgJSON.getString("securityInfo");
String signatureValue = JSONObject.parseObject(securityInfo1).getString("signatureValue");
boolean verifyFlag = RSA.verify(msgJSON.getString("header"), signatureValue, server_public_key);
if(verifyFlag == true){
log.debug("验签成功");
byte[] b64 = Base64.getFormBase64ByString(msgJSON.getString("busiData"));
byte[] busiData = ThreeDes.decryptMode(three_des_key.getBytes(), b64);
String rspData = new String(busiData, 0, busiData.length, "UTF-8");
log.debug("响应BusiData明文:" + rspData);
return rspData;
}else{
log.debug("验签失败");
return "响应数据验签失败!";
}
}
/**
* {@inheritDoc}
*/
@Override
public SampleResult sample(Entry e) {
log.debug("into SampleResult.sample");
trace("sample()");
SampleResult res = new SampleResult();
boolean isOK = false; // Did sample succeed?
String data = getData(); // Sampler data
String response = null;
res.setSampleLabel(getTitle());
/*
* Perform the sampling
*/
res.sampleStart(); // Start timing
try {
// Do something here ...
response = postHttpRequest(); //Thread.currentThread().getName();
/*
* Set up the sample result details
*/
res.setSamplerData(data);
res.setResponseData(response, null);
res.setDataType(SampleResult.TEXT);
res.setResponseCodeOK();
res.setResponseMessage("OK");// $NON-NLS-1$
isOK = true;
} catch (Exception ex) {
log.debug("", ex);
res.setResponseCode("500");// $NON-NLS-1$
res.setResponseMessage(ex.toString());
}
res.sampleEnd(); // End timimg
res.setSuccessful(isOK);
return res;
}
/**
* @return a string for the sampleResult Title
*/
private String getTitle() {
log.debug("into getTitle");
return this.getName();
}
/**
* @return the data for the sample
*/
public String getData() {
return getPropertyAsString(DATA);
}
/**
* @return the serverURL for the sample
*/
public String getServerURL() {
return getPropertyAsString(serverURL);
}
/**
* @return the orgCode for the sample
*/
public String getOrgCode() {
return getPropertyAsString(orgCode);
}
public String getUserName() {
return getPropertyAsString(userName);
}
public String getUserPassword() {
return getPropertyAsString(userPassword);
}
public String getFunctionCode() {
return getPropertyAsString(functionCode);
}
public String getClientPrivateKey() {
return getPropertyAsString(clientPrivateKey);
}
public String getClientPublicKey() {
return getPropertyAsString(clientPublicKey);
}
public String getServerPublicKey() {
return getPropertyAsString(serverPublicKey);
}
public String getThreeDesKey() {
return getPropertyAsString(threeDesKey);
}
/*
* Helper method
*/
private void trace(String s) {
String tl = getTitle();
String tn = Thread.currentThread().getName();
String th = this.toString();
log.debug(tn + " (" + classCount.get() + ") " + tl + " " + s + " " + th);
}
}
修改前
image.png
修改后
image.png