添加批量数据并行支持

This commit is contained in:
cheney
2022-09-07 20:11:03 +08:00
parent d2aaa8e9ac
commit b32d2d7c40
10 changed files with 1099 additions and 768 deletions
@@ -1,789 +1,117 @@
package com.sunyard.sge.database; package com.sunyard.sge.database;
import com.sunyard.SydApiException; import com.sunyard.SydApiException;
import com.sunyard.proto.Util;
import com.sunyard.sge.database.pool.HsmLinkInfo; import com.sunyard.sge.database.pool.HsmLinkInfo;
import com.sunyard.sge.log.LogFactory; import com.sunyard.sge.pool.CommWorker;
import com.sunyard.sge.pool.ObjectInPool;
import com.sunyard.util.SYMUtil;
import org.apache.logging.log4j.Logger;
import racal.sunyard.main.SydApi4j; import racal.sunyard.main.SydApi4j;
import java.util.Arrays; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/** public class SydApi4Database extends SydApi4Function {
* 上海黄金交易所 - 数据库加密方案 private static final int BATCH_SIZE = 7680;
*/ private static final CommWorker longLinkWorks = new CommWorker();
public class SydApi4Database implements SydApi {
static {
SydApi.SYD_SetLogConfig("./logs/", 0);
}
private SydApi4j[] hsms = null;
private HsmLinkInfo[] linkInfos = null;
private ObjectInPool oip = null;
private boolean isShortLinkMode = false;
public SydApi4Database() { public SydApi4Database() {
isShortLinkMode = true; super();
} }
public SydApi4Database(SydApi4j[] hsms, HsmLinkInfo[] linkInfos) { public SydApi4Database(SydApi4j[] hsms, HsmLinkInfo[] linkInfos) {
this.hsms = hsms; super(hsms, linkInfos);
this.linkInfos = linkInfos;
}
public SydApi4j[] getHsms() {
return hsms;
}
public HsmLinkInfo[] getLinkInfos() {
return linkInfos;
}
public void setOip(ObjectInPool oip) {
this.oip = oip;
}
private void updateLastUseTime(){
if ( null != this.oip ) {
this.oip.updateLastUseTime();
}
}
@Override
public SydApi SYD_Short_Connect_Ex(String[] pcIpList, int[] iPortList, int iConnectTimeOut, int allDealTimeOut) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_Connect_Ex方法接收参数:pcIpList:{},iPortList:{},iConnectTimeOut:{},iDealTimeOut:{}", Arrays.toString(pcIpList), Arrays.toString(iPortList), iConnectTimeOut, allDealTimeOut);
}
if (pcIpList.length != iPortList.length) {
throw new IllegalArgumentException("ip与端口数量不一致");
}
SydApi4j[] apis = new SydApi4j[pcIpList.length];
int iDealTimeOut = allDealTimeOut / pcIpList.length;
boolean connected = false;
for (int i = 0; i < pcIpList.length; i++) {
try {
apis[i] = (SydApi4j) new SydApi4j().connect(pcIpList[i], iPortList[i], null, iConnectTimeOut, iDealTimeOut);
connected = true;
} catch (Exception e) {
// 忽略错误
log.error("网络连接错误 {} {} - 忽略", pcIpList[i], iPortList[i]);
}
}
if (!connected) {
// TODO
throw new SydApiException("连接错误", -1);
} }
hsms = apis; private List<byte[]> super_SYD_SM4_BatchData(int[] iKeyIndex, List<byte[]> pcData, int iFlag) {
isShortLinkMode = true; return super.SYD_SM4_BatchData(iKeyIndex, pcData, iFlag);
return this;
}
public void SYD_Disconnect() {
if (null == hsms) {
return;
}
try {
for (int i = 0; i < hsms.length; i++) {
SydApi4j api = hsms[i];
if (null != api) {
try {
api.disconnect();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
}
hsms = null;
}
@Override
public void SYD_Disconnect_Ex() {
if (isShortLinkMode) {
SYD_Disconnect();
}
// 配合链接池,不再需要释放。
}
@Override
public String SYD_SM3_Hash_ShortData(byte[] pcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM3_Hash_ShortData方法接收参数:pcData:{}", Arrays.toString(pcData));
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
SydApiException le = new SydApiException(-1);
updateLastUseTime();
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
byte[] hash = api.SYD_SM3_LongData(pcData, null, 0);
log.debug("api.SYD_SM3_LongData方法返回值:{}", Arrays.toString(hash));
return Util.bytes2HexString(hash);
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
byte[] hash = api.SYD_SM3_LongData(pcData, null, 0);
log.debug("api.SYD_SM3_LongData方法返回值:{}", Arrays.toString(hash));
return Util.bytes2HexString(hash);
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public LongDataReturn<String, String> SYD_SM3_Hash_LongData(byte[] pcData, int iPkgNum, String pcProcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM3_Hash_LongData方法接收参数:pcData:{},iPkgNum:{},pcProcData:{}", Arrays.toString(pcData), iPkgNum, pcProcData);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
byte[] procData = null;
if (2 == iPkgNum || 3 == iPkgNum) {
procData = Util.hexString2Bytes(pcProcData);
log.debug("Util.hexString2Bytes方法返回值:{}", Arrays.toString(procData));
}
SydApiException le = new SydApiException(-1);
updateLastUseTime();
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
byte[] hash = api.SYD_SM3_LongData(pcData, procData, iPkgNum);
log.debug("api.SYD_SM3_LongData方法返回值:{}", Arrays.toString(hash));
if (0 == iPkgNum || 3 == iPkgNum) {
return new LongDataReturn<String, String>(null, Util.bytes2HexString(hash));
} else {
return new LongDataReturn<String, String>(Util.bytes2HexString(hash), null);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
byte[] hash = api.SYD_SM3_LongData(pcData, procData, iPkgNum);
log.debug("api.SYD_SM3_LongData方法返回值:{}", Arrays.toString(hash));
if (0 == iPkgNum || 3 == iPkgNum) {
return new LongDataReturn<String, String>(null, Util.bytes2HexString(hash));
} else {
return new LongDataReturn<String, String>(Util.bytes2HexString(hash), null);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public byte[] SYD_SM4_ShortData(int iKeyIndex, byte[] pcData, int iFlag) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4_ShortData方法接收参数:iKeyIndex:{},pcData:{},iFlag:{}", iKeyIndex, Arrays.toString(pcData), iFlag);
}
if (iFlag == Consts.ECB_DEC && null == pcData || pcData.length == 0) {
throw new SydApiException(19);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
updateLastUseTime();
String keyIndex = String.format("%08d", iKeyIndex);
SydApiException le = new SydApiException(-1);
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYMEncryptData(
com.sunyard.SydApi.NALG_SM4,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData);
} else {
return api.SYMDecryptData(
com.sunyard.SydApi.NALG_SM4,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYMEncryptData(
com.sunyard.SydApi.NALG_SM4,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData);
} else {
return api.SYMDecryptData(
com.sunyard.SydApi.NALG_SM4,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
} }
@Override @Override
public List<byte[]> SYD_SM4_BatchData(int[] iKeyIndex, List<byte[]> pcData, int iFlag) { public List<byte[]> SYD_SM4_BatchData(int[] iKeyIndex, List<byte[]> pcData, int iFlag) {
Logger log = LogFactory.getLogger(); // 将数据进行分组,防止超长。
if (LogFactory.iLogLevel == 3) { List<List<byte[]>> dataGroups = new ArrayList<>();
log.debug("SYD_SM4_BatchData方法接收参数:iKeyIndex:{},pcData元素个数为:{},iFlag:{}", iKeyIndex, pcData.size(), iFlag); List<List<Integer>> keyGroups = new ArrayList<>();
} int totalLen = 0;
if (iFlag == Consts.ECB_DEC) {
for (byte[] pcdata : pcData) {
if (null == pcData || pcdata.length == 0) {
throw new SydApiException(19);
}
}
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String[] keys = new String[iKeyIndex.length]; List<byte[]> curDataGroup = new ArrayList<>();
updateLastUseTime(); List<Integer> curKeyGroup = new ArrayList<>();
for (int i = 0; i < iKeyIndex.length; i++) {
keys[i] = "SK" + SYMUtil.genPrivateKeyMark("000000", "00A", String.format("%08d", iKeyIndex[i]));
}
SydApiException le = new SydApiException(-1); for (int i = 0 ; i < pcData.size(); i++ ) {
for (SydApi4j api : this.hsms) { byte[] data = pcData.get( i );
if (null == api) { if (null == data) {
continue; data = new byte[0];
} }
if (isShortLinkMode) { if (
try { curDataGroup.size() <= 9 // 分组小于等于 9 个
if (Consts.ECB_ENC == iFlag) { && (totalLen + data.length < BATCH_SIZE) // 总大小小于 BATCH_SIZE
return api.SYMEncryptDecryptBatchData(8, 1, null, keys, 1, pcData); ) {
curDataGroup.add(data);
curKeyGroup.add( iKeyIndex[i] );
totalLen += data.length;
} else { } else {
return api.SYMEncryptDecryptBatchData(9, 1, null, keys, 1, pcData); // 扩展包
} dataGroups.add(curDataGroup);
} catch (SydApiException e) { keyGroups.add( curKeyGroup );
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYMEncryptDecryptBatchData(8, 1, null, keys, 1, pcData);
} else { curDataGroup = new ArrayList<>();
return api.SYMEncryptDecryptBatchData(9, 1, null, keys, 1, pcData); curKeyGroup = new ArrayList<>();
curDataGroup.add(data);
curKeyGroup.add( iKeyIndex[i] );
totalLen = data.length;
} }
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
} }
dataGroups.add( curDataGroup );
keyGroups.add( curKeyGroup );
// 并发处理
List<FutureTask<List<byte[]>>> tasks = new ArrayList<>();
for ( int i = 0; i < dataGroups.size(); i++ ) {
int finalI = i;
FutureTask<List<byte[]>> task = longLinkWorks.fTask(new Callable<List<byte[]>>() {
@Override @Override
public byte[] SYD_SM4_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, int iFlag) { public List<byte[]> call() throws Exception {
Logger log = LogFactory.getLogger(); return super_SYD_SM4_BatchData(toIntArray(keyGroups.get( finalI )), dataGroups.get( finalI ), iFlag);
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4_LongData方法接收参数:iKeyIndex:{},pcData:{},iPkgNum:{},iFlag:{}", iKeyIndex, Arrays.toString(pcData), iPkgNum, iFlag);
} }
if (iFlag == Consts.ECB_DEC && (null == pcData || pcData.length == 0)) { });
throw new SydApiException(19); tasks.add(task);
} }
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
updateLastUseTime();
String keyIndex = String.format("%08d", iKeyIndex);
SydApiException le = new SydApiException(-1);
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try { try {
if (Consts.ECB_ENC == iFlag) { List<byte[]> ret = new ArrayList<>();
return api.SYD_SM4_LongData( for (FutureTask<List<byte[]>> t : tasks) {
8, ret.addAll(t.get());
1, null,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
} else {
return api.SYD_SM4_LongData(
9,
1, null,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
} }
return ret;
} catch (SydApiException e) { } catch (Exception e) {
le = e; throw new SydApiException("并行任务执行失败", 0xC101);
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
} }
throw e;
}
} else {
synchronized (api) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYD_SM4_LongData(
8,
1, null,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
} else {
return api.SYD_SM4_LongData(
9,
1, null,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
}
} catch (SydApiException e) {
if (null==e){
}
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
} }
@Override @Override
public String[] SYD_SM4Mac_BatchData(int[] iKeyIndex, List<byte[]> pcData) { public String[] SYD_SM4Mac_BatchData(int[] iKeyIndex, List<byte[]> pcData) {
Logger log = LogFactory.getLogger(); return super.SYD_SM4Mac_BatchData(iKeyIndex, pcData);
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_BatchData:iKeyIndex:{},pcData元素个数为:{}", iKeyIndex, pcData.size());
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String[] keys = new String[iKeyIndex.length];
updateLastUseTime();
for (int i = 0; i < iKeyIndex.length; i++) {
keys[i] = "SK" + SYMUtil.genPrivateKeyMark("000000", "00A", String.format("%08d", iKeyIndex[i]));
}
SydApiException le = new SydApiException(-1);
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
List<byte[]> list = api.SYMEncryptDecryptBatchData(8, 2, null, keys, 1, pcData);
String[] ret = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
byte[] mac = new byte[16];
byte[] buff = list.get(i);
System.arraycopy(buff, buff.length - 16, mac, 0, 16);
ret[i] = Util.bytes2HexString(buff);
}
return ret;
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
List<byte[]> list = api.SYMEncryptDecryptBatchData(8, 2, null, keys, 1, pcData);
String[] ret = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
byte[] mac = new byte[16];
byte[] buff = list.get(i);
System.arraycopy(buff, buff.length - 16, mac, 0, 16);
ret[i] = Util.bytes2HexString(buff);
}
return ret;
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
} }
@Override @Override
public boolean[] SYD_SM4Mac_BatchData(int[] iKeyIndex, List<byte[]> pcData, String[] pcMac) { public boolean[] SYD_SM4Mac_BatchData(int[] iKeyIndex, List<byte[]> pcData, String[] pcMac) {
Logger log = LogFactory.getLogger(); return super.SYD_SM4Mac_BatchData(iKeyIndex, pcData, pcMac);
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_BatchData方法接收参数:iKeyIndex:{},pcData元素个数为:{},pcMac:{}", iKeyIndex, pcData.size(), Arrays.toString(pcMac));
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
} }
String[] keys = new String[iKeyIndex.length]; private static int[] toIntArray(List<Integer> list){
updateLastUseTime(); if ( null == list || 0 == list.size() ) {
for (int i = 0; i < iKeyIndex.length; i++) { return new int[0];
keys[i] = "SK" + SYMUtil.genPrivateKeyMark("000000", "00A", String.format("%08d", iKeyIndex[i]));
} }
int[] ia = new int[ list.size() ];
SydApiException le = new SydApiException(-1); for ( int i = 0 ; i < ia.length; i ++ ) {
for (SydApi4j api : this.hsms) { ia[i] = list.get(i);
if (null == api) {
continue;
} }
if (isShortLinkMode) { return ia;
try {
List<byte[]> list = api.SYMEncryptDecryptBatchData(8, 2, null, keys, 1, pcData);
boolean[] ret = new boolean[list.size()];
for (int i = 0; i < list.size(); i++) {
byte[] mac = new byte[16];
byte[] buff = list.get(i);
System.arraycopy(buff, buff.length - 16, mac, 0, 16);
ret[i] = pcMac[i].equals(Util.bytes2HexString(buff));
}
return ret;
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
List<byte[]> list = api.SYMEncryptDecryptBatchData(8, 2, null, keys, 1, pcData);
boolean[] ret = new boolean[list.size()];
for (int i = 0; i < list.size(); i++) {
byte[] mac = new byte[16];
byte[] buff = list.get(i);
System.arraycopy(buff, buff.length - 16, mac, 0, 16);
ret[i] = pcMac[i].equals(Util.bytes2HexString(buff));
}
return ret;
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public LongDataReturn<String, String> SYD_SM4Mac_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, String pcProcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_LongData方法接收参数:iKeyIndex:{},pcData:{},iPkgNum:{},pcProcData:{}", iKeyIndex, Arrays.toString(pcData), iPkgNum, pcProcData);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String keyIndex = String.format("%08d", iKeyIndex);
byte[] iv = null;
// 仅一包 和 第一包 忽略 pcProcData 参数
if (Consts.PkgNumAll != iPkgNum && Consts.PkgNumHead != iPkgNum) {
iv = pcProcData.getBytes();
}
SydApiException le = new SydApiException(-1);
updateLastUseTime();
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
byte[] ret = api.SYD_SM4_LongData(
8,
2, iv,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
byte[] mac = new byte[16];
System.arraycopy(ret, ret.length - 16, mac, 0, 16);
// 仅一包 和 尾包 返回最终结果
if (Consts.PkgNumAll == iPkgNum || Consts.PkgNumTail == iPkgNum) {
return new LongDataReturn<>(null, Util.bytes2HexString(mac));
} else {
// 返回中间值
return new LongDataReturn<>(Util.bytes2HexString(mac), null);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
byte[] ret = api.SYD_SM4_LongData(
8,
2, iv,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
byte[] mac = new byte[16];
System.arraycopy(ret, ret.length - 16, mac, 0, 16);
// 仅一包 和 尾包 返回最终结果
if (Consts.PkgNumAll == iPkgNum || Consts.PkgNumTail == iPkgNum) {
return new LongDataReturn<>(null, Util.bytes2HexString(mac));
} else {
// 返回中间值
return new LongDataReturn<>(Util.bytes2HexString(mac), null);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public LongDataReturn<String, Boolean> SYD_SM4Mac_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, String pcProcData, String pcMac) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_LongData方法接收参数:iKeyIndex:{},pcData:{},iPkgNum:{},pcProcData:{}", iKeyIndex, Arrays.toString(pcData), iPkgNum, pcProcData, pcMac);
}
updateLastUseTime();
LongDataReturn<String, String> ret = SYD_SM4Mac_LongData(iKeyIndex, pcData, iPkgNum, pcProcData);
// 仅一包 和 尾包 返回最终结果
if (Consts.PkgNumAll == iPkgNum || Consts.PkgNumTail == iPkgNum) {
return new LongDataReturn<>(null, pcMac.equals(ret.getData()));
} else {
// 返回中间值
return new LongDataReturn<>(ret.getProcData(), false);
}
}
@Override
public String SYD_SM4Mac_ShortData(int iKeyIndex, byte[] pcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_ShortData方法接收参数:iKeyIndex:{},pcData:{},iFlag:{}", iKeyIndex, Arrays.toString(pcData));
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String keyIndex = "SK" + SYMUtil.genPrivateKeyMark("000000", "00A", String.format("%08d", iKeyIndex));
log.debug("\"SK\" + SYMUtil.genPrivateKeyMark方法返回值:{}", keyIndex);
SydApiException le = new SydApiException(-1);
updateLastUseTime();
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
return api.SYD_SM4Mac_ShortData(keyIndex, pcData);
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
else {
synchronized (api){
try {
return api.SYD_SM4Mac_ShortData(keyIndex, pcData);
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public boolean SYD_SM4Mac_ShortData(int iKeyIndex, byte[] pcData, String pcMac) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_ShortData方法接收参数:{}", iKeyIndex, Arrays.toString(pcData), pcMac);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
if (null == pcMac) {
throw new IllegalArgumentException();
}
updateLastUseTime();
String mac = this.SYD_SM4Mac_ShortData(iKeyIndex, pcData);
log.debug(this + ".SYD_SM4Mac_ShortData方法返回值:{}", mac);
return pcMac.equals(mac);
}
@Override
public SydApiSM4 initSM4(int iKeyIndex, int ende) {
return new SydApiSM4(this,iKeyIndex,ende);
}
public SydApiSM3 initSM3() {
return new SydApiSM3(this);
}
@Override
public SydSM4Mac initSM4Mac(int iKeyIndex) {
return new SydSM4Mac(this, iKeyIndex);
} }
} }
@@ -0,0 +1,789 @@
package com.sunyard.sge.database;
import com.sunyard.SydApiException;
import com.sunyard.proto.Util;
import com.sunyard.sge.database.pool.HsmLinkInfo;
import com.sunyard.sge.log.LogFactory;
import com.sunyard.sge.pool.ObjectInPool;
import com.sunyard.util.SYMUtil;
import org.apache.logging.log4j.Logger;
import racal.sunyard.main.SydApi4j;
import java.util.Arrays;
import java.util.List;
/**
* 上海黄金交易所 - 数据库加密方案
*/
public class SydApi4Function implements SydApi {
static {
SydApi.SYD_SetLogConfig("./logs/", 0);
}
private SydApi4j[] hsms = null;
private HsmLinkInfo[] linkInfos = null;
private ObjectInPool oip = null;
private boolean isShortLinkMode = false;
public SydApi4Function() {
isShortLinkMode = true;
}
public SydApi4Function(SydApi4j[] hsms, HsmLinkInfo[] linkInfos) {
this.hsms = hsms;
this.linkInfos = linkInfos;
}
public SydApi4j[] getHsms() {
return hsms;
}
public HsmLinkInfo[] getLinkInfos() {
return linkInfos;
}
public void setOip(ObjectInPool oip) {
this.oip = oip;
}
private void updateLastUseTime(){
if ( null != this.oip ) {
this.oip.updateLastUseTime();
}
}
@Override
public SydApi SYD_Short_Connect_Ex(String[] pcIpList, int[] iPortList, int iConnectTimeOut, int allDealTimeOut) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_Connect_Ex方法接收参数:pcIpList:{},iPortList:{},iConnectTimeOut:{},iDealTimeOut:{}", Arrays.toString(pcIpList), Arrays.toString(iPortList), iConnectTimeOut, allDealTimeOut);
}
if (pcIpList.length != iPortList.length) {
throw new IllegalArgumentException("ip与端口数量不一致");
}
SydApi4j[] apis = new SydApi4j[pcIpList.length];
int iDealTimeOut = allDealTimeOut / pcIpList.length;
boolean connected = false;
for (int i = 0; i < pcIpList.length; i++) {
try {
apis[i] = (SydApi4j) new SydApi4j().connect(pcIpList[i], iPortList[i], null, iConnectTimeOut, iDealTimeOut);
connected = true;
} catch (Exception e) {
// 忽略错误
log.error("网络连接错误 {} {} - 忽略", pcIpList[i], iPortList[i]);
}
}
if (!connected) {
// TODO
throw new SydApiException("连接错误", -1);
}
hsms = apis;
isShortLinkMode = true;
return this;
}
public void SYD_Disconnect() {
if (null == hsms) {
return;
}
try {
for (int i = 0; i < hsms.length; i++) {
SydApi4j api = hsms[i];
if (null != api) {
try {
api.disconnect();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
}
hsms = null;
}
@Override
public void SYD_Disconnect_Ex() {
if (isShortLinkMode) {
SYD_Disconnect();
}
// 配合链接池,不再需要释放。
}
@Override
public String SYD_SM3_Hash_ShortData(byte[] pcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM3_Hash_ShortData方法接收参数:pcData:{}", Arrays.toString(pcData));
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
SydApiException le = new SydApiException(-1);
updateLastUseTime();
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
byte[] hash = api.SYD_SM3_LongData(pcData, null, 0);
log.debug("api.SYD_SM3_LongData方法返回值:{}", Arrays.toString(hash));
return Util.bytes2HexString(hash);
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
byte[] hash = api.SYD_SM3_LongData(pcData, null, 0);
log.debug("api.SYD_SM3_LongData方法返回值:{}", Arrays.toString(hash));
return Util.bytes2HexString(hash);
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public LongDataReturn<String, String> SYD_SM3_Hash_LongData(byte[] pcData, int iPkgNum, String pcProcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM3_Hash_LongData方法接收参数:pcData:{},iPkgNum:{},pcProcData:{}", Arrays.toString(pcData), iPkgNum, pcProcData);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
byte[] procData = null;
if (2 == iPkgNum || 3 == iPkgNum) {
procData = Util.hexString2Bytes(pcProcData);
log.debug("Util.hexString2Bytes方法返回值:{}", Arrays.toString(procData));
}
SydApiException le = new SydApiException(-1);
updateLastUseTime();
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
byte[] hash = api.SYD_SM3_LongData(pcData, procData, iPkgNum);
log.debug("api.SYD_SM3_LongData方法返回值:{}", Arrays.toString(hash));
if (0 == iPkgNum || 3 == iPkgNum) {
return new LongDataReturn<String, String>(null, Util.bytes2HexString(hash));
} else {
return new LongDataReturn<String, String>(Util.bytes2HexString(hash), null);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
byte[] hash = api.SYD_SM3_LongData(pcData, procData, iPkgNum);
log.debug("api.SYD_SM3_LongData方法返回值:{}", Arrays.toString(hash));
if (0 == iPkgNum || 3 == iPkgNum) {
return new LongDataReturn<String, String>(null, Util.bytes2HexString(hash));
} else {
return new LongDataReturn<String, String>(Util.bytes2HexString(hash), null);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public byte[] SYD_SM4_ShortData(int iKeyIndex, byte[] pcData, int iFlag) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4_ShortData方法接收参数:iKeyIndex:{},pcData:{},iFlag:{}", iKeyIndex, Arrays.toString(pcData), iFlag);
}
if (iFlag == Consts.ECB_DEC && null == pcData || pcData.length == 0) {
throw new SydApiException(19);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
updateLastUseTime();
String keyIndex = String.format("%08d", iKeyIndex);
SydApiException le = new SydApiException(-1);
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYMEncryptData(
com.sunyard.SydApi.NALG_SM4,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData);
} else {
return api.SYMDecryptData(
com.sunyard.SydApi.NALG_SM4,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYMEncryptData(
com.sunyard.SydApi.NALG_SM4,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData);
} else {
return api.SYMDecryptData(
com.sunyard.SydApi.NALG_SM4,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public List<byte[]> SYD_SM4_BatchData(int[] iKeyIndex, List<byte[]> pcData, int iFlag) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4_BatchData方法接收参数:iKeyIndex:{},pcData元素个数为:{},iFlag:{}", iKeyIndex, pcData.size(), iFlag);
}
if (iFlag == Consts.ECB_DEC) {
for (byte[] pcdata : pcData) {
if (null == pcData || pcdata.length == 0) {
throw new SydApiException(19);
}
}
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String[] keys = new String[iKeyIndex.length];
updateLastUseTime();
for (int i = 0; i < iKeyIndex.length; i++) {
keys[i] = "SK" + SYMUtil.genPrivateKeyMark("000000", "00A", String.format("%08d", iKeyIndex[i]));
}
SydApiException le = new SydApiException(-1);
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYMEncryptDecryptBatchData(8, 1, null, keys, 1, pcData);
} else {
return api.SYMEncryptDecryptBatchData(9, 1, null, keys, 1, pcData);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYMEncryptDecryptBatchData(8, 1, null, keys, 1, pcData);
} else {
return api.SYMEncryptDecryptBatchData(9, 1, null, keys, 1, pcData);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public byte[] SYD_SM4_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, int iFlag) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4_LongData方法接收参数:iKeyIndex:{},pcData:{},iPkgNum:{},iFlag:{}", iKeyIndex, Arrays.toString(pcData), iPkgNum, iFlag);
}
if (iFlag == Consts.ECB_DEC && (null == pcData || pcData.length == 0)) {
throw new SydApiException(19);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
updateLastUseTime();
String keyIndex = String.format("%08d", iKeyIndex);
SydApiException le = new SydApiException(-1);
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYD_SM4_LongData(
8,
1, null,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
} else {
return api.SYD_SM4_LongData(
9,
1, null,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
if (Consts.ECB_ENC == iFlag) {
return api.SYD_SM4_LongData(
8,
1, null,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
} else {
return api.SYD_SM4_LongData(
9,
1, null,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
}
} catch (SydApiException e) {
if (null==e){
}
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public String[] SYD_SM4Mac_BatchData(int[] iKeyIndex, List<byte[]> pcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_BatchData:iKeyIndex:{},pcData元素个数为:{}", iKeyIndex, pcData.size());
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String[] keys = new String[iKeyIndex.length];
updateLastUseTime();
for (int i = 0; i < iKeyIndex.length; i++) {
keys[i] = "SK" + SYMUtil.genPrivateKeyMark("000000", "00A", String.format("%08d", iKeyIndex[i]));
}
SydApiException le = new SydApiException(-1);
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
List<byte[]> list = api.SYMEncryptDecryptBatchData(8, 2, null, keys, 1, pcData);
String[] ret = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
byte[] mac = new byte[16];
byte[] buff = list.get(i);
System.arraycopy(buff, buff.length - 16, mac, 0, 16);
ret[i] = Util.bytes2HexString(buff);
}
return ret;
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
List<byte[]> list = api.SYMEncryptDecryptBatchData(8, 2, null, keys, 1, pcData);
String[] ret = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
byte[] mac = new byte[16];
byte[] buff = list.get(i);
System.arraycopy(buff, buff.length - 16, mac, 0, 16);
ret[i] = Util.bytes2HexString(buff);
}
return ret;
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public boolean[] SYD_SM4Mac_BatchData(int[] iKeyIndex, List<byte[]> pcData, String[] pcMac) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_BatchData方法接收参数:iKeyIndex:{},pcData元素个数为:{},pcMac:{}", iKeyIndex, pcData.size(), Arrays.toString(pcMac));
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String[] keys = new String[iKeyIndex.length];
updateLastUseTime();
for (int i = 0; i < iKeyIndex.length; i++) {
keys[i] = "SK" + SYMUtil.genPrivateKeyMark("000000", "00A", String.format("%08d", iKeyIndex[i]));
}
SydApiException le = new SydApiException(-1);
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
List<byte[]> list = api.SYMEncryptDecryptBatchData(8, 2, null, keys, 1, pcData);
boolean[] ret = new boolean[list.size()];
for (int i = 0; i < list.size(); i++) {
byte[] mac = new byte[16];
byte[] buff = list.get(i);
System.arraycopy(buff, buff.length - 16, mac, 0, 16);
ret[i] = pcMac[i].equals(Util.bytes2HexString(buff));
}
return ret;
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
List<byte[]> list = api.SYMEncryptDecryptBatchData(8, 2, null, keys, 1, pcData);
boolean[] ret = new boolean[list.size()];
for (int i = 0; i < list.size(); i++) {
byte[] mac = new byte[16];
byte[] buff = list.get(i);
System.arraycopy(buff, buff.length - 16, mac, 0, 16);
ret[i] = pcMac[i].equals(Util.bytes2HexString(buff));
}
return ret;
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public LongDataReturn<String, String> SYD_SM4Mac_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, String pcProcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_LongData方法接收参数:iKeyIndex:{},pcData:{},iPkgNum:{},pcProcData:{}", iKeyIndex, Arrays.toString(pcData), iPkgNum, pcProcData);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String keyIndex = String.format("%08d", iKeyIndex);
byte[] iv = null;
// 仅一包 和 第一包 忽略 pcProcData 参数
if (Consts.PkgNumAll != iPkgNum && Consts.PkgNumHead != iPkgNum) {
iv = pcProcData.getBytes();
}
SydApiException le = new SydApiException(-1);
updateLastUseTime();
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
byte[] ret = api.SYD_SM4_LongData(
8,
2, iv,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
byte[] mac = new byte[16];
System.arraycopy(ret, ret.length - 16, mac, 0, 16);
// 仅一包 和 尾包 返回最终结果
if (Consts.PkgNumAll == iPkgNum || Consts.PkgNumTail == iPkgNum) {
return new LongDataReturn<>(null, Util.bytes2HexString(mac));
} else {
// 返回中间值
return new LongDataReturn<>(Util.bytes2HexString(mac), null);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
} else {
synchronized (api) {
try {
byte[] ret = api.SYD_SM4_LongData(
8,
2, iv,
"SK" + SYMUtil.genPrivateKeyMark("000000", "00A", keyIndex),
1,
pcData, iPkgNum);
byte[] mac = new byte[16];
System.arraycopy(ret, ret.length - 16, mac, 0, 16);
// 仅一包 和 尾包 返回最终结果
if (Consts.PkgNumAll == iPkgNum || Consts.PkgNumTail == iPkgNum) {
return new LongDataReturn<>(null, Util.bytes2HexString(mac));
} else {
// 返回中间值
return new LongDataReturn<>(Util.bytes2HexString(mac), null);
}
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public LongDataReturn<String, Boolean> SYD_SM4Mac_LongData(int iKeyIndex, byte[] pcData, int iPkgNum, String pcProcData, String pcMac) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_LongData方法接收参数:iKeyIndex:{},pcData:{},iPkgNum:{},pcProcData:{}", iKeyIndex, Arrays.toString(pcData), iPkgNum, pcProcData, pcMac);
}
updateLastUseTime();
LongDataReturn<String, String> ret = SYD_SM4Mac_LongData(iKeyIndex, pcData, iPkgNum, pcProcData);
// 仅一包 和 尾包 返回最终结果
if (Consts.PkgNumAll == iPkgNum || Consts.PkgNumTail == iPkgNum) {
return new LongDataReturn<>(null, pcMac.equals(ret.getData()));
} else {
// 返回中间值
return new LongDataReturn<>(ret.getProcData(), false);
}
}
@Override
public String SYD_SM4Mac_ShortData(int iKeyIndex, byte[] pcData) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_ShortData方法接收参数:iKeyIndex:{},pcData:{},iFlag:{}", iKeyIndex, Arrays.toString(pcData));
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
String keyIndex = "SK" + SYMUtil.genPrivateKeyMark("000000", "00A", String.format("%08d", iKeyIndex));
log.debug("\"SK\" + SYMUtil.genPrivateKeyMark方法返回值:{}", keyIndex);
SydApiException le = new SydApiException(-1);
updateLastUseTime();
for (SydApi4j api : this.hsms) {
if (null == api) {
continue;
}
if (isShortLinkMode) {
try {
return api.SYD_SM4Mac_ShortData(keyIndex, pcData);
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
else {
synchronized (api){
try {
return api.SYD_SM4Mac_ShortData(keyIndex, pcData);
} catch (SydApiException e) {
le = e;
if (e.getRetCode() < 0) {
log.error("HA 重试");
continue;
}
throw e;
}
}
}
}
throw le;
}
@Override
public boolean SYD_SM4Mac_ShortData(int iKeyIndex, byte[] pcData, String pcMac) {
Logger log = LogFactory.getLogger();
if (LogFactory.iLogLevel == 3) {
log.debug("SYD_SM4Mac_ShortData方法接收参数:{}", iKeyIndex, Arrays.toString(pcData), pcMac);
}
if (null == this.hsms || this.hsms.length < 1) {
throw new SydApiException(-1);
}
if (null == pcMac) {
throw new IllegalArgumentException();
}
updateLastUseTime();
String mac = this.SYD_SM4Mac_ShortData(iKeyIndex, pcData);
log.debug(this + ".SYD_SM4Mac_ShortData方法返回值:{}", mac);
return pcMac.equals(mac);
}
@Override
public SydApiSM4 initSM4(int iKeyIndex, int ende) {
return new SydApiSM4(this,iKeyIndex,ende);
}
public SydApiSM3 initSM3() {
return new SydApiSM3(this);
}
@Override
public SydSM4Mac initSM4Mac(int iKeyIndex) {
return new SydSM4Mac(this, iKeyIndex);
}
}
@@ -13,7 +13,7 @@ public class SydApiSM4 {
private int iFlag; private int iFlag;
private boolean is_finished = false; private boolean is_finished = false;
private byte[] dataResult = new byte[0]; private byte[] dataResult = new byte[0];
BytesQueue queue = new BytesQueue(); private BytesQueue queue = new BytesQueue();
public SydApiSM4(SydApi api, int iKeyIndex, int endeFlag) { public SydApiSM4(SydApi api, int iKeyIndex, int endeFlag) {
@@ -0,0 +1,42 @@
package com.sunyard.sge.pool;
import java.util.concurrent.*;
/**
* 负责真正的阻塞通信
*/
public class CommWorker {
// 连接池配置
private final PoolConfig poolConfig;
// 真正的通信线程
private final ExecutorService threadPool;
public CommWorker(){
this( new PoolConfig() );
}
public CommWorker(PoolConfig poolConfig) {
this.poolConfig = poolConfig;
threadPool = new ThreadPoolExecutor(
this.poolConfig.getKeepAliveNumber(),
this.poolConfig.getMaxAliveNumber(),
this.poolConfig.getMaxIdle(),
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()
);
}
/**
* 执行一个异步任务
* @param callable
* @param <T>
* @return
*/
public <T> FutureTask<T> fTask(Callable<T> callable) {
FutureTask<T> task = new FutureTask<>(callable);
threadPool.submit( task );
return task;
}
}
@@ -3,10 +3,16 @@ package com.sunyard.sge.pool;
public class PoolConfig { public class PoolConfig {
// 最大空闲时间 // 最大空闲时间
private long maxIdle = 5L * 60L ; // 5 分钟 private long maxIdle = 5L * 60 * 1000L ; // 5 分钟
// 最大无用时间 // 最大无用时间
private long maxUseless = 30L * 60L ; // 30 分钟 private long maxUseless = 30L * 60 * 1000L ; // 30 分钟
// 最小保持连接数
private int keepAliveNumber = 5;
// 最大连接数
private int maxAliveNumber = 100;
public long getMaxIdle() { public long getMaxIdle() {
return maxIdle; return maxIdle;
@@ -23,4 +29,20 @@ public class PoolConfig {
public void setMaxUseless(long maxUseless) { public void setMaxUseless(long maxUseless) {
this.maxUseless = maxUseless; this.maxUseless = maxUseless;
} }
public int getKeepAliveNumber() {
return keepAliveNumber;
}
public void setKeepAliveNumber(int keepAliveNumber) {
this.keepAliveNumber = keepAliveNumber;
}
public int getMaxAliveNumber() {
return maxAliveNumber;
}
public void setMaxAliveNumber(int maxAliveNumber) {
this.maxAliveNumber = maxAliveNumber;
}
} }
@@ -1,19 +1,15 @@
package com.sunyard.sge.pool; package com.sunyard.sge.pool;
import com.sunyard.sge.database.SydApi; import com.sunyard.sge.database.SydApi;
import com.sunyard.sge.database.SydApi4Database;
import com.sunyard.sge.log.LogFactory; import com.sunyard.sge.log.LogFactory;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadBasedConnectPool<T> { public class ThreadBasedConnectPool<T> {
static { static {
@@ -42,8 +38,22 @@ public class ThreadBasedConnectPool<T> {
Iterator<Map.Entry<Thread, ObjectInPool<T>>> it = map.entrySet().iterator(); Iterator<Map.Entry<Thread, ObjectInPool<T>>> it = map.entrySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Map.Entry<Thread, ObjectInPool<T>> entry = it.next(); Map.Entry<Thread, ObjectInPool<T>> entry = it.next();
ObjectInPool<T> oip = entry.getValue(); ObjectInPool<T> oip = entry.getValue();
if (Thread.State.TERMINATED == entry.getKey().getState()) {
// 如果线程结束
log.debug("回收一个链接,关联线程已释放。");
it.remove();
try {
free(oip.getObject());
} catch (Exception e) {
}
continue;
}
if (System.currentTimeMillis() - oip.getLasUseAt() < config.getMaxIdle()) { if (System.currentTimeMillis() - oip.getLasUseAt() < config.getMaxIdle()) {
// 空闲时间不足,免检。 // 空闲时间不足,免检。
continue; continue;
@@ -51,7 +61,7 @@ public class ThreadBasedConnectPool<T> {
if (System.currentTimeMillis() - oip.getLasUseAt() > config.getMaxUseless()) { if (System.currentTimeMillis() - oip.getLasUseAt() > config.getMaxUseless()) {
// 长时间未使用,回收链接 // 长时间未使用,回收链接
log.debug("回收一个链接"); log.debug("回收一个链接,超时。");
it.remove(); it.remove();
@@ -67,11 +77,10 @@ public class ThreadBasedConnectPool<T> {
checkPass = check(entry.getValue().getObjectForCheck()); checkPass = check(entry.getValue().getObjectForCheck());
} catch (Exception e) { } catch (Exception e) {
checkPass = false; checkPass = false;
} } finally {
finally {
} }
if ( ! checkPass) { if (!checkPass) {
log.debug("一个链接检查未通过"); log.debug("一个链接检查未通过");
// 检查未通过 // 检查未通过
it.remove(); it.remove();
@@ -129,7 +138,7 @@ public class ThreadBasedConnectPool<T> {
map.remove(Thread.currentThread()); map.remove(Thread.currentThread());
} }
protected void afterInit(ObjectInPool oip, T value ){ protected void afterInit(ObjectInPool oip, T value) {
} }
@@ -137,7 +146,7 @@ public class ThreadBasedConnectPool<T> {
T value = initialValue(); T value = initialValue();
ObjectInPool opi = new ObjectInPool<>(value); ObjectInPool opi = new ObjectInPool<>(value);
map.put(Thread.currentThread(), opi); map.put(Thread.currentThread(), opi);
afterInit( opi , value); afterInit(opi, value);
return value; return value;
} }
} }
+4 -1
View File
@@ -11,10 +11,13 @@ public class ShortLinkSample {
SydApi.SYD_SetLogConfig("./logs/",3); SydApi.SYD_SetLogConfig("./logs/",3);
String[] pcipList = {"127.0.0.1", "192.168.0.200" }; String[] pcipList = {"127.0.0.1", "192.168.0.200" };
int[] iportList ={8080,8889}; int[] iportList = {8080,8889};
SydApi api = new SydApi4Database(); SydApi api = new SydApi4Database();
try { try {
api.SYD_Short_Connect_Ex(pcipList,iportList,10,10); api.SYD_Short_Connect_Ex(pcipList,iportList,10,10);
} finally { } finally {
if ( null != api ) { if ( null != api ) {
api.SYD_Disconnect_Ex(); api.SYD_Disconnect_Ex();
+73
View File
@@ -0,0 +1,73 @@
package test;
import com.sunyard.proto.Util;
import com.sunyard.sge.database.*;
import org.checkerframework.checker.units.qual.A;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class BatchDataTest {
private SydApi api;
@Before
public void init() {
// System.setProperty("com.sunyard.sydapi4j.debug", "true");
SydApiBuilder builder = new SydApiBuilder(
new String[]{"192.168.1.129"},
new int[]{8889},
10,
15
);
api = builder.build();
}
@After
public void end(){
if ( null != api ) {
api.SYD_Disconnect_Ex();
}
}
@Test
public void batchSM4Case1(){
// 密钥索引
int[] keyIdx = new int[]{ 0, 1, 2 , 0, 1, 2, 0, 1, 2, 0, 1, 2}; // 12 组
// 测试数据
List<byte[]> data = new ArrayList<>();
data.add( new byte[8] );
data.add( new byte[16] );
data.add( new byte[1024] );
data.add( new byte[8] );
data.add( new byte[16] );
data.add( new byte[1024] );
data.add( new byte[8] );
data.add( new byte[16] );
data.add( new byte[1024] );
data.add( new byte[8] );
data.add( new byte[16] );
data.add( new byte[1024] );
List<byte[]> encData = api.SYD_SM4_BatchData( keyIdx , data, Consts.ECB_ENC );
List<byte[]> orgData = api.SYD_SM4_BatchData( keyIdx , encData, Consts.ECB_DEC );
for ( int i = 0 ; i < data.size() ; i++ ) {
System.out.println( "HEX=" + Util.bytes2HexString( encData.get( i ) ) );
Assert.assertArrayEquals( orgData.get( i ), data.get( i ) );
}
}
}
+66
View File
@@ -0,0 +1,66 @@
package test;
import com.sunyard.sge.pool.CommWorker;
import com.sunyard.sge.pool.PoolConfig;
import org.junit.Test;
import java.util.concurrent.*;
public class FutureTaskTest {
/**
* 并发任务
*/
@Test
public void case1() throws ExecutionException, InterruptedException, TimeoutException {
PoolConfig poolConfig = new PoolConfig();
CommWorker workers = new CommWorker(poolConfig);
long startAt = System.currentTimeMillis();
try {
FutureTask<Integer> task1 = workers.fTask(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println( Thread.currentThread() + " task start");
Thread.sleep( 1000 );
System.out.println( Thread.currentThread() + " task over");
return 1;
}
});
FutureTask<Integer> task2 = workers.fTask(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println( Thread.currentThread() + " task start");
Thread.sleep( 2000 );
System.out.println( Thread.currentThread() + " task over");
return 1;
}
});
FutureTask<Integer> task3 = workers.fTask(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println( Thread.currentThread() + " task start");
Thread.sleep( 3000 );
System.out.println( Thread.currentThread() + " task over");
return 1;
}
});
task1.get( );
task2.get( );
task3.get( );
}finally {
long endAt = System.currentTimeMillis();
System.out.println("耗时 " + ( endAt - startAt ) );
}
}
}
+5 -6
View File
@@ -92,13 +92,12 @@ package test;
//} //}
import java.util.ArrayList;
import java.util.List;
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
if (16 > 1799 + 16 List<Integer> keyGroups = new ArrayList<>();
|| keyGroups.toArray( new Integer[0] );
(1799 + 16)/16<2
) {
System.out.println("1");
}
} }
} }