Compare commits

...

10 Commits

Author SHA1 Message Date
jif2.zhang
26292b15c0 稳定性测试改成短链接 2025-08-12 15:50:44 +08:00
jiangr.wu@sunyard.com
7fe4118083 16进制错误码改成10进制 2025-08-12 15:04:10 +08:00
jiangr.wu@sunyard.com
4ad5250026 错误码优化 2025-08-11 18:18:36 +08:00
jif2.zhang
08ddb35bc3 1.25稳定性bug修改同步到1.26 2025-08-11 11:26:01 +08:00
jiangr.wu@sunyard.com
d40594bce1 错误码优化 2025-08-11 10:20:26 +08:00
jif2.zhang
d9bde5df32 继承自1.24版本,变更版本为1.26 2025-07-22 17:57:40 +08:00
jif2.zhang
a0cf1b1936 继承自1.24版本,更改版本为1.26 2025-07-22 17:55:13 +08:00
jif2.zhang
654e7617cb 短数据加密生成mac,短数据校验mac并解密:短链接的性能提升 2025-07-21 17:41:59 +08:00
jif2.zhang
3ecb230cf7 1.24版本更新:
在1.20版本上将1.19-1.23版本里更新的内容进行同步
2025-07-16 17:19:01 +08:00
729b6b217e 1.20 发布 2025-07-14 14:55:40 +08:00
28 changed files with 6543 additions and 1074 deletions

View File

@ -1,6 +1,12 @@
# 应用配置
# 调试模式 (true/false)
debug=true
debug=false
# 最大线程数
maxThread=20
# 总数
total=100000
# 地址列表 (格式: addX=ip:port)
addr1=baishe.fullstack.club:18889
addr1=172.1.41.129:8889

37
pom.xml
View File

@ -6,8 +6,7 @@
<groupId>com.sunyard.sge.database</groupId>
<artifactId>sydapi-database</artifactId>
<version>1.19</version>
<version>1.28</version>
<name>sydapi-database</name>
<properties>
@ -29,31 +28,41 @@
<artifactId>groovy</artifactId>
<version>2.4.15</version>
</dependency>
<dependency>
<groupId>com.sunyard</groupId>
<artifactId>proto</artifactId>
<version>1.0-20220905</version>
</dependency>
<dependency>
<groupId>com.sunyard</groupId>
<artifactId>sydapi4j</artifactId>
<version>1.15.20250711</version>
<exclusions>
<!-- 排除 log4j-api -->
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<!-- 排除 log4j-core -->
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log.version}</version>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>2.4.15</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log.version}</version>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.13.0</version> <!-- 使用最新版本 -->
<version>4.5.0</version> <!-- 使用最新版本 -->
</dependency>
</dependencies>

31
qodana.yaml Normal file
View File

@ -0,0 +1,31 @@
#-------------------------------------------------------------------------------#
# Qodana analysis is configured by qodana.yaml file #
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
#-------------------------------------------------------------------------------#
version: "1.0"
#Specify inspection profile for code analysis
profile:
name: qodana.starter
#Enable inspections
#include:
# - name: <SomeEnabledInspectionId>
#Disable inspections
#exclude:
# - name: <SomeDisabledInspectionId>
# paths:
# - <path/where/not/run/inspection>
projectJDK: "8" #(Applied in CI/CD pipeline)
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
#bootstrap: sh ./prepare-qodana.sh
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
#plugins:
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
linter: jetbrains/qodana-jvm-community:2025.1

View File

@ -0,0 +1,19 @@
package com.sunyard.sge.database;
public class Env {
private static boolean isLinux = false;
static {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
isLinux = true;
} else {
isLinux = false;
}
}
public static boolean isLinux(){
return isLinux;
}
}

View File

@ -1,9 +1,6 @@
package com.sunyard.sge.database;
import com.sunyard.sge.log.LogFactory;
import com.sunyard.sge.plus.SydLibrary;
import org.apache.logging.log4j.Logger;
import racal.sunyard.main.SydApi4j;
import java.util.List;
@ -29,11 +26,12 @@ public interface SydApi {
if (pcLogPath == null || iLogLevel < 0 || iLogLevel > 3) {
throw new IllegalArgumentException("地址不能为空且等级范围为0到3");
}
Logger logger = LogFactory.createLogger(pcLogPath, iLogLevel);
SydApi4j.setLogger(logger);
// logback 版本的日志直接由外部配置文件控制
// 初始化 C 部分日志
SydLibrary.INSTANCE.SYD_SetLogConfig(pcLogPath, pcLogPath.getBytes().length, iLogLevel);
if ( Env.isLinux() ){
// 初始化 C 部分日志
SydLibrary.INSTANCE.SYD_SetLogConfig(pcLogPath, pcLogPath.getBytes().length, iLogLevel);
}
}
/**

View File

@ -1,6 +1,10 @@
package com.sunyard.sge.database;
import com.sunyard.SydApiException;
import com.sunyard.log.ILogFactory;
import com.sunyard.log.ILogger;
import com.sunyard.sge.database.pool.HsmLinkInfo;
import com.sunyard.sge.log.LogbackFactory;
import racal.sunyard.main.SydApi4j;
import java.util.ArrayList;
@ -30,7 +34,7 @@ public class SydApi4Database extends SydApiBaseFunction {
}
if ( iKeyIndex.length != pcData.size() ) {
throw new IllegalArgumentException("批量输入数据密钥和数据数量不等");
throw new SydApiException("批量输入数据密钥和数据数量不等", 0x01000001);
}
if ( 0 == iKeyIndex.length ) {
@ -148,7 +152,7 @@ public class SydApi4Database extends SydApiBaseFunction {
}
if ( iKeyIndex.length != pcData.size() ) {
throw new IllegalArgumentException("批量输入数据密钥和数据数量不等");
throw new SydApiException("批量输入数据密钥和数据数量不等", 0x01000001);
}
if ( 0 == iKeyIndex.length ) {

View File

@ -3,12 +3,11 @@ package com.sunyard.sge.database;
import com.sunyard.SydApiException;
import com.sunyard.sge.database.pool.HsmLinkInfo;
import com.sunyard.sge.database.pool.SydApiPool;
import com.sunyard.sge.log.LogFactory;
import com.sunyard.sge.plus.ConnectHandlerManager;
import com.sunyard.sge.plus.SydLibrary;
import com.sunyard.sge.pool.CommWorker;
import com.sunyard.sge.pool.PoolConfig;
import org.apache.logging.log4j.Logger;
import com.sunyard.sge.pool.ThreadBasedConnectPool;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
@ -32,26 +31,27 @@ public class SydApiBuilder {
int iDealTimeOut,
PoolConfig config
) {
Logger log = LogFactory.getLogger();
org.slf4j.Logger log = LoggerFactory.getLogger(ThreadBasedConnectPool.class);
if ( log.isDebugEnabled() ) {
if (log.isDebugEnabled()) {
log.debug("创建链接");
log.debug("SydApiBuilder构造方法接收参数:pcIpList:{},iPortList:{},iConnectTimeOut:{},iDealTimeOut:{}", Arrays.toString(pcIpList),Arrays.toString(iPortList),iConnectTimeOut,iDealTimeOut);
log.debug("pool config {}", config);
}
// 同时初始化 jna c 的链接
int ret = ConnectHandlerManager.init(pcIpList, iPortList, iConnectTimeOut, iDealTimeOut);
if ( Env.isLinux() ) {
// 同时初始化 jna c 的链接
int ret = ConnectHandlerManager.init(pcIpList, iPortList, iConnectTimeOut, iDealTimeOut);
if ( 0 != ret ) {
throw new SydApiException(-1);
if ( 0 != ret ) {
throw new SydApiException(-1);
}
}
HsmLinkInfo[] linkInfo = HsmLinkInfo.mutiHsmLinkInfo(pcIpList, iPortList, iConnectTimeOut, iDealTimeOut);
this.pool = new SydApiPool(config, linkInfo);
longLinkWorks = new CommWorker();
warmUp( pcIpList, iPortList, iConnectTimeOut, iDealTimeOut );
// warmUp( pcIpList, iPortList, iConnectTimeOut, iDealTimeOut );
}
public CommWorker getLongLinkWorks() {

View File

@ -6,10 +6,10 @@ import com.sun.jna.ptr.IntByReference;
import com.sunyard.SydApiException;
import com.sunyard.proto.Util;
import com.sunyard.sge.bytes.BytesUtil;
import com.sunyard.sge.log.LogFactory;
import com.sunyard.sge.plus.ConnectHandlerManager;
import com.sunyard.sge.plus.SydLibrary;
import org.apache.logging.log4j.Logger;
import com.sunyard.sge.pool.ThreadBasedConnectPool;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
@ -26,9 +26,9 @@ import static com.sunyard.sge.database.SydApiConfig.BATCH_SIZE;
*/
public class SydApiLongLinkWrap implements SydApi {
private Logger log = LogFactory.getLogger();
org.slf4j.Logger log = LoggerFactory.getLogger(ThreadBasedConnectPool.class);
private SydApiBuilder builder;
private final SydApiBuilder builder;
public SydApiLongLinkWrap(SydApiBuilder builder) {
this.builder = builder;
@ -46,16 +46,11 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public byte[] SYD_SM3_Hash_ShortData(byte[] pcData) {
FutureTask<byte[]> task = builder.getLongLinkWorks().fTask(new Callable<byte[]>() {
@Override
public byte[] call() throws Exception {
return builder.get().SYD_SM3_Hash_ShortData(pcData);
}
});
FutureTask<byte[]> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM3_Hash_ShortData(pcData));
try {
return task.get();
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -64,16 +59,11 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public LongDataReturn<byte[], byte[]> SYD_SM3_Hash_LongData(byte[] pcData, int iPkgNum, byte[] pcProcData) {
FutureTask<LongDataReturn<byte[], byte[]>> task = builder.getLongLinkWorks().fTask(new Callable<LongDataReturn<byte[], byte[]>>() {
@Override
public LongDataReturn<byte[], byte[]> call() throws Exception {
return builder.get().SYD_SM3_Hash_LongData(pcData, iPkgNum, pcProcData);
}
});
FutureTask<LongDataReturn<byte[], byte[]>> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM3_Hash_LongData(pcData, iPkgNum, pcProcData));
try {
return task.get();
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -82,16 +72,11 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public byte[] SYD_SM4_ShortData(int iKeyIndex, byte[] pcData, int iFlag) {
FutureTask<byte[]> task = builder.getLongLinkWorks().fTask(new Callable<byte[]>() {
@Override
public byte[] call() throws Exception {
return builder.get().SYD_SM4_ShortData(iKeyIndex, pcData, iFlag);
}
});
FutureTask<byte[]> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4_ShortData(iKeyIndex, pcData, iFlag));
try {
return task.get();
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -100,16 +85,11 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public byte[] SYD_SM4_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, int iFlag) {
FutureTask<byte[]> task = builder.getLongLinkWorks().fTask(new Callable<byte[]>() {
@Override
public byte[] call() throws Exception {
return builder.get().SYD_SM4_LongData(iKeyIndex, pcData, iPkgNum, iFlag);
}
});
FutureTask<byte[]> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4_LongData(iKeyIndex, pcData, iPkgNum, iFlag));
try {
return task.get();
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -119,16 +99,11 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public LongDataReturn<byte[], byte[]> SYD_SM4Mac_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, byte[] pcProcData) {
FutureTask<LongDataReturn<byte[], byte[]>> task = builder.getLongLinkWorks().fTask(new Callable<LongDataReturn<byte[], byte[]>>() {
@Override
public LongDataReturn<byte[], byte[]> call() throws Exception {
return builder.get().SYD_SM4Mac_LongData(iKeyIndex, pcData, iPkgNum, pcProcData);
}
});
FutureTask<LongDataReturn<byte[], byte[]>> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4Mac_LongData(iKeyIndex, pcData, iPkgNum, pcProcData));
try {
return task.get();
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -137,16 +112,11 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public LongDataReturn<byte[], Boolean> SYD_SM4Mac_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, byte[] pcProcData, byte[] pcMac) {
FutureTask<LongDataReturn<byte[], Boolean>> task = builder.getLongLinkWorks().fTask(new Callable<LongDataReturn<byte[], Boolean>>() {
@Override
public LongDataReturn<byte[], Boolean> call() throws Exception {
return builder.get().SYD_SM4Mac_LongData(iKeyIndex, pcData, iPkgNum, pcProcData, pcMac);
}
});
FutureTask<LongDataReturn<byte[], Boolean>> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4Mac_LongData(iKeyIndex, pcData, iPkgNum, pcProcData, pcMac));
try {
return task.get();
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -155,16 +125,11 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public byte[] SYD_SM4Mac_ShortData(int iKeyIndex, byte[] pcData) {
FutureTask<byte[]> task = builder.getLongLinkWorks().fTask(new Callable<byte[]>() {
@Override
public byte[] call() throws Exception {
return builder.get().SYD_SM4Mac_ShortData(iKeyIndex, pcData);
}
});
FutureTask<byte[]> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4Mac_ShortData(iKeyIndex, pcData));
try {
return task.get();
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -173,48 +138,26 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public boolean SYD_SM4Mac_ShortData(int iKeyIndex, byte[] pcData, byte[] pcMac) {
FutureTask<Boolean> task = builder.getLongLinkWorks().fTask(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return builder.get().SYD_SM4Mac_ShortData(iKeyIndex, pcData, pcMac);
}
});
FutureTask<Boolean> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4Mac_ShortData(iKeyIndex, pcData, pcMac));
try {
return task.get();
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
}
}
private DataAndMac SYD_SM4_AllInOne(int iEncKeyIndex, int iMacKeyIndex, byte[] pcData){
DataAndMac SYD_SM4_EncryptAndMac_ShortData_java(int iEncKeyIndex, int iMacKeyIndex, byte[] pcData) {
try {
FutureTask<byte[]> taskEnc = builder.getLongLinkWorks().fTask(new Callable<byte[]>() {
@Override
public byte[] call() throws Exception {
return builder.get().SYD_SM4_ShortData(iEncKeyIndex, pcData, Consts.ECB_ENC);
}
});
FutureTask<DataAndMac> taskEnc = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4_EncryptAndMac_ShortData(iEncKeyIndex, iMacKeyIndex, pcData));
byte[] enData = taskEnc.get();
FutureTask<byte[]> taskMac = builder.getLongLinkWorks().fTask(new Callable<byte[]>() {
@Override
public byte[] call() throws Exception {
return builder.get().SYD_SM4Mac_ShortData(iMacKeyIndex, enData);
}
});
byte[] mac = taskMac.get();
return new DataAndMac(enData, mac);
}
catch (SydApiException e) {
return taskEnc.get();
} catch (SydApiException e) {
throw e;
}
catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
} catch (Exception e) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -223,9 +166,18 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public DataAndMac SYD_SM4_EncryptAndMac_ShortData(int iEncKeyIndex, int iMacKeyIndex, byte[] pcData) {
log.info("SYD_SM4_EncryptAndMac_ShortData {} {}", iEncKeyIndex, iMacKeyIndex);
// if (Env.isLinux()) {
// return SYD_SM4_EncryptAndMac_ShortData_c(iEncKeyIndex, iMacKeyIndex, pcData);
// } else {
// return SYD_SM4_EncryptAndMac_ShortData_java(iEncKeyIndex, iMacKeyIndex, pcData);
// }
return SYD_SM4_EncryptAndMac_ShortData_java(iEncKeyIndex, iMacKeyIndex, pcData);
}
DataAndMac SYD_SM4_EncryptAndMac_ShortData_c(int iEncKeyIndex, int iMacKeyIndex, byte[] pcData) {
log.info("SYD_SM4_EncryptAndMac_ShortData_c {} {}", iEncKeyIndex, iMacKeyIndex);
try {
if ( ! ConnectHandlerManager.isInited() ) {
if (!ConnectHandlerManager.isInited()) {
throw new SydApiException(-1);
}
@ -245,9 +197,9 @@ public class SydApiLongLinkWrap implements SydApi {
mac
);
if ( 0 == i ){
if (0 == i) {
byte[] data = new byte[encDataLen.getValue()];
if( data.length == encData.length ) {
if (data.length == encData.length) {
data = encData;
} else {
System.arraycopy(encData, 0, data, 0, data.length);
@ -257,84 +209,32 @@ public class SydApiLongLinkWrap implements SydApi {
} else {
throw new SydApiException(i);
}
// return SYD_SM4_AllInOne(iEncKeyIndex, iMacKeyIndex, pcData);
// // 线程池忙 使用单线程计算
// if( builder.getLongLinkWorks().threadPoolIsBusy() ) {
// return SYD_SM4_AllInOne(iEncKeyIndex, iMacKeyIndex, pcData);
// }
//
// // 线程池不忙使用并发计算
//
// // 将pcData拆分为两半第一半16字节对齐
// int halfLength = pcData.length / 2;
// int alignedLength = (halfLength + 15) & ~15; // 向上取整到16的倍数
// alignedLength = Math.min(alignedLength, pcData.length); // 不超过原始数据长度
// if (alignedLength < 16) {
// throw new IllegalArgumentException("数据长度不足16字节无法对齐");
// }
//
//
// byte[] firstHalf = Arrays.copyOfRange(pcData, 0, alignedLength);
// byte[] secondHalf = Arrays.copyOfRange(pcData, alignedLength, pcData.length);
//
//
// FutureTask<byte[]> taskEnc1 = builder.getLongLinkWorks().fTask(new Callable<byte[]>() {
// @Override
// public byte[] call() throws Exception {
// return builder.get().SYD_SM4_LongData( iEncKeyIndex, firstHalf, 1, Consts.ECB_ENC);
// }
// });
// FutureTask<byte[]> taskEnc2 = builder.getLongLinkWorks().fTask(new Callable<byte[]>() {
// @Override
// public byte[] call() throws Exception {
// return builder.get().SYD_SM4_LongData( iEncKeyIndex, secondHalf, 3, Consts.ECB_ENC);
// }
// });
//
// byte[] enData1 = taskEnc1.get();
// FutureTask<LongDataReturn<String, String>> taskMac = builder.getLongLinkWorks().fTask(new Callable< LongDataReturn<String, String>>() {
// @Override
// public LongDataReturn<String, String> call() throws Exception {
// return builder.get().SYD_SM4Mac_LongData(iMacKeyIndex, enData1, 1, null);
// }
// });
//
// byte[] enData2 = taskEnc2.get();
// LongDataReturn<String, String> macProc = taskMac.get();
// FutureTask<LongDataReturn<String, String>> taskMac2 = builder.getLongLinkWorks().fTask(new Callable<LongDataReturn<String, String>>() {
// @Override
// public LongDataReturn<String, String> call() throws Exception {
// return builder.get().SYD_SM4Mac_LongData(iMacKeyIndex, enData2, 3, macProc.getProcData());
// }
// });
// LongDataReturn<String, String> mac = taskMac.get();
//
// // 合并密文
// byte[] enData = new byte[enData1.length + enData2.length];
// System.arraycopy(enData1, 0, enData, 0, enData1.length);
// System.arraycopy(enData2, 0, enData, enData1.length, enData2.length);
//
//
// return new DataAndMac(enData, mac.getData());
}
catch (SydApiException e) {
} catch (SydApiException e) {
throw e;
}
catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
} catch (Exception e) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
}
}
@Override
public DataAndMacCheck SYD_SM4_CheckMacAndDecrypt_ShortData(int iEncKeyIndex, int iMacKeyIndex, byte[] pcData, byte[] macs) {
log.info("SYD_SM4_CheckMacAndDecrypt_ShortData {} {}", iEncKeyIndex, iMacKeyIndex);
// if (Env.isLinux()) {
// return SYD_SM4_CheckMacAndDecrypt_ShortData_c(iEncKeyIndex, iMacKeyIndex, pcData, macs);
// } else {
// return SYD_SM4_CheckMacAndDecrypt_ShortData_java(iEncKeyIndex, iMacKeyIndex, pcData, macs);
// }
return SYD_SM4_CheckMacAndDecrypt_ShortData_java(iEncKeyIndex, iMacKeyIndex, pcData, macs);
}
public DataAndMacCheck SYD_SM4_CheckMacAndDecrypt_ShortData_c(int iEncKeyIndex, int iMacKeyIndex, byte[] pcData, byte[] macs) {
log.info("SYD_SM4_CheckMacAndDecrypt_ShortData_c {} {}", iEncKeyIndex, iMacKeyIndex);
try {
if ( ! ConnectHandlerManager.isInited() ) {
if (!ConnectHandlerManager.isInited()) {
throw new SydApiException(-1);
}
@ -355,45 +255,56 @@ public class SydApiLongLinkWrap implements SydApi {
byte[] data = new byte[decryptedDataLen.getValue()];
System.arraycopy(decryptedData, 0, data, 0, data.length);
System.out.println("outlen=" + data.length);
if ( 0 == i ){
if (0 == i) {
return new DataAndMacCheck(data, true);
} if (0x01000010 == i) {
}
if (0x01000010 == i) {
return new DataAndMacCheck(data, false);
} else {
throw new SydApiException(i);
}
}
catch (SydApiException e) {
} catch (SydApiException e) {
throw e;
}
catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
} catch (Exception e) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
}
}
// FutureTask<DataAndMacCheck> task = builder.getLongLinkWorks().fTask(new Callable<DataAndMacCheck>() {
// @Override
// public DataAndMacCheck call() throws Exception {
// return builder.get().SYD_SM4_CheckMacAndDecrypt_ShortData(iEncKeyIndex, iMacKeyIndex, pcData, mac);
// }
// });
// try {
// return task.get();
// } catch (Exception e) {
// throw new SydApiException("并行任务执行失败", 0xC101, e);
// }
public DataAndMacCheck SYD_SM4_CheckMacAndDecrypt_ShortData_java(int iEncKeyIndex, int iMacKeyIndex, byte[] pcData, byte[] macs) {
log.info("SYD_SM4_CheckMacAndDecrypt_ShortData_java {} {}", iEncKeyIndex, iMacKeyIndex);
FutureTask<DataAndMacCheck> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4_CheckMacAndDecrypt_ShortData(iEncKeyIndex, iMacKeyIndex, pcData, macs));
try {
return task.get();
} catch (SydApiException e) {
throw e;
} catch (Exception e) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
}
}
@Override
public List<DataAndMac> SYD_SM4_EncryptAndMac_BatchData(int[] iEncKeyIndex, int[] iMacKeyIndex, List<byte[]> pcData) {
log.info("SYD_SM4_EncryptAndMac_BatchData {} {}", iEncKeyIndex, iMacKeyIndex);
// if (Env.isLinux()) {
// return SYD_SM4_EncryptAndMac_BatchData_c(iEncKeyIndex, iMacKeyIndex, pcData);
// } else {
// return SYD_SM4_EncryptAndMac_BatchData_java(iEncKeyIndex, iMacKeyIndex, pcData);
// }
return SYD_SM4_EncryptAndMac_BatchData_java(iEncKeyIndex, iMacKeyIndex, pcData);
}
if ( ! ConnectHandlerManager.isInited() ) {
public List<DataAndMac> SYD_SM4_EncryptAndMac_BatchData_c(int[] iEncKeyIndex, int[] iMacKeyIndex, List<byte[]> pcData) {
log.info("SYD_SM4_EncryptAndMac_BatchData_c {} {}", iEncKeyIndex, iMacKeyIndex);
if (!ConnectHandlerManager.isInited()) {
throw new SydApiException(-1);
}
@ -411,79 +322,113 @@ public class SydApiLongLinkWrap implements SydApi {
// 3. 准备 MAC 输出缓冲
Pointer[] pcMacArray = new Pointer[pcData.size()];
try {
for (int i = 0; i < pcData.size(); i++) {
byte[] bytes = pcData.get(i);
// 为每个 byte[] 分配本地内存并复制数据
Memory memory = new Memory(bytes.length);
memory.write(0, bytes, 0, bytes.length);
pcDataArray[i] = memory;
iDataLen[i] = bytes.length;
iEncDataLen[i] = BytesUtil.calculatePaddedLength(bytes.length);
pcEncArray[i] = new Memory( iEncDataLen[i] );
pcMacArray[i] = new Memory(16);
}
// 调用加密函数
int result = SydLibrary.INSTANCE.SYD_SM4_Encrypt_Mac_BatchData(
ConnectHandlerManager.getHandler(),
iEncKeyIndex,
iMacKeyIndex,
pcDataArray,
iDataLen,
size,
pcEncArray,
iEncDataLen,
pcMacArray);
if (0 == result) {
// 转换结果为Java风格的对象列表
List<DataAndMac> results = new ArrayList<>();
for (int i = 0; i < size; i++) {
results.add(new DataAndMac(pcEncArray[i].getByteArray(0, iEncDataLen[i]), pcMacArray[i].getByteArray(0,16)));
for (int i = 0; i < pcData.size(); i++) {
byte[] bytes = pcData.get(i);
// 为每个 byte[] 分配本地内存并复制数据
Memory memory = new Memory(bytes.length);
memory.write(0, bytes, 0, bytes.length);
pcDataArray[i] = memory;
iDataLen[i] = bytes.length;
iEncDataLen[i] = BytesUtil.calculatePaddedLength(bytes.length);
pcEncArray[i] = new Memory(iEncDataLen[i]);
pcMacArray[i] = new Memory(16);
}
return results;
} else {
throw new SydApiException(result);
// 调用加密函数
int result = SydLibrary.INSTANCE.SYD_SM4_Encrypt_Mac_BatchData(
ConnectHandlerManager.getHandler(),
iEncKeyIndex,
iMacKeyIndex,
pcDataArray,
iDataLen,
size,
pcEncArray,
iEncDataLen,
pcMacArray);
if (0 == result) {
// 转换结果为Java风格的对象列表
List<DataAndMac> results = new ArrayList<>();
for (int i = 0; i < size; i++) {
results.add(new DataAndMac(pcEncArray[i].getByteArray(0, iEncDataLen[i]), pcMacArray[i].getByteArray(0, 16)));
}
return results;
} else {
throw new SydApiException(result);
}
} finally {
// for ( Pointer d : pcDataArray ) {
// if ( d instanceof Memory ) {
// ((Memory)d).close();
// }
// }
//
// for ( Pointer d : pcEncArray ) {
// if ( d instanceof Memory ) {
// ((Memory)d).close();
// }
// }
//
// for ( Pointer d : pcMacArray ) {
// if ( d instanceof Memory ) {
// ((Memory)d).close();
// }
// }
}
}
catch (SydApiException e) {
} catch (SydApiException e) {
throw e;
}
catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
} catch (Exception e) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
}
// FutureTask<List<DataAndMac>> task = builder.getLongLinkWorks().fTask(new Callable<List<DataAndMac>>() {
// @Override
// public List<DataAndMac> call() throws Exception {
// return builder.get().SYD_SM4_EncryptAndMac_BatchData(iEncKeyIndex, iMacKeyIndex, pcData);
// }
// });
// try {
// return task.get();
// } catch (Exception e) {
// throw new SydApiException("并行任务执行失败", 0xC101, e);
// }
}
public List<DataAndMac> SYD_SM4_EncryptAndMac_BatchData_java(int[] iEncKeyIndex, int[] iMacKeyIndex, List<byte[]> pcData) {
log.info("SYD_SM4_EncryptAndMac_BatchData {} {}", iEncKeyIndex, iMacKeyIndex);
FutureTask<List<DataAndMac>> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4_EncryptAndMac_BatchData(iEncKeyIndex, iMacKeyIndex, pcData));
try {
return task.get();
} catch (Exception e) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
}
}
@Override
public List<DataAndMacCheck> SYD_SM4_CheckMacAndDecrypt_BatchData(int[] iEncKeyIndex, int[] iMacKeyIndex, List<DataAndMac> pcData) {
// if (Env.isLinux()) {
// return SYD_SM4_CheckMacAndDecrypt_BatchData_c(iEncKeyIndex, iMacKeyIndex, pcData);
// } else {
// return SYD_SM4_CheckMacAndDecrypt_BatchData_java(iEncKeyIndex, iMacKeyIndex, pcData);
// }
return SYD_SM4_CheckMacAndDecrypt_BatchData_java(iEncKeyIndex, iMacKeyIndex, pcData);
}
log.info("SYD_SM4_CheckMacAndDecrypt_BatchData {} {}", iEncKeyIndex, iMacKeyIndex);
List<DataAndMacCheck> SYD_SM4_CheckMacAndDecrypt_BatchData_c(int[] iEncKeyIndex, int[] iMacKeyIndex, List<DataAndMac> pcData) {
log.info("SYD_SM4_CheckMacAndDecrypt_BatchData_c {} {}", iEncKeyIndex, iMacKeyIndex);
int size = pcData.size();
log.debug("size {}" , size);
log.debug("SYD_SM4_CheckMacAndDecrypt_BatchData_c size {}", size);
// 1. 准备明文参数
Pointer[] pcDataArray = new Pointer[pcData.size()];
int[] iDataLen = new int[size];
// 2. 准备密文缓冲区
Pointer[] pcEncArray = new Pointer[pcData.size()];
int[] iEncDataLen = new int[size];
@ -493,72 +438,100 @@ public class SydApiLongLinkWrap implements SydApi {
int[] iCheckRet = new int[size];
try {
for (int i = 0; i < pcData.size(); i++) {
DataAndMac dm = pcData.get(i);
for (int i = 0; i < pcData.size(); i++) {
DataAndMac dm = pcData.get(i);
// 为每个 byte[] 分配本地内存并复制数据
Memory memory = new Memory( dm.getData().length );
memory.write(0, dm.getData(), 0, dm.getData().length);
pcEncArray[i] = memory;
iEncDataLen[i] = dm.getData().length;
log.debug("pcEncArray={}" , dm.getData().length);
// 为每个 byte[] 分配本地内存并复制数据
Memory memory = new Memory(dm.getData().length);
memory.write(0, dm.getData(), 0, dm.getData().length);
pcEncArray[i] = memory;
iEncDataLen[i] = dm.getData().length;
log.debug("pcEncArray={}", dm.getData().length);
pcDataArray[i] = new Memory( dm.getData().length );
iDataLen[i] = dm.getData().length;
log.debug("iDataLen= {}" , dm.getData().length);
pcDataArray[i] = new Memory(dm.getData().length);
iDataLen[i] = dm.getData().length;
log.debug("iDataLen= {}", dm.getData().length);
Memory mem_mac = new Memory(16);
mem_mac.write(0, dm.getMac(), 0, 16);
pcMacArray[i] = mem_mac;
Memory mem_mac = new Memory(16);
mem_mac.write(0, dm.getMac(), 0, 16);
pcMacArray[i] = mem_mac;
if ( log.isDebugEnabled() ) {
log.debug("mem_mac=" + Util.bytes2HexString(dm.getMac()));
}
}
// 调用解密函数
int result = SydLibrary.INSTANCE.SYD_SM4_Decrypt_Mac_BatchData(
ConnectHandlerManager.getHandler(),
iEncKeyIndex,
iMacKeyIndex,
pcEncArray,
iEncDataLen,
pcMacArray,
size,
pcDataArray,
iDataLen,
iCheckRet);
if (0 == result) {
// 转换结果为Java风格的对象列表
List<DataAndMacCheck> results = new ArrayList<>();
for (int i = 0; i < size; i++) {
results.add(new DataAndMacCheck(pcDataArray[i].getByteArray(0, iDataLen[i]), iCheckRet[i] == 0));
if (log.isDebugEnabled()) {
log.debug("mem_mac={}" , Util.bytes2HexString(dm.getMac()));
}
}
return results;
} else {
throw new SydApiException(result);
}
// FutureTask<List<DataAndMacCheck>> task = builder.getLongLinkWorks().fTask(new Callable<List<DataAndMacCheck>>() {
// @Override
// public List<DataAndMacCheck> call() throws Exception {
// return builder.get().SYD_SM4_CheckMacAndDecrypt_BatchData(iEncKeyIndex, iMacKeyIndex, pcData);
// 调用解密函数
int result = SydLibrary.INSTANCE.SYD_SM4_Decrypt_Mac_BatchData(
ConnectHandlerManager.getHandler(),
iEncKeyIndex,
iMacKeyIndex,
pcEncArray,
iEncDataLen,
pcMacArray,
size,
pcDataArray,
iDataLen,
iCheckRet);
if (0 == result) {
// 转换结果为 Java 风格的对象列表
List<DataAndMacCheck> results = new ArrayList<>();
for (int i = 0; i < size; i++) {
results.add(new DataAndMacCheck(pcDataArray[i].getByteArray(0, iDataLen[i]), iCheckRet[i] == 0));
}
return results;
} else {
throw new SydApiException(result);
}
} finally {
// for ( Pointer d : pcDataArray ) {
// if ( d instanceof Memory ) {
// ((Memory)d).close();
// }
// }
// });
// try {
// return task.get();
// } catch (Exception e) {
// throw new SydApiException("并行任务执行失败", 0xC101, e);
// }
//
// for ( Pointer d : pcEncArray ) {
// if ( d instanceof Memory ) {
// ((Memory)d).close();
// }
// }
//
// for ( Pointer d : pcMacArray ) {
// if ( d instanceof Memory ) {
// ((Memory)d).close();
// }
// }
}
}
List<DataAndMacCheck> SYD_SM4_CheckMacAndDecrypt_BatchData_java(int[] iEncKeyIndex, int[] iMacKeyIndex, List<DataAndMac> pcData) {
log.info("SYD_SM4_CheckMacAndDecrypt_BatchData_java {} {}", iEncKeyIndex, iMacKeyIndex);
int size = pcData.size();
log.debug("size {}", size);
FutureTask<List<DataAndMacCheck>> task = builder.getLongLinkWorks().fTask(() -> builder.get().SYD_SM4_CheckMacAndDecrypt_BatchData(iEncKeyIndex, iMacKeyIndex, pcData));
try {
return task.get();
} catch (Exception e) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
}
}
@Override
public ISM4 initSM4(int iKeyIndex, int ende) {
return new SydSM4(this, iKeyIndex, ende);
@ -577,15 +550,15 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public List<byte[]> SYD_SM4_BatchData(int[] iKeyIndex, List<byte[]> pcData, int iFlag) {
if ( null == iKeyIndex || null == pcData ) {
if (null == iKeyIndex || null == pcData) {
throw new IllegalArgumentException("批量输入数据为 null");
}
if ( iKeyIndex.length != pcData.size() ) {
throw new IllegalArgumentException("批量输入数据密钥和数据数量不等");
if (iKeyIndex.length != pcData.size()) {
throw new SydApiException("批量输入数据密钥和数据数量不等", 0x01000001);
}
if ( 0 == iKeyIndex.length ) {
if (0 == iKeyIndex.length) {
return new ArrayList<>();
}
// 将数据进行分组防止超长
@ -629,12 +602,9 @@ public class SydApiLongLinkWrap implements SydApi {
for (int i = 0; i < dataGroups.size(); i++) {
int finalI = i;
FutureTask<List<byte[]>> task = builder.getLongLinkWorks().fTask(new Callable<List<byte[]>>() {
@Override
public List<byte[]> call() throws Exception {
SydApi api = builder.get();
return api.SYD_SM4_BatchData(toIntArray(keyGroups.get(finalI)), dataGroups.get(finalI), iFlag);
}
FutureTask<List<byte[]>> task = builder.getLongLinkWorks().fTask(() -> {
SydApi api = builder.get();
return api.SYD_SM4_BatchData(toIntArray(keyGroups.get(finalI)), dataGroups.get(finalI), iFlag);
});
tasks.add(task);
}
@ -646,30 +616,28 @@ public class SydApiLongLinkWrap implements SydApi {
}
return ret;
}
catch (ExecutionException e) {
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof SydApiException) {
throw (SydApiException) cause;
}
throw new SydApiException("并行任务执行失败", 0xC101);
}
catch (Exception e) {
} catch (Exception e) {
throw new SydApiException("并行任务执行失败", 0xC101, e);
}
}
@Override
public List<byte[]> SYD_SM4Mac_BatchData(int[] iKeyIndex, List<byte[]> pcData) {
if ( null == iKeyIndex || null == pcData ) {
if (null == iKeyIndex || null == pcData) {
throw new IllegalArgumentException("批量输入数据为 null");
}
if ( iKeyIndex.length != pcData.size() ) {
throw new IllegalArgumentException("批量输入数据密钥和数据数量不等");
if (iKeyIndex.length != pcData.size()) {
throw new SydApiException("批量输入数据密钥和数据数量不等", 0x01000001);
}
if ( 0 == iKeyIndex.length ) {
if (0 == iKeyIndex.length) {
return new ArrayList<>();
}
// 将数据进行分组防止超长
@ -711,12 +679,9 @@ public class SydApiLongLinkWrap implements SydApi {
for (int i = 0; i < dataGroups.size(); i++) {
int finalI = i;
FutureTask<List<byte[]>> task = builder.getLongLinkWorks().fTask(new Callable<List<byte[]>>() {
@Override
public List<byte[]> call() throws Exception {
SydApi api = builder.get();
return api.SYD_SM4Mac_BatchData(toIntArray(keyGroups.get(finalI)), dataGroups.get(finalI));
}
FutureTask<List<byte[]>> task = builder.getLongLinkWorks().fTask(() -> {
SydApi api = builder.get();
return api.SYD_SM4Mac_BatchData(toIntArray(keyGroups.get(finalI)), dataGroups.get(finalI));
});
tasks.add(task);
}
@ -730,7 +695,7 @@ public class SydApiLongLinkWrap implements SydApi {
return ret;
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);
@ -739,15 +704,15 @@ public class SydApiLongLinkWrap implements SydApi {
@Override
public boolean[] SYD_SM4Mac_BatchData(int[] iKeyIndex, List<byte[]> pcData, List<byte[]> pcMac) {
if ( null == iKeyIndex || null == pcData ) {
if (null == iKeyIndex || null == pcData) {
throw new IllegalArgumentException("批量输入数据为 null");
}
if ( iKeyIndex.length != pcData.size() ) {
throw new IllegalArgumentException("批量输入数据密钥和数据数量不等");
if (iKeyIndex.length != pcData.size()) {
throw new SydApiException("批量输入数据密钥和数据数量不等", 0x01000001);
}
if ( 0 == iKeyIndex.length ) {
if (0 == iKeyIndex.length) {
return new boolean[0];
}
@ -797,16 +762,13 @@ public class SydApiLongLinkWrap implements SydApi {
for (int i = 0; i < dataGroups.size(); i++) {
int finalI = i;
FutureTask<boolean[]> task = builder.getLongLinkWorks().fTask(new Callable<boolean[]>() {
@Override
public boolean[] call() throws Exception {
SydApi api = builder.get();
return api.SYD_SM4Mac_BatchData(
toIntArray(keyGroups.get(finalI)),
dataGroups.get(finalI),
macGroups.get(finalI)
);
}
FutureTask<boolean[]> task = builder.getLongLinkWorks().fTask(() -> {
SydApi api = builder.get();
return api.SYD_SM4Mac_BatchData(
toIntArray(keyGroups.get(finalI)),
dataGroups.get(finalI),
macGroups.get(finalI)
);
});
tasks.add(task);
}
@ -822,7 +784,7 @@ public class SydApiLongLinkWrap implements SydApi {
return toBoolArray(ret);
} catch (Exception e) {
if ( e.getCause() instanceof SydApiException) {
if (e.getCause() instanceof SydApiException) {
throw (SydApiException) e.getCause();
}
throw new SydApiException("并行任务执行失败", 0xC101, e);

View File

@ -20,7 +20,7 @@ public class SydSM3 implements ISM3 {
pcData = new byte[0];
}
if (pcData.length > 4064) {
throw new IllegalArgumentException();
throw new SydApiException(0x01000001);
}
if (null == this.pcProcData) {
LongDataReturn<byte[], byte[]> stringStringLongDataReturn = api.SYD_SM3_Hash_LongData(pcData, 1, null);

View File

@ -33,7 +33,7 @@ public class SydSM4 implements ISM4 {
throw new SydApiException(0x8007);
}
if (plength > 4064) {
throw new SydApiException(0x8006);
throw new SydApiException(0x01000001);
}
if (iFlag == 1) {
if (0 == queue.getLength()) {

View File

@ -32,18 +32,22 @@ public class SydSM4Mac implements ISM4Mac {
throw new SydApiException(0x8007);
}
if (length > 4064) {
throw new SydApiException(0x8006);
throw new SydApiException(0x01000001);
}
if (0 == queue.getLength()) {
if (length < 16) {
queue.push(pcData);
// if (length < 16) {
// queue.push(pcData);
// }
// if (length % 16 != 0) {
// }
queue.push(pcData);
pcdataResult = queue.pop(16, 0);
if ( null == pcdataResult || pcdataResult.length == 0 ) {
return;
}
if (length % 16 != 0) {
queue.push(pcData);
byte[] pop = queue.pop(16, 0);
pcdataResult =pop;
}
if (null == this.pcMac || "".equals(this.pcMac)) {
if (null == this.pcMac || this.pcMac.length == 0) {
LongDataReturn<byte[], byte[]> stringStringLongDataReturn = api.SYD_SM4Mac_LongData(iKeyIndex, pcdataResult, iPkgNum, pcProcData);
pcProcData = stringStringLongDataReturn.getProcData();
iPkgNum = 2;
@ -59,7 +63,7 @@ public class SydSM4Mac implements ISM4Mac {
queue.push(pcData);
byte[] pop = queue.pop(16, 0);
if (null == this.pcMac || "".equals(this.pcMac)) {
if (null == this.pcMac || this.pcMac.length == 0 ) {
LongDataReturn<byte[], byte[]> stringStringLongDataReturn = api.SYD_SM4Mac_LongData(iKeyIndex, pop, iPkgNum, pcProcData);
pcProcData = stringStringLongDataReturn.getProcData();
iPkgNum = 2;
@ -75,6 +79,7 @@ public class SydSM4Mac implements ISM4Mac {
@Override
public boolean checkDigest(byte[] mac) {
this.pcMac = this.digest();
return mac != null && Arrays.equals(this.pcMac, mac);
}
@ -93,7 +98,8 @@ public class SydSM4Mac implements ISM4Mac {
byte[] pop = queue.pop();
LongDataReturn<byte[], byte[]> stringStringLongDataReturn = api.SYD_SM4Mac_LongData(iKeyIndex, pop, iPkgNum, pcProcData);
return stringStringLongDataReturn.getData();
this.pcMac = stringStringLongDataReturn.getData();
return this.pcMac;
}

View File

@ -4,15 +4,15 @@ import com.sunyard.SydApiException;
import com.sunyard.sge.database.SydApi;
import com.sunyard.sge.database.SydApi4Database;
import com.sunyard.sge.database.SydApiBaseFunction;
import com.sunyard.sge.log.LogFactory;
import com.sunyard.sge.pool.ObjectInPool;
import com.sunyard.sge.pool.PoolConfig;
import com.sunyard.sge.pool.ThreadBasedConnectPool;
import org.apache.logging.log4j.Logger;
import org.slf4j.LoggerFactory;
import racal.sunyard.main.SydApi4j;
public class SydApiPool extends ThreadBasedConnectPool<SydApi> {
private HsmLinkInfo[] linkInfos;
private final HsmLinkInfo[] linkInfos;
public SydApiPool(HsmLinkInfo[] linkInfos) {
super();
this.linkInfos = linkInfos;
@ -24,7 +24,7 @@ public class SydApiPool extends ThreadBasedConnectPool<SydApi> {
// 继承 初始化
protected SydApi initialValue() {
Logger log = LogFactory.getLogger();
org.slf4j.Logger log = LoggerFactory.getLogger(ThreadBasedConnectPool.class);
// 所有加密机一次性链接
SydApi4j[] apis = new SydApi4j[linkInfos.length];
@ -83,7 +83,7 @@ public class SydApiPool extends ThreadBasedConnectPool<SydApi> {
hsms[i] = (SydApi4j) new SydApi4j().connect(info.getPcIp(), info.getiPort(), null, info.getiConnectTimeOut(), info.getiDealTimeOut());
canUse = true;
} catch (Exception e) {
// free
}
}
}

View File

@ -1,122 +1,122 @@
package com.sunyard.sge.log;
import com.sunyard.sge.database.Consts;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.appender.rolling.SizeBasedTriggeringPolicy;
import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.Logger;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 金交所定制日志
*/
public class LogFactory {
// 金交所定制日志
public static final String logName = "sge-hsm-sydapi-log";
// 日志级别
public static int iLogLevel = Consts.LogLevelOFF;
// Levels
private static final Level[] levels = new Level[]{ Level.OFF, Level.ERROR, Level.INFO, Level.DEBUG };
// 日志目录
private static String pcLogPath = "./sydapi-logs/";
// // 日期格式
// private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
private LogFactory() {
}
public static void start() {
// 上下文
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
// 创建一个展示的样式
Layout layout = PatternLayout.createLayout(
"[%level{DEBUG=3, INFO=2, ERROR=1, OFF=0}: %d{ISO8601} <%thread>] %message%n%throwable",
null,
config, null, null, true, false, null, null);
TriggeringPolicy tp = SizeBasedTriggeringPolicy.createPolicy("10MB");
// Appender appender = RollingFileAppender.createAppender(String.format("logs/test/syncshows-job-%s.log", jobID),
// "/logs/test/" + jobID + "/syncshows-job-" + jobID + ".log.gz",
// "true", jobID, null, null, null, tp, null, layout, null,
// null, null, null, config);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// 日志打印方式输出为文件   
Appender appender = FileAppender.createAppender(
String.format( pcLogPath + "sydapi_"+ format.format(new Date()) + ".log"),
"true", "false",
logName, null, "true", "true", null, layout, null, null, null, config);
appender.start();
config.addAppender(appender);
AppenderRef ref = AppenderRef.createAppenderRef( logName, levels[ iLogLevel ], null);
AppenderRef[] refs = new AppenderRef[]{ref};
LoggerConfig loggerConfig = LoggerConfig.createLogger("false", levels[ iLogLevel ], logName,
"true", refs, null, config, null);
loggerConfig.addAppender(appender, levels[ iLogLevel ], null);
config.addLogger( logName, loggerConfig);
ctx.updateLoggers();
}
public static void stop() {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
config.getAppender( logName ).stop();
config.getLoggerConfig(logName).removeAppender( logName);
config.removeLogger(logName);
ctx.updateLoggers();
}
public static int getiLogLevel() {
return iLogLevel;
}
/**
* 创建 Logger
* @return Logger
*/
public static Logger createLogger(String pcLogPath, int iLogLevel) {
if( null == pcLogPath || pcLogPath.trim().equals("") ) {
pcLogPath = "./";
}
if( ! pcLogPath.endsWith("/") ) {
pcLogPath = pcLogPath + "/";
}
LogFactory.pcLogPath = pcLogPath;
LogFactory.iLogLevel = iLogLevel;
start();
return LogManager.getLogger(logName);
}
/**
* 获取 Logger
* @return Logger
*/
public static Logger getLogger() {
return LogManager.getLogger(logName);
}
}
//package com.sunyard.sge.log;
//
//import com.sunyard.sge.database.Consts;
//import org.apache.logging.log4j.Level;
//import org.apache.logging.log4j.LogManager;
//import org.apache.logging.log4j.core.Appender;
//import org.apache.logging.log4j.core.Layout;
//import org.apache.logging.log4j.core.LoggerContext;
//import org.apache.logging.log4j.core.appender.FileAppender;
//import org.apache.logging.log4j.core.appender.rolling.SizeBasedTriggeringPolicy;
//import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
//import org.apache.logging.log4j.core.config.AppenderRef;
//import org.apache.logging.log4j.core.config.Configuration;
//import org.apache.logging.log4j.core.config.LoggerConfig;
//import org.apache.logging.log4j.core.layout.PatternLayout;
//import org.apache.logging.log4j.Logger;
//
//import java.text.SimpleDateFormat;
//import java.util.Date;
//
///**
// * 金交所定制日志
// */
//public class LogFactory {
//
// // 金交所定制日志
// public static final String logName = "sge-hsm-sydapi-log";
//
// // 日志级别
// public static int iLogLevel = Consts.LogLevelOFF;
//
// // Levels
// private static final Level[] levels = new Level[]{ Level.OFF, Level.ERROR, Level.INFO, Level.DEBUG };
//
// // 日志目录
// private static String pcLogPath = "./sydapi-logs/";
//
//// // 日期格式
//// private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//
// private LogFactory() {
// }
//
// public static void start() {
// // 上下文
// final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
// final Configuration config = ctx.getConfiguration();
//
// // 创建一个展示的样式
// Layout layout = PatternLayout.createLayout(
// "[%level{DEBUG=3, INFO=2, ERROR=1, OFF=0}: %d{ISO8601} <%thread>] %message%n%throwable",
// null,
// config, null, null, true, false, null, null);
//
//
// TriggeringPolicy tp = SizeBasedTriggeringPolicy.createPolicy("10MB");
//
//// Appender appender = RollingFileAppender.createAppender(String.format("logs/test/syncshows-job-%s.log", jobID),
//// "/logs/test/" + jobID + "/syncshows-job-" + jobID + ".log.gz",
//// "true", jobID, null, null, null, tp, null, layout, null,
//// null, null, null, config);
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
// // 日志打印方式输出为文件   
// Appender appender = FileAppender.createAppender(
// String.format( pcLogPath + "sydapi_"+ format.format(new Date()) + ".log"),
// "true", "false",
// logName, null, "true", "true", null, layout, null, null, null, config);
//
// appender.start();
// config.addAppender(appender);
// AppenderRef ref = AppenderRef.createAppenderRef( logName, levels[ iLogLevel ], null);
// AppenderRef[] refs = new AppenderRef[]{ref};
// LoggerConfig loggerConfig = LoggerConfig.createLogger("false", levels[ iLogLevel ], logName,
// "true", refs, null, config, null);
// loggerConfig.addAppender(appender, levels[ iLogLevel ], null);
// config.addLogger( logName, loggerConfig);
// ctx.updateLoggers();
// }
//
//
// public static void stop() {
// final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
// final Configuration config = ctx.getConfiguration();
// config.getAppender( logName ).stop();
// config.getLoggerConfig(logName).removeAppender( logName);
// config.removeLogger(logName);
// ctx.updateLoggers();
// }
//
// public static int getiLogLevel() {
// return iLogLevel;
// }
//
// /**
// * 创建 Logger
// * @return Logger
// */
// public static Logger createLogger(String pcLogPath, int iLogLevel) {
// if( null == pcLogPath || pcLogPath.trim().equals("") ) {
// pcLogPath = "./";
// }
// if( ! pcLogPath.endsWith("/") ) {
// pcLogPath = pcLogPath + "/";
// }
//
// LogFactory.pcLogPath = pcLogPath;
// LogFactory.iLogLevel = iLogLevel;
// start();
// return LogManager.getLogger(logName);
//
// }
//
// /**
// * 获取 Logger
// * @return Logger
// */
// public static Logger getLogger() {
// return LogManager.getLogger(logName);
// }
//
//
//}

View File

@ -0,0 +1,19 @@
package com.sunyard.sge.log;
import com.sunyard.log.ILogFactory;
import com.sunyard.log.ILogger;
import racal.sunyard.main.SydApi4j;
public class LogbackFactory implements ILogFactory {
static {
SydApi4j.setLogFactory(new LogbackFactory());
}
@Override
public ILogger getLogger(Class cls) {
return new LogbackLogger(cls);
}
}

View File

@ -0,0 +1,44 @@
package com.sunyard.sge.log;
import com.sunyard.log.ILogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogbackLogger implements ILogger {
private Class aClass;
public LogbackLogger(Class cls) {
this.aClass = cls;
}
@Override
public int getCurrentLogLevel() {
return -1;
}
@Override
public void error(String msg, Object... params) {
Logger logger = LoggerFactory.getLogger(aClass);
logger.error(msg, params);
}
@Override
public void info(String msg, Object... params) {
Logger logger = LoggerFactory.getLogger(aClass);
logger.info(msg, params);
}
@Override
public void debug(String msg, Object... params) {
Logger logger = LoggerFactory.getLogger(aClass);
logger.debug(msg, params);
}
@Override
public boolean isDebugEnabled() {
Logger logger = LoggerFactory.getLogger(aClass);
return logger.isDebugEnabled();
}
}

View File

@ -8,7 +8,7 @@ import com.sun.jna.ptr.PointerByReference;
*/
public class ConnectHandlerManager {
private static PointerByReference phHandle = new PointerByReference();
private static Pointer[] phHandle = new Pointer[1];
private static Boolean inited = false;
/**
@ -45,6 +45,6 @@ public class ConnectHandlerManager {
}
public static Pointer getHandler(){
return phHandle.getValue();
return phHandle[0];
}
}

View File

@ -8,7 +8,7 @@ import com.sun.jna.ptr.PointerByReference;
public interface SydLibrary extends Library {
// 加载动态库
SydLibrary INSTANCE = Native.load("sunyard", SydLibrary.class);
SydLibrary INSTANCE = Native.loadLibrary("sunyard", SydLibrary.class);
// 1.1 设置日志配置
int SYD_SetLogConfig(String pcLogPath, int iLogPathLen, int iLogLevel);
@ -21,7 +21,7 @@ public interface SydLibrary extends Library {
int iConnectTimeOut,
int iDealTimeOut,
int iThreadCount,
PointerByReference phHandle);
Pointer[] phHandle);
// 1.3 断开与设备的连接
int SYD_DisConnect_Ex(Pointer phHandle);

View File

@ -1,10 +1,8 @@
package com.sunyard.sge.pool;
import com.sunyard.sge.log.LogFactory;
import org.apache.logging.log4j.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Iterator;
@ -24,9 +22,11 @@ public class ThreadBasedConnectPool<T> {
// 配置
private PoolConfig config;
private Logger log = LoggerFactory.getLogger(ThreadBasedConnectPool.class);
public ThreadBasedConnectPool(PoolConfig config) {
this.config = config;
Logger log = LogFactory.getLogger();
threadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
@ -49,6 +49,7 @@ public class ThreadBasedConnectPool<T> {
try {
free(oip.getObject());
} catch (Exception e) {
// free
}
continue;
}
@ -67,6 +68,7 @@ public class ThreadBasedConnectPool<T> {
try {
free(oip.getObject());
} catch (Exception e) {
// free
}
continue;
}
@ -76,7 +78,6 @@ public class ThreadBasedConnectPool<T> {
checkPass = check(entry.getValue().getObjectForCheck());
} catch (Exception e) {
checkPass = false;
} finally {
}
if (!checkPass) {
@ -87,6 +88,7 @@ public class ThreadBasedConnectPool<T> {
try {
free(oip.getObject());
} catch (Exception e) {
// free
}
continue;
}

View File

@ -0,0 +1,169 @@
package com.sunyard.sge.database;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class EncryptAndMac {
public static void conformance_testcase1_SYD_SM4_EncryptAndMac_ShortData(SydApiLongLinkWrap api){
int keyEnc = 0;
int keyMac = 0;
byte[] data1 = new byte[1024];
System.out.println("step1");
DataAndMac en_data1 = api.SYD_SM4_EncryptAndMac_ShortData_c(keyEnc, keyMac, data1);
System.out.println("step2");
DataAndMacCheck de_data1 = api.SYD_SM4_CheckMacAndDecrypt_ShortData_java(keyEnc, keyMac, en_data1.getData(), en_data1.getMac());
System.out.println("step3 ");
if ( de_data1.getMacCheck() ) {
System.out.println("conformance_testcase1 测试通过");
}
}
public static void conformance_testcase2_SYD_SM4_EncryptAndMac_ShortData(SydApiLongLinkWrap api){
int keyEnc = 0;
int keyMac = 0;
byte[] data1 = new byte[1024];
System.out.println("step1");
DataAndMac en_data1 = api.SYD_SM4_EncryptAndMac_ShortData_java(keyEnc, keyMac, data1);
System.out.println("step2");
DataAndMacCheck de_data1 = api.SYD_SM4_CheckMacAndDecrypt_ShortData_c(keyEnc, keyMac, en_data1.getData(), en_data1.getMac());
System.out.println("step3 " + de_data1.getMacCheck());
if ( de_data1.getMacCheck() ) {
System.out.println("conformance_testcase2 测试通过");
}
}
public static void conformance_testcase1_sm4BatchMacFunc(SydApiLongLinkWrap api){
List<byte[]> data = new ArrayList<>();
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
int[] keyEnc = new int[]{0, 0, 0, 0, 0, 0, 0};
int[] keyMac = new int[]{0, 0, 0, 0, 0, 0, 0};
List<DataAndMac> en_data = api.SYD_SM4_EncryptAndMac_BatchData_c(keyEnc, keyMac, data);
List<DataAndMacCheck> de_data = api.SYD_SM4_CheckMacAndDecrypt_BatchData_java(keyEnc, keyMac, en_data);
boolean flag = true;
for (int i = 0; i < de_data.size(); i++) {
flag = flag & de_data.get(i).getMacCheck();
}
if (flag) {
System.out.println("批量数据加密计算MAC校验MAC解密测试成功");
} else {
System.out.println("批量数据加密计算MAC校验MAC解密测试失败");
}
}
public static void conformance_testcase2_sm4BatchMacFunc(SydApiLongLinkWrap api){
List<byte[]> data = new ArrayList<>();
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
int[] keyEnc = new int[]{0, 0, 0, 0, 0, 0, 0};
int[] keyMac = new int[]{0, 0, 0, 0, 0, 0, 0};
List<DataAndMac> en_data = api.SYD_SM4_EncryptAndMac_BatchData_java(keyEnc, keyMac, data);
List<DataAndMacCheck> de_data = api.SYD_SM4_CheckMacAndDecrypt_BatchData_c(keyEnc, keyMac, en_data);
boolean flag = true;
for (int i = 0; i < de_data.size(); i++) {
flag = flag & de_data.get(i).getMacCheck();
}
if (flag) {
System.out.println("批量数据加密计算MAC校验MAC解密测试成功");
} else {
System.out.println("批量数据加密计算MAC校验MAC解密测试失败");
}
}
public static void main(String[] args) {
// 路径要以 / \\ 结尾表示目录
String[] pcipList = {"172.1.41.216", "172.1.41.129"};
int[] iportList = {8880, 8889};
SydApi api = new SydApi4Database();
try {
api.SYD_Short_Connect_Ex(pcipList, iportList, 1000, 1000);
// 密钥索引
int keyEncIdx = 0;
int keyMacIdx = 0;
// 测试数据
byte[] data = new byte[16];
// 短数据
DataAndMac ret = api.SYD_SM4_EncryptAndMac_ShortData(keyEncIdx, keyMacIdx, data);
DataAndMacCheck deData = api.SYD_SM4_CheckMacAndDecrypt_ShortData(keyEncIdx, keyMacIdx, ret.getData(), ret.getMac());
if (Arrays.equals( data, deData.getData() ) ) {
System.out.println("短数据加密并计算 MAC - 测试通过");
} else {
System.out.println("短数据加密并计算 MAC - 测试失败");
}
// 批量短数据
List<byte[]>data2 = Arrays.asList(
new byte[8],
new byte[500],
new byte[512]
);
List<DataAndMac> ret2 = api.SYD_SM4_EncryptAndMac_BatchData(
new int[] {keyEncIdx, keyEncIdx, keyEncIdx},
new int[] {keyMacIdx, keyMacIdx, keyMacIdx},
data2
);
List<DataAndMacCheck>deDatas = api.SYD_SM4_CheckMacAndDecrypt_BatchData(
new int[] {keyEncIdx, keyEncIdx, keyEncIdx},
new int[] {keyMacIdx, keyMacIdx, keyMacIdx},
ret2
);
for (int i=0; i< deDatas.size(); i++){
byte[] d1 = data2.get(i);
DataAndMacCheck d2 = deDatas.get(i);
if (! d2.getMacCheck() ) {
System.out.println("批量短数据加密并计算 MAC 验证失败 - 测试失败");
return;
}
if (! Arrays.equals( d1, d2.getData() ) ) {
System.out.println("批量短数据加密并计算 MAC - 测试失败");
return;
}
}
System.out.println("批量短数据加密并计算 MAC - 测试通过");
} finally {
if (null != api) {
api.SYD_Disconnect_Ex();
}
}
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,83 +0,0 @@
package test;
import com.sunyard.sge.database.*;
import java.util.Arrays;
import java.util.List;
public class EncryptAndMac {
public static void main(String[] args) {
// 路径要以 / \\ 结尾表示目录
String[] pcipList = {"172.1.41.216", "172.1.41.129"};
int[] iportList = {8880, 8889};
SydApi api = new SydApi4Database();
try {
api.SYD_Short_Connect_Ex(pcipList, iportList, 1000, 1000);
// 密钥索引
int keyEncIdx = 0;
int keyMacIdx = 0;
// 测试数据
byte[] data = new byte[16];
// 短数据
DataAndMac ret = api.SYD_SM4_EncryptAndMac_ShortData(keyEncIdx, keyMacIdx, data);
DataAndMacCheck deData = api.SYD_SM4_CheckMacAndDecrypt_ShortData(keyEncIdx, keyMacIdx, ret.getData(), ret.getMac());
if (Arrays.equals( data, deData.getData() ) ) {
System.out.println("短数据加密并计算 MAC - 测试通过");
} else {
System.out.println("短数据加密并计算 MAC - 测试失败");
}
// 批量短数据
List<byte[]>data2 = Arrays.asList(
new byte[8],
new byte[500],
new byte[512]
);
List<DataAndMac> ret2 = api.SYD_SM4_EncryptAndMac_BatchData(
new int[] {keyEncIdx, keyEncIdx, keyEncIdx},
new int[] {keyMacIdx, keyMacIdx, keyMacIdx},
data2
);
List<DataAndMacCheck>deDatas = api.SYD_SM4_CheckMacAndDecrypt_BatchData(
new int[] {keyEncIdx, keyEncIdx, keyEncIdx},
new int[] {keyMacIdx, keyMacIdx, keyMacIdx},
ret2
);
for (int i=0; i< deDatas.size(); i++){
byte[] d1 = data2.get(i);
DataAndMacCheck d2 = deDatas.get(i);
if (! d2.getMacCheck() ) {
System.out.println("批量短数据加密并计算 MAC 验证失败 - 测试失败");
return;
}
if (! Arrays.equals( d1, d2.getData() ) ) {
System.out.println("批量短数据加密并计算 MAC - 测试失败");
return;
}
}
System.out.println("批量短数据加密并计算 MAC - 测试通过");
} finally {
if (null != api) {
api.SYD_Disconnect_Ex();
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -127,7 +127,7 @@ public class LongDataTest {
public static boolean case1(SydApi api) {
int max = 1000;
int size = 4065;
int size = 4064;
ISM4 en = api.initSM4(0, 1);
ISM4 de = api.initSM4(0, 0);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,829 @@
package test;
import com.sunyard.sge.database.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestMAC {
private static final String[] ipListElec = new String[]{"127.0.0.1", "172.1.41.129"};
private static final String[] ipListLight = new String[]{"192.168.110.240", "192.168.100.45"};
private static final String[] ipList = ipListLight;
private static final String[] ipListErr = new String[]{"172.2.41.216", "172.2.41.129"};
public static final int ECB_DEC = 0;
public static final int ECB_ENC = 1;
public static void setLog() {
System.setProperty("com.sunyard.sydapi4j.debug", "false");
}
private static void startPerformanceFile() {
try (FileWriter fw = new FileWriter(PERF_RESULT_FILE, true);
BufferedWriter bw = new BufferedWriter(fw)) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = sdf.format(now);
bw.write("==================== Performance Test Start: " + timeStr + " ====================");
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stopPerformanceFile() {
try (FileWriter fw = new FileWriter(PERF_RESULT_FILE, true);
BufferedWriter bw = new BufferedWriter(fw)) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = sdf.format(now);
bw.write("==================== Performance Test End: " + timeStr + " ====================");
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeToPerformanceFile(String interfaceName, int dataLen, int machineCount, int threadNum, int totalRequests, double tps, double avgLatency) {
try (FileWriter fw = new FileWriter(PERF_RESULT_FILE, true);
BufferedWriter bw = new BufferedWriter(fw)) {
String line = String.format("%s\t%d\t%d\t%d\t%d\t%.2f\t%.2f",
interfaceName, dataLen, machineCount, threadNum, totalRequests, tps, avgLatency);
bw.write(line);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeToPerformanceFile(String interfaceName, int dataLen, int machineCount, int threadNum, int totalRequests, String tps, double avgLatency) {
try (FileWriter fw = new FileWriter(PERF_RESULT_FILE, true);
BufferedWriter bw = new BufferedWriter(fw)) {
String line = String.format("%s\t%d\t%d\t%d\t%d\t%s\t%.2f",
interfaceName, dataLen, machineCount, threadNum, totalRequests, tps, avgLatency);
bw.write(line);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeToPerformanceFile2(String interfaceName, String dataLen, int machineCount, int threadNum, double totalRequests) {
try (FileWriter fw = new FileWriter(PERF_RESULT_FILE, true);
BufferedWriter bw = new BufferedWriter(fw)) {
String line = String.format("%s\t%s\t%d\t%d\t%.2f",
interfaceName, dataLen, machineCount, threadNum, totalRequests);
bw.write(line);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void menu1(Config config, Choise choise, TestMAC test) throws Exception {
FuncTest funcTest = new FuncTest(config);
while (true) {
System.out.println("请选择测试项:");
// System.out.println("1. 功能单项测试");
// System.out.println("2. 功能全量测试");
System.out.println("1. 性能单项测试");
System.out.println("2. 性能全量测试");
System.out.println("-1. 退出");
switch (choise.getAsInt()) {
// case 1:
// SydApi.SYD_SetLogConfig("./logs", 3);
// funcTest.funcMenu(config, choise, funcTest);
// break;
// case 2:
// funcTest.funcAll();
// break;
case 1:
SydApi.SYD_SetLogConfig("./logs", 0);
perfMenu(config, choise, test);
break;
case 2:
SydApi.SYD_SetLogConfig("./logs", 0);
startPerformanceFile();
test.perfAll();
stopPerformanceFile();
break;
default:
System.exit(0);
}
}
}
public void sm4ShortEndes() throws InterruptedException {
System.out.println("-------- SM4短数据加解密性能测试开始 --------");
sm4ShortEnde(1, config.getTotal(), 1024);
sm4ShortEnde(40, config.getTotal(), 1024);
System.out.println("-------- SM4短数据加解密性能测试结束 --------\n");
}
private static final String PERF_RESULT_FILE = "performance_results.txt";
public void sm4ShortEnde(int numberOfThreads, int totalRequest, int plainLen) throws InterruptedException {
byte[] data = new byte[plainLen];
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
ThreadLocal<SydApi> Api = new ThreadLocal<SydApi>() {
@Override
protected SydApi initialValue() {
return builder.build();
}
};
ExecutorService poolEnc = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolEnc.submit(() -> {
SydApi api = Api.get();
api.SYD_SM4_ShortData(0, data, ECB_ENC);
});
}
poolEnc.shutdown();
poolEnc.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
long end = System.currentTimeMillis();
long duration = end - start;
double tps = totalRequest * 1000.0 / duration;
double throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("加密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatencyEnc = numberOfThreads * duration * 1.0 / totalRequest;
System.out.println("平均延时(加密): " + String.format("%.2f", avgLatencyEnc) + " ms");
writeToPerformanceFile("SM4短数据加密", 1024, 1, numberOfThreads, totalRequest, tps, avgLatencyEnc);
SydApi apiTest = Api.get();
byte[] res = apiTest.SYD_SM4_ShortData(0, data, ECB_ENC);
ExecutorService poolDec = Executors.newFixedThreadPool(numberOfThreads);
start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolDec.submit(() -> {
SydApi api = Api.get();
byte[] plain = api.SYD_SM4_ShortData(0, res, ECB_DEC);
});
}
poolDec.shutdown();
poolDec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
end = System.currentTimeMillis();
duration = end - start;
tps = totalRequest * 1000.0 / duration;
throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("解密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatencyDec = numberOfThreads * duration * 1.0 / totalRequest;
System.out.println("平均延时(解密): " + String.format("%.2f", avgLatencyDec) + " ms");
writeToPerformanceFile("SM4短数据解密", 1024, 1, numberOfThreads, totalRequest, tps, avgLatencyDec);
}
public void sm4BatchEndes() throws InterruptedException {
System.out.println("-------- SM4批量数据加解密性能测试开始 --------");
sm4BatchEnde(1, config.getTotal(), 1024);
sm4BatchEnde(40, config.getTotal(), 1024);
System.out.println("-------- SM4批量数据加解密性能测试结束 --------\n");
}
public void sm4BatchEnde(int numberOfThreads, int totalRequest, int plainLen) throws InterruptedException {
int[] keyIdx = new int[]{0, 0, 0, 0};
List<byte[]> data = new ArrayList<>();
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
ThreadLocal<SydApi> Api = new ThreadLocal<SydApi>() {
@Override
protected SydApi initialValue() {
return builder.build();
}
};
ExecutorService poolEnc = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolEnc.submit(() -> {
SydApi api = Api.get();
api.SYD_SM4_BatchData(keyIdx, data, ECB_ENC);
});
}
poolEnc.shutdown();
poolEnc.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
long end = System.currentTimeMillis();
long duration = end - start;
double tps = totalRequest * 1000.0 / duration;
double throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("加密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM4批量数据加密", 1024, 1, numberOfThreads, totalRequest, String.format("%.2f", tps) + " x 4", avgLatency);
SydApi apiTest = Api.get();
List<byte[]> res = apiTest.SYD_SM4_BatchData(keyIdx, data, ECB_ENC);
ExecutorService poolDec = Executors.newFixedThreadPool(numberOfThreads);
start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolDec.submit(() -> {
SydApi api = Api.get();
List<byte[]> plain = api.SYD_SM4_BatchData(keyIdx, res, ECB_DEC);
});
}
poolDec.shutdown();
poolDec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
end = System.currentTimeMillis();
duration = end - start;
tps = totalRequest * 1000.0 / duration;
throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("解密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM4批量数据解密", 1024, 1, numberOfThreads, totalRequest, tps, avgLatency);
}
public void sm4macShortEndes() throws InterruptedException {
System.out.println("-------- SM4MAC短数据性能测试开始 --------");
sm4macShortEnde(1, config.getTotal(), 1024);
sm4macShortEnde(40, config.getTotal(), 1024);
System.out.println("-------- SM4MAC短数据性能测试结束 --------\n");
}
public void sm4macShortEnde(int numberOfThreads, int totalRequest, int plainLen) throws InterruptedException {
byte[] data = new byte[plainLen];
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
ThreadLocal<SydApi> Api = new ThreadLocal<SydApi>() {
@Override
protected SydApi initialValue() {
return builder.build();
}
};
ExecutorService poolEnc = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolEnc.submit(() -> {
SydApi api = Api.get();
api.SYD_SM4Mac_ShortData(0, data);
});
}
poolEnc.shutdown();
poolEnc.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
long end = System.currentTimeMillis();
long duration = end - start;
double tps = totalRequest * 1000.0 / duration;
double throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM4MAC 短数据", 1024, 1, numberOfThreads, totalRequest, tps, avgLatency);
}
public void sm4macBatchEndes() throws InterruptedException {
System.out.println("-------- SM4MAC批量数据性能测试开始 --------");
sm4macBatchEnde(1, config.getTotal(), 1024);
sm4macBatchEnde(40, config.getTotal(), 1024);
System.out.println("-------- SM4MAC 批量数据性能测试结束 --------\n");
}
public void sm4macBatchEnde(int numberOfThreads, int totalRequest, int plainLen) throws InterruptedException {
int[] keyIdx = new int[]{0, 0, 0, 0};
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
ThreadLocal<SydApi> Api = new ThreadLocal<SydApi>() {
@Override
protected SydApi initialValue() {
return builder.build();
}
};
List<byte[]> data = new ArrayList<>();
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
data.add(new byte[1024]);
ExecutorService poolEnc = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolEnc.submit(() -> {
SydApi api = Api.get();
List<byte[]> s = api.SYD_SM4Mac_BatchData(keyIdx, data);
});
}
poolEnc.shutdown();
poolEnc.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
long end = System.currentTimeMillis();
long duration = end - start;
double tps = totalRequest * 1000.0 / duration;
double throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM4MAC 批量数据", 1024, 1, numberOfThreads, totalRequest, String.format("%.2f", tps) + " x 4", avgLatency);
}
public void sm3ShortEndes() throws InterruptedException {
System.out.println("-------- SM3短数据性能测试开始 --------");
sm3ShortEnde(1, config.getTotal(), 1024);
sm3ShortEnde(40, config.getTotal(), 1024);
System.out.println("-------- SM3短数据性能测试结束 --------\n");
}
public void sm3ShortEnde(int numberOfThreads, int totalRequest, int plainLen) throws InterruptedException {
byte[] data = new byte[plainLen];
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
ThreadLocal<SydApi> Api = new ThreadLocal<SydApi>() {
@Override
protected SydApi initialValue() {
return builder.build();
}
};
ExecutorService poolEnc = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolEnc.submit(() -> {
SydApi api = Api.get();
api.SYD_SM3_Hash_ShortData(data);
});
}
poolEnc.shutdown();
poolEnc.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
long end = System.currentTimeMillis();
long duration = end - start;
double tps = totalRequest * 1000.0 / duration;
double throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM3 短数据", 1024, 1, numberOfThreads, totalRequest, tps, avgLatency);
}
public void sm4ShortMacEndes() throws InterruptedException {
System.out.println("-------- SM4短数据加密生成MAC,验证MAC解密性能测试开始 --------");
System.out.println("单线程");
sm4ShortMacEnde(1, config.getTotal(), 1024);
System.out.println("40 线程");
sm4ShortMacEnde(40, config.getTotal(), 1024);
System.out.println("-------- SM4短数据加密生成MAC,验证MAC解密性能测试结束 --------\n");
}
public void sm4ShortMacEnde(int numberOfThreads, int totalRequest, int plainLen) throws InterruptedException {
byte[] data = new byte[plainLen];
int keyEnc = 0;
int keyMac = 0;
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
ThreadLocal<SydApi> Api = new ThreadLocal<SydApi>() {
@Override
protected SydApi initialValue() {
return builder.build();
}
};
SydApi apiTest = Api.get();
DataAndMac ret = apiTest.SYD_SM4_EncryptAndMac_ShortData(keyEnc, keyMac, data);
ExecutorService poolEnc = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolEnc.submit(() -> {
SydApi api = Api.get();
api.SYD_SM4_EncryptAndMac_ShortData(keyEnc, keyMac, data);
});
}
poolEnc.shutdown();
poolEnc.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
long end = System.currentTimeMillis();
long duration = end - start;
double tps = totalRequest * 1000.0 / duration;
double throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("加密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM4短数据加密并生成MAC", 1024, 1, numberOfThreads, totalRequest, tps, avgLatency);
ExecutorService poolDec = Executors.newFixedThreadPool(numberOfThreads);
start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolDec.submit(() -> {
SydApi api = Api.get();
api.SYD_SM4_CheckMacAndDecrypt_ShortData(keyEnc, keyMac, ret.getData(), ret.getMac());
});
}
poolDec.shutdown();
poolDec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
end = System.currentTimeMillis();
duration = end - start;
tps = totalRequest * 1000.0 / duration;
throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("解密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM4短数据解密并校验MAC", 1024, 1, numberOfThreads, totalRequest, tps, avgLatency);
}
public void sm4BatchMacEndes() throws InterruptedException {
System.out.println("-------- SM4批量数据加密生成MAC,验证MAC解密性能测试开始 --------");
System.out.println("单线程");
sm4BatchMacEnde(1, config.getTotal(), 1024);
System.out.println("40 线程");
sm4BatchMacEnde(40, config.getTotal(), 1024);
System.out.println("-------- SM4批量数据加密生成MAC,验证MAC解密性能测试结束 --------\n");
}
public void sm4BatchMacEnde(int numberOfThreads, int totalRequest, int plainLen) throws InterruptedException {
int[] keyEnc = new int[]{0, 0, 0, 0};
int[] keyMac = new int[]{0, 0, 0, 0};
List<byte[]> data = new ArrayList<>();
data.add(new byte[plainLen]);
data.add(new byte[plainLen]);
data.add(new byte[plainLen]);
data.add(new byte[plainLen]);
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
ThreadLocal<SydApi> Api = new ThreadLocal<SydApi>() {
@Override
protected SydApi initialValue() {
return builder.build();
}
};
SydApi apiTest = Api.get();
List<DataAndMac> ret = apiTest.SYD_SM4_EncryptAndMac_BatchData(keyEnc, keyMac, data);
ExecutorService poolEnc = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolEnc.submit(() -> {
SydApi api = Api.get();
api.SYD_SM4_EncryptAndMac_BatchData(keyEnc, keyMac, data);
});
}
poolEnc.shutdown();
poolEnc.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
long end = System.currentTimeMillis();
long duration = end - start;
double tps = totalRequest * 1000.0 / duration;
double throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("加密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM4批量数据加密并生成MAC", 1024, 1, numberOfThreads, totalRequest, String.format("%.2f", tps) + " x 4", avgLatency);
ExecutorService poolDec = Executors.newFixedThreadPool(numberOfThreads);
start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolDec.submit(() -> {
SydApi api = Api.get();
api.SYD_SM4_CheckMacAndDecrypt_BatchData(keyEnc, keyMac, ret);
});
}
poolDec.shutdown();
poolDec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
end = System.currentTimeMillis();
duration = end - start;
tps = totalRequest * 1000.0 / duration;
throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("解密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
writeToPerformanceFile("SM4批量数据解密并校验MAC", 1024, 1, numberOfThreads, totalRequest, String.format("%.2f", tps) + " x 4", avgLatency);
}
public void sm4LongEnde() {
System.out.println("-------- SM4长数据加解密性能测试开始 --------");
byte[] data = new byte[2048];
int key = 0;
// ByteBuffer enDataBuff = ByteBuffer.allocate(100 * 1024 * 1024 + 16);
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
long start = System.currentTimeMillis();
SydApi api = builder.build();
ISM4 sm4 = api.initSM4(key, ECB_ENC);
for (int i = 0; i < 100 * 1024 * 1024 / data.length; i++) {
sm4.update(data);
}
byte[] res = sm4.finish();
long end = System.currentTimeMillis();
long duration = end - start;
double throughput = 100.0 * 1000 / duration;
System.out.println("加密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
writeToPerformanceFile2("SM4长数据加密", "100M", 1, 1, throughput);
start = System.currentTimeMillis();
sm4 = api.initSM4(key, ECB_DEC);
for (int i = 0; i < 100 * 1024 * 1024 / data.length; i++) {
sm4.update(data);
}
// sm4.finish();
end = System.currentTimeMillis();
duration = end - start;
throughput = 100.0 * 1000 / duration;
System.out.println("解密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
writeToPerformanceFile2("SM4长数据解密", "100M", 1, 1, throughput);
System.out.println("-------- SM4长数据加解密性能测试结束 --------\\n");
}
public void sm4MacLongEnde() {
System.out.println("-------- SM4MAC长数据性能测试开始 --------");
byte[] data = new byte[2048];
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
long start = System.currentTimeMillis();
SydApi api = builder.build();
ISM4Mac sm4mac = api.initSM4Mac(0);
for (int i = 0; i < 100 * 1024 * 1024 / data.length; i++) {
sm4mac.update(data);
}
sm4mac.digest();
long end = System.currentTimeMillis();
long duration = end - start;
double throughput = 100.0 * 1000 / duration;
System.out.println("共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
writeToPerformanceFile2("SM4长数据MAC", "100M", 1, 1, throughput);
System.out.println("-------- SM4MAC长数据性能测试结束 --------");
}
public void sm3LongEnde() {
System.out.println("-------- SM3长数据性能测试开始 --------");
byte[] data = new byte[2048];
SydApiBuilder builder = new SydApiBuilder(
config.getIps(),
config.getPorts(),
1000,
2000
);
long start = System.currentTimeMillis();
SydApi api = builder.build();
ISM3 sm3 = api.initSM3();
for (int i = 0; i < 100 * 1024 * 1024 / data.length; i++) {
sm3.update(data);
}
sm3.digest();
long end = System.currentTimeMillis();
long duration = end - start;
double throughput = 100.0 * 1000 / duration;
System.out.println("共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
writeToPerformanceFile2("SM3长数据", "100MB", 1, 1, throughput);
System.out.println("-------- SM3长数据性能测试结束 --------");
}
public void perfAll() throws InterruptedException {
this.sm4ShortEndes();
this.sm4BatchEndes();
// this.sm4macShortEndes();
// this.sm4macBatchEndes();
// this.sm3ShortEndes();
this.sm4ShortMacEndes();
this.sm4BatchMacEndes();
// this.sm4LongEnde();
// this.sm4MacLongEnde();
// this.sm3LongEnde();
}
public static void showmenu() {
System.out.println("请选择测试项:");
System.out.println("1.SM4 短数据加解密");
System.out.println("2.SM4 批量数据加解密");
// System.out.println("3.SM4MAC 短数据");
// System.out.println("4.SM4MAC 批量数据");
// System.out.println("5.SM3 短数据");
System.out.println("6.SM4 短数据加密后生成MAC解密验证MAC");
System.out.println("7.SM4 批量数据加密后生成MAC解密验证MAC");
// System.out.println("8.SM4 长数据加解密");
// System.out.println("9.SM4 长数据MAC");
// System.out.println("10.SM3 长数据");
// System.out.println("11. 短数据 SM4+MAC性能测试");
// System.out.println("12. 批量数据 SM4+MAC性能测试");
System.out.println("-1.退出");
}
public static void perfMenu(Config config, Choise choise, TestMAC test) throws Exception {
boolean flag = true;
while (flag) {
showmenu();
switch (choise.getAsInt()) {
case 1:
test.sm4ShortEndes();
break;
case 2:
test.sm4BatchEndes();
break;
// case 3:
// test.sm4macShortEndes();
// break;
// case 4:
// test.sm4macBatchEndes();
// break;
// case 5:
// test.sm3ShortEndes();
// break;
case 6:
test.sm4ShortMacEndes();
break;
case 7:
test.sm4BatchMacEndes();
break;
// case 8:
// test.sm4LongEnde();
// break;
// case 9:
// test.sm4MacLongEnde();
// break;
// case 10:
// test.sm3LongEnde();
// break;
// case 11: {
// test.sm4ShortMacEndes();
// break;
// }
// case 12: {
// test.sm4BatchMacEndes();
// break;
// }
case -1:
flag = false;
break;
}
}
}
private static Config config = null;
public static void main(String[] args) throws Exception {
// 载入配置文件
config = Config.loadConfig();
if (config == null || config.isDebug()) {
System.setProperty("com.sunyard.sydapi4j.debug", "true");
}
System.out.println("ips=" + Arrays.toString(config.getIps()));
System.out.println("ports=" + Arrays.toString(config.getPorts()));
System.out.println("debug=" + config.isDebug());
TestMAC test = new TestMAC();
Choise choise = new Choise(args);
menu1(config, choise, test);
}
}

View File

@ -0,0 +1,210 @@
package test;
import com.sun.jna.Pointer;
import com.sunyard.sge.database.DataAndMac;
import com.sunyard.sge.database.SydApi;
import com.sunyard.sge.database.SydApi4Database;
import com.sunyard.sge.plus.SydLibrary;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestOpenClose {
private static Config config ;
public static void sm4ShortMacEnde1(int numberOfThreads, int totalRequest, int plainLen) throws InterruptedException {
byte[] data = new byte[plainLen];
int keyEnc = 0;
int keyMac = 0;
Set<SydApi> syncSet = Collections.synchronizedSet(new HashSet<>());
ThreadLocal<SydApi> Api = new ThreadLocal<SydApi>() {
@Override
protected SydApi initialValue() {
SydApi api = new SydApi4Database();
try {
api.SYD_Short_Connect_Ex(config.getIps(), config.getPorts(), 2000, 2000);
System.out.println("create link " + Thread.currentThread().getName());
syncSet.add( api );
System.out.println("建立链接 " + syncSet.size());
}catch (Exception e) {
System.out.println("error link " + Thread.currentThread().getName());
// e.printStackTrace();
throw e;
}
return api;
}
};
try {
System.out.println("准备密文数据");
SydApi apiTest = Api.get();
final DataAndMac ret = apiTest.SYD_SM4_EncryptAndMac_ShortData(keyEnc, keyMac, data);
apiTest.SYD_Disconnect_Ex();
System.out.println("密文数据准备完成");
ExecutorService poolEnc = Executors.newFixedThreadPool(numberOfThreads);
long start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolEnc.submit(() -> {
SydApi api = Api.get();
if ( null == api ) {
System.out.println("api is null");
}
api.SYD_SM4_EncryptAndMac_ShortData(keyEnc, keyMac, data);
// System.out.println("encrypt " + Thread.currentThread().getName());
// System.out.println("Thread=" + Thread.currentThread().getName());
// SydApi4Database adb = (SydApi4Database) api;
// System.out.println("handler=" + adb.getHandler());
});
}
poolEnc.shutdown();
poolEnc.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
System.out.println("释放链接 " + syncSet.size());
syncSet.forEach(SydApi::SYD_Disconnect_Ex);
syncSet.clear();
// System.out.println("sleep");
// Thread.sleep(10 * 1000);
long end = System.currentTimeMillis();
long duration = end - start;
double tps = totalRequest * 1000.0 / duration;
double throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("加密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
double avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
ExecutorService poolDec = Executors.newFixedThreadPool(numberOfThreads);
start = System.currentTimeMillis();
for (int i = 0; i < totalRequest; i++) {
poolDec.submit(() -> {
SydApi api = Api.get();
api.SYD_SM4_CheckMacAndDecrypt_ShortData(keyEnc, keyMac, ret.getData(), ret.getMac());
// System.out.println("decrypt " + Thread.currentThread().getName());
});
}
poolDec.shutdown();
poolDec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
System.out.println("释放链接 " + syncSet.size());
syncSet.forEach(SydApi::SYD_Disconnect_Ex);
syncSet.clear();
// System.out.println("sleep");
// Thread.sleep(10 * 1000);
end = System.currentTimeMillis();
duration = end - start;
tps = totalRequest * 1000.0 / duration;
throughput = totalRequest * 1000.0 / duration * plainLen / 1024 / 1024;
System.out.println("并发数: " + numberOfThreads);
System.out.println("解密共花费 " + String.format("%.2f", duration / 1000.0) + "");
System.out.println("TPS: " + String.format("%.2f", tps));
System.out.println("吞吐量: " + String.format("%.2f", throughput) + " MB/S");
avgLatency = numberOfThreads * duration * 1.0 / totalRequest;
} catch (Exception e) {
System.out.println("密文数据准备异常");
e.printStackTrace();
throw e;
}
}
public static void case1(){
System.out.println("case1 start");
// PointerByReference phHandle = new PointerByReference();
Pointer[] phHandle = new Pointer[1];
int connectResult = SydLibrary.INSTANCE.SYD_Connect_Ex(
config.getIps(),
config.getPorts(),
config.getIps().length,
1000,
2000,
0,
phHandle);
if ( 0 != connectResult ){
System.out.println("link error" + connectResult);
} else {
System.out.println("SYD_Disconnect this.phHandle=" + Pointer.nativeValue(phHandle[0]));
System.out.println("link");
}
System.out.println("SYD_Disconnect this.phHandle=" + Pointer.nativeValue(phHandle[0]));
int disResult = SydLibrary.INSTANCE.SYD_DisConnect_Ex(phHandle[0]);
if ( 0 != disResult ){
System.out.println("disResult error" + disResult);
} else {
System.out.println("disResult");
}
System.out.println("case1 end");
}
public static void case2(){
System.out.println("case2 start");
SydApi4Database api = new SydApi4Database();
api.SYD_Short_Connect_Ex(config.getIps(), config.getPorts(), 2000, 2000);
api.SYD_Disconnect_Ex();
System.out.println("case2 end");
}
public static void case3(String[] args) throws InterruptedException {
int threads = 40;
try {
threads = Integer.valueOf(args[0]);
}catch ( Exception e ) {
}
System.out.println("threads=" + threads);
System.out.println("case3 start");
while (true) {
sm4ShortMacEnde1(threads, 100000, 1024);
}
// System.out.println("case3 end");
}
public static void main(String[] args) throws InterruptedException {
// 载入配置文件
config = Config.loadConfig();
System.out.println("config=" + Arrays.toString(config.getIps()));
// case1();
// case2();
case3(args);
}
}