去除无用代码

This commit is contained in:
liulu 2024-10-31 16:59:44 +08:00
parent ac339d668e
commit 8b49400e08
16 changed files with 218 additions and 1384 deletions

View File

@ -5,7 +5,6 @@ import com.sunyard.ssp.SSPApi4jBuilder;
import com.sunyard.ssp.UnionMessage;
import com.sunyard.ssp.common.constant.SdkConstant;
import com.sunyard.ssp.common.exception.SspwebException;
import com.sunyard.ssp.config.ServerConfigure;
import com.sunyard.ssp.constv.Alg;
import com.sunyard.ssp.constv.KeyPairType;
import com.sunyard.ssp.constv.KeyType;

View File

@ -1,4 +1,4 @@
package com.sunyard.ssp.config;
package com.sunyard.ssp.modules.sdk;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;

View File

@ -2,27 +2,20 @@ package com.sunyard.ssp.modules.sysconf.paramconf.serviceimpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.sunyard.chsm.utils.JsonUtils;
import com.sunyard.ssp.common.constant.ParamConfKeyConstant;
import com.sunyard.ssp.modules.sysconf.paramconf.entity.ParamConf;
import com.sunyard.ssp.modules.sysconf.paramconf.mapper.ParamConfMapper;
import com.sunyard.ssp.modules.sysconf.paramconf.service.IParamConfService;
import com.sunyard.ssp.modules.user.entity.ScPermission;
import com.sunyard.ssp.modules.user.service.IScPermissionService;
import com.sunyard.ssp.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -47,7 +40,7 @@ import static com.sunyard.ssp.common.constant.ParamConfKeyConstant.IP_WHITELIST_
@Slf4j
@Service
@Transactional
public class ParamConfServiceImpl extends ServiceImpl<ParamConfMapper, ParamConf> implements IParamConfService, ApplicationRunner {
public class ParamConfServiceImpl extends ServiceImpl<ParamConfMapper, ParamConf> implements IParamConfService {
@Autowired
private IScPermissionService permissionService;
@ -155,7 +148,7 @@ public class ParamConfServiceImpl extends ServiceImpl<ParamConfMapper, ParamConf
* @param args
* @throws Exception
*/
@Override
// @Override
public void run(ApplicationArguments args) throws Exception {
// System.out.println("初始化系统参数-----------------");
// List<ParamConf> paramConfs = getParamConfByJsonFile();
@ -176,18 +169,18 @@ public class ParamConfServiceImpl extends ServiceImpl<ParamConfMapper, ParamConf
*
* @return
*/
private List<ParamConf> getParamConfByJsonFile() {
String jsonStr = "";
List<ParamConf> paramConfs = new ArrayList<>();
try {
File jsonFile = new File(ParamConfKeyConstant.SYS_PARAM_CONFIG_FILE_PATH);
jsonStr = JsonUtil.getJsonStrFromJsonFile(jsonFile);
paramConfs = JsonUtils.objectMapper().readValue(jsonStr, new TypeReference<List<ParamConf>>() {
});
// paramConfs = JSON.parseArray(jsonStr, ParamConf.class);
return paramConfs;
} catch (Exception ex) {
return paramConfs;
}
}
// private List<ParamConf> getParamConfByJsonFile() {
// String jsonStr = "";
// List<ParamConf> paramConfs = new ArrayList<>();
// try {
// File jsonFile = new File(ParamConfKeyConstant.SYS_PARAM_CONFIG_FILE_PATH);
// jsonStr = JsonUtil.getJsonStrFromJsonFile(jsonFile);
// paramConfs = JsonUtils.objectMapper().readValue(jsonStr, new TypeReference<List<ParamConf>>() {
// });
//// paramConfs = JSON.parseArray(jsonStr, ParamConf.class);
// return paramConfs;
// } catch (Exception ex) {
// return paramConfs;
// }
// }
}

View File

@ -1,167 +1,167 @@
package com.sunyard.ssp.server;
import com.alibaba.fastjson.JSONObject;
import com.sunyard.ssp.proto.control.Control;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.UUID;
/**
* 这个类暂时先这么记着
* [TODO] 读写分离
* [TODO] 对接配置中心热重载
*/
@Slf4j
public class Config {
public static Config global = new Config();
public System system = new System();
public static class System {
public String name;
public System() {
this.name = findName();
}
private boolean getBooleFromEnv(String name){
log.debug("尝试从环境变量载入 {}", name);
Map map = java.lang.System.getenv();
if ( map.containsKey(name) ){
String sn = (String) map.get(name);
if ( "true".equals( sn.trim().toLowerCase() ) ){
return true;
}
}
return false;
}
private String readNameFromFile(){
// 检查路径
File folder = new File("/data");
if ( !folder.exists() ){
folder.mkdirs();
}
File snFile = new File(folder, "security.name");
if ( snFile.exists() ){
try(FileReader fr = new FileReader(snFile) ; BufferedReader bfr = new BufferedReader(fr) ) {
String sn = bfr.readLine();
sn = sn.trim().toLowerCase();
if ( sn.length() >= 6 ){
saveNameToFile(sn);
return sn;
} else {
log.debug("security.name 的值不合规");
return null;
}
} catch (IOException e) {
e.printStackTrace();
log.error("写入 security.name 配置文件的时候失败了,{}", snFile.getAbsolutePath() );
return null;
}
} else {
log.error("security.name 配置文件不存在,{}", snFile.getAbsolutePath() );
return null;
}
}
private String genSn(){
return UUID.randomUUID().toString().replaceAll("-","");
}
private void saveNameToFile( String sn ){
// 检查路径
File folder = new File("/data");
if ( !folder.exists() ){
folder.mkdirs();
}
File snFile = new File(folder, "security.name");
if ( snFile.exists() ){
snFile.delete();
}
try( FileOutputStream fio = new FileOutputStream(snFile); ) {
snFile.createNewFile();
fio.write( sn.getBytes(Charset.forName("UTF-8")) );
fio.flush();
} catch (IOException e) {
e.printStackTrace();
log.error("写入 security.name 配置文件的时候失败了,{}", snFile.getAbsolutePath() );
}
log.debug("写入 security.name 配置文件完成SERVER_NAME = {}{}", sn, snFile.getAbsolutePath());
}
private String findName(){
log.debug("尝试从环境变量载入 SERVER_NAME");
Map map = java.lang.System.getenv();
if ( map.containsKey("SERVER_NAME") ){
String sn = (String) map.get("SERVER_NAME");
sn = sn.trim().toUpperCase();
if ( sn.length() >= 6 ){
//package com.sunyard.ssp.server;
//
//
//import com.alibaba.fastjson.JSONObject;
//import com.sunyard.ssp.proto.control.Control;
//import lombok.Cleanup;
//import lombok.SneakyThrows;
//import lombok.extern.slf4j.Slf4j;
//
//import java.io.BufferedReader;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
//import java.io.FileReader;
//import java.io.IOException;
//import java.nio.charset.Charset;
//import java.util.Map;
//import java.util.UUID;
//
///**
// * 这个类暂时先这么记着
// * [TODO] 读写分离
// * [TODO] 对接配置中心热重载
// */
//@Slf4j
//public class Config {
//
// public static Config global = new Config();
//
// public System system = new System();
// public static class System {
// public String name;
//
// public System() {
// this.name = findName();
// }
//
// private boolean getBooleFromEnv(String name){
// log.debug("尝试从环境变量载入 {}", name);
// Map map = java.lang.System.getenv();
// if ( map.containsKey(name) ){
// String sn = (String) map.get(name);
// if ( "true".equals( sn.trim().toLowerCase() ) ){
// return true;
// }
// }
//
// return false;
// }
//
// private String readNameFromFile(){
// // 检查路径
// File folder = new File("/data");
// if ( !folder.exists() ){
// folder.mkdirs();
// }
//
// File snFile = new File(folder, "security.name");
// if ( snFile.exists() ){
// try(FileReader fr = new FileReader(snFile) ; BufferedReader bfr = new BufferedReader(fr) ) {
//
// String sn = bfr.readLine();
// sn = sn.trim().toLowerCase();
// if ( sn.length() >= 6 ){
// saveNameToFile(sn);
return sn;
} else {
log.debug("环境变量 SERVER_NAME 的值不合规");
}
}
log.debug("尝试从 security.name 配置载入 SERVER_NAME");
String sn = readNameFromFile();
if ( null != sn){
return sn;
}
sn = genSn();
// saveNameToFile( sn );
return sn;
}
}
public Messenger messenger = new Messenger();
public static class Messenger {
//cluster solo
public JSONObject redisCluster = (JSONObject) loadFileConfig("redis.config.json");
public int maxWaitTime = 10; //
public String privateCliChannel(){
return Control.Req.Origin.CLI.name() + "_" + Config.global.system.name;
}
public String privateServerChannel(){
return Control.Req.Origin.SERVER.name() + "_" + Config.global.system.name;
}
}
@SneakyThrows
public static JSONObject loadFileConfig(String name ){
File folder = new File("./config");
File configFile = new File(folder, name);
if ( ! configFile.exists() ){
log.error("没有找到配置文件 {}", name);
}
@Cleanup FileInputStream fio = new FileInputStream(configFile);
byte[] buff = new byte[ fio.available() ];
fio.read( buff );
return (JSONObject) JSONObject.parse( new String(buff) );
}
}
// return sn;
// } else {
// log.debug("security.name 的值不合规");
// return null;
// }
//
// } catch (IOException e) {
// e.printStackTrace();
// log.error("写入 security.name 配置文件的时候失败了,{}", snFile.getAbsolutePath() );
// return null;
// }
// } else {
// log.error("security.name 配置文件不存在,{}", snFile.getAbsolutePath() );
// return null;
// }
// }
//
// private String genSn(){
// return UUID.randomUUID().toString().replaceAll("-","");
// }
//
// private void saveNameToFile( String sn ){
// // 检查路径
// File folder = new File("/data");
// if ( !folder.exists() ){
// folder.mkdirs();
// }
//
// File snFile = new File(folder, "security.name");
// if ( snFile.exists() ){
// snFile.delete();
// }
//
// try( FileOutputStream fio = new FileOutputStream(snFile); ) {
//
// snFile.createNewFile();
//
// fio.write( sn.getBytes(Charset.forName("UTF-8")) );
// fio.flush();
//
// } catch (IOException e) {
// e.printStackTrace();
// log.error("写入 security.name 配置文件的时候失败了,{}", snFile.getAbsolutePath() );
// }
//
// log.debug("写入 security.name 配置文件完成SERVER_NAME = {}{}", sn, snFile.getAbsolutePath());
// }
//
// private String findName(){
// log.debug("尝试从环境变量载入 SERVER_NAME");
// Map map = java.lang.System.getenv();
// if ( map.containsKey("SERVER_NAME") ){
// String sn = (String) map.get("SERVER_NAME");
// sn = sn.trim().toUpperCase();
// if ( sn.length() >= 6 ){
// //saveNameToFile(sn);
// return sn;
// } else {
// log.debug("环境变量 SERVER_NAME 的值不合规");
// }
// }
//
// log.debug("尝试从 security.name 配置载入 SERVER_NAME");
// String sn = readNameFromFile();
// if ( null != sn){
// return sn;
// }
//
// sn = genSn();
//// saveNameToFile( sn );
// return sn;
// }
// }
//
// public Messenger messenger = new Messenger();
// public static class Messenger {
// //cluster solo
// public JSONObject redisCluster = (JSONObject) loadFileConfig("redis.config.json");
// public int maxWaitTime = 10; //
//
// public String privateCliChannel(){
// return Control.Req.Origin.CLI.name() + "_" + Config.global.system.name;
// }
// public String privateServerChannel(){
// return Control.Req.Origin.SERVER.name() + "_" + Config.global.system.name;
// }
//
// }
//
// @SneakyThrows
// public static JSONObject loadFileConfig(String name ){
// File folder = new File("./config");
// File configFile = new File(folder, name);
// if ( ! configFile.exists() ){
// log.error("没有找到配置文件 {}", name);
// }
// @Cleanup FileInputStream fio = new FileInputStream(configFile);
// byte[] buff = new byte[ fio.available() ];
// fio.read( buff );
// return (JSONObject) JSONObject.parse( new String(buff) );
// }
//}

View File

@ -1,18 +1,18 @@
package com.sunyard.ssp.server;
import lombok.Data;
/**
* @author:tsz
* @date:2020/3/25
* @description:
*/
@Data
public class VOChannel {
private String type;
private String msg;
//private List<Control.VOChannelCheckRes> list;
}
//package com.sunyard.ssp.server;
//import lombok.Data;
//
///**
// * @author:tsz
// * @date:2020/3/25
// * @description:
// */
//@Data
//public class VOChannel {
//
// private String type;
//
// private String msg;
//
// //private List<Control.VOChannelCheckRes> list;
//
//}

View File

@ -1,372 +0,0 @@
package com.sunyard.ssp.utils;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.X509KeyUsage;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.util.encoders.Base64;
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import java.util.Set;
/**
* @author:tsz
* @date:2020/4/27
* @description:
*/
@Slf4j
public class CaUtil {
static {
Security.addProvider(new BouncyCastleProvider());
BouncyCastleProvider bc = new BouncyCastleProvider();
Set<Provider.Service> services = bc.getServices();
for (Provider.Service s:services){
if (s.toString().toUpperCase().contains("CIPHER")) log.info(s.toString());
}
}
public static void main(String[] args) throws Exception {
genGMCACert();
//genCertWithCaSign();
// testDigitalSign();
//testSM2EcDc();
//testSaveGMKeyStore();
}
public static void genGMCACert() throws Exception {
log.info("=============测试生成国密CA根证书=============");
KeyPairGenerator g = KeyPairGenerator.getInstance("EC", "BC");
g.initialize(new ECNamedCurveGenParameterSpec("sm2p256v1"));
KeyPair p = g.generateKeyPair();
PrivateKey privKey = p.getPrivate();
PublicKey pubKey = p.getPublic();
log.info("CA PrivateKey:" + Base64.toBase64String(privKey.getEncoded()));
X500Principal iss = new X500Principal("CN=test GM ROOT CA,OU=test,C=CN,S=Guangdong,O=test");
ContentSigner sigGen = new JcaContentSignerBuilder("SM3withSM2").setProvider("BC").build(privKey);
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
iss,
BigInteger.valueOf(1),
new Date(System.currentTimeMillis() - 50000),
new Date(System.currentTimeMillis() + 50000),
iss,
pubKey).addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true,
new X509KeyUsage(0xfe))
.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true,
new DERSequence(KeyPurposeId.anyExtendedKeyUsage))
.addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true,
new GeneralNames(new GeneralName[]
{
new GeneralName(GeneralName.rfc822Name, "gmca@test.cn"),
new GeneralName(GeneralName.dNSName, "ca.test.cn")
}));
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());
cert.verify(pubKey);
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate) fact.generateCertificate(bIn);
log.info("CA Cert:" + Base64.toBase64String(cert.getEncoded()));
saveFile("CAPrikey", privKey.getEncoded());
saveFile("CARootCert.cer", cert.getEncoded());
log.info("=============测试生成国密CA根证书=============");
}
public static void genCertWithCaSign() throws Exception {
log.info("=============测试国密CA根证书签发国密证书=============");
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(readFile("CAPrikey"));
PrivateKey caPrivateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X509", "BC");
Certificate caRootCert = certificateFactory.generateCertificate(new FileInputStream("CARootCert.cer"));
KeyPairGenerator g = KeyPairGenerator.getInstance("EC", "BC");
g.initialize(new ECNamedCurveGenParameterSpec("sm2p256v1"));
KeyPair p = g.generateKeyPair();
PrivateKey privKey = p.getPrivate();
PublicKey pubKey = p.getPublic();
ContentSigner sigGen = new JcaContentSignerBuilder("SM3withSM2").setProvider("BC").build(caPrivateKey);
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
(X509Certificate) caRootCert,
BigInteger.valueOf(new Random().nextInt()),
new Date(System.currentTimeMillis() - 50000),
new Date(System.currentTimeMillis() + 50000),
new X500Principal("CN=TestCert"),
pubKey).addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true,
new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation))
.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true,
new DERSequence(KeyPurposeId.anyExtendedKeyUsage))
.addExtension(new ASN1ObjectIdentifier("2.5.29.17"), true,
new GeneralNames(new GeneralName[]
{
new GeneralName(GeneralName.rfc822Name, "gmca@test.cn"),
new GeneralName(GeneralName.dNSName, "ca.test.cn")
}));
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());
cert.verify(caRootCert.getPublicKey());
ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
cert = (X509Certificate) fact.generateCertificate(bIn);
log.info("custCert:" + Base64.toBase64String(cert.getEncoded()));
log.info("custPrivateKey:" + Base64.toBase64String(privKey.getEncoded()));
saveFile("custCert.cer", cert.getEncoded());
saveFile("custPrivateKey", privKey.getEncoded());
log.info("=============测试国密CA根证书签发国密证书=============");
}
public static void testDigitalSign() throws Exception {
log.info("=============测试国密证书数字签名=============");
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(readFile("custPrivateKey"));
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X509", "BC");
Certificate certificate = certificateFactory.generateCertificate(new FileInputStream("custCert.cer"));
Signature signature = Signature.getInstance("SM3withSM2", "BC");
signature.initSign(privateKey);
String signText = "测试123456test";
signature.update(signText.getBytes("UTF-8"));
byte[] digitalsignature = signature.sign();
log.info("signText:" + signText);
log.info("digitalsignature:" + Base64.toBase64String(digitalsignature));
Signature signature1 = Signature.getInstance("SM3withSM2", "BC");
signature1.initVerify(certificate.getPublicKey());
signature1.update(signText.getBytes("UTF-8"));
boolean result = signature1.verify(digitalsignature);
log.info("verifyResult:" + result);
Signature signature2 = Signature.getInstance("SM3withSM2", "BC");
signature2.initVerify(certificate.getPublicKey());
signature2.update((signText + "exception").getBytes("UTF-8"));
boolean exceptionResult = signature2.verify(digitalsignature);
log.info("exceptionVerifyResult:" + exceptionResult);
log.info("=============测试国密证书数字签名=============");
}
public static void testSM2EcDc() throws Exception {
log.info("=============测试国密SM2加解密=============");
//从证书获取公钥
CertificateFactory certificateFactory = CertificateFactory.getInstance("X509", "BC");
Certificate certificate = certificateFactory.generateCertificate(new FileInputStream("custCert.cer"));
PublicKey publicKey = certificate.getPublicKey();
//获取加密参数
BCECPublicKey localECPublicKey = (BCECPublicKey)publicKey;
ECParameterSpec localECParameterSpec = localECPublicKey.getParameters();
ECDomainParameters localECDomainParameters = new ECDomainParameters(
localECParameterSpec.getCurve(), localECParameterSpec.getG(),
localECParameterSpec.getN());
ECPublicKeyParameters localECPublicKeyParameters = new ECPublicKeyParameters(localECPublicKey.getQ(),
localECDomainParameters);
//待加密数据
byte[] ebs = "123sssss测试".getBytes("UTF-8");
log.info("原文:"+new String(ebs));
//初始化加密引擎
SM2Engine sm2EncEngine = new SM2Engine();
sm2EncEngine.init(true, new ParametersWithRandom(localECPublicKeyParameters));
//加密
byte[] bs = sm2EncEngine.processBlock(ebs,0,ebs.length);
String es = Base64.toBase64String(bs);
log.info("密文:"+es);
//获取私钥
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(readFile("custPrivateKey"));
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//获取解密参数
BCECPrivateKey sm2PriK = (BCECPrivateKey)privateKey;
ECParameterSpec ecParameterSpec = sm2PriK.getParameters();
ECDomainParameters ecDomainParameters = new ECDomainParameters(
ecParameterSpec.getCurve(), ecParameterSpec.getG(),
ecParameterSpec.getN());
ECPrivateKeyParameters localECPrivateKeyParameters = new ECPrivateKeyParameters(
sm2PriK.getD(), ecDomainParameters);
//初始化解密引擎
SM2Engine sm2DcEngine = new SM2Engine();
sm2EncEngine.init(true, new ParametersWithRandom(localECPublicKeyParameters));
sm2DcEngine.init(false, localECPrivateKeyParameters);
bs = Base64.decode(es.getBytes("Utf-8"));
byte[] b = sm2DcEngine.processBlock(bs,0,bs.length);
log.info("明文:"+new String(b));
log.info("=============测试国密SM2加解密=============");
}
public static void testSaveGMKeyStore() throws Exception {
log.info("=============测试国密证书PKCS12 KeyStore存取=============");
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(readFile("custPrivateKey"));
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X509", "BC");
Certificate certificate = certificateFactory.generateCertificate(new FileInputStream("custCert.cer"));
KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
keyStore.load(null, null);
keyStore.setKeyEntry("test", privateKey, "32145698745632145698745632145698".toCharArray(), new Certificate[]{certificate});
keyStore.store(new FileOutputStream("cust.pfx"), "32145698745632145698745632145698".toCharArray());
KeyStore keyStore1 = KeyStore.getInstance("PKCS12", "BC");
keyStore1.load(new FileInputStream("cust.pfx"), "32145698745632145698745632145698".toCharArray());
Certificate certificate1 = keyStore1.getCertificate("test");
PrivateKey privateKey1 = (PrivateKey) keyStore1.getKey("test", "32145698745632145698745632145698".toCharArray());
log.info("公钥证书存取前后对比:" + Arrays.equals(certificate1.getEncoded(), certificate.getEncoded()));
log.info("私钥存取前后对比:" + Arrays.equals(privateKey.getEncoded(), privateKey1.getEncoded()));
log.info("=============测试国密证书PKCS12 KeyStore存取=============");
}
public static void saveFile(String path, byte[] data) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(path);
fileOutputStream.write(data);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] readFile(String path) throws Exception {
FileInputStream fileInputStream = new FileInputStream(path);
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
return bytes;
}
public static byte[] getPriKeyByteFromP8(byte[] p8byte) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(p8byte);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
ASN1InputStream asn1InputStream = new ASN1InputStream(privateKey.getEncoded());
ASN1Sequence p8 = (ASN1Sequence) asn1InputStream.readObject();
ASN1InputStream asn1InputStream1 = new ASN1InputStream(((DEROctetString) p8.getObjectAt(2)).getOctets());
ASN1Sequence gmPrivateKey = (ASN1Sequence)asn1InputStream1.readObject();
byte[] gmPriKeyBytes = ((DEROctetString)gmPrivateKey.getObjectAt(1)).getOctets();
return gmPriKeyBytes;
}
}

View File

@ -1,144 +0,0 @@
package com.sunyard.ssp.utils;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 获取包下所有的类名
*/
public class ClazzUtils {
/**
* 获取某包下所有类
* @param packageName 包名
* @param isRecursion 是否遍历子包
* @return 类的完整名称
*/
public static Set<String> getClassName(String packageName, boolean isRecursion) {
Set<String> classNames = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagePath = packageName.replace(".", "/");
URL url = loader.getResource(packagePath);
if (url != null) {
String protocol = url.getProtocol();
if (protocol.equals("file")) {
classNames = getClassNameFromDir(url.getPath(), packageName, isRecursion);
} else if (protocol.equals("jar")) {
JarFile jarFile = null;
try {
jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
} catch (Exception e) {
e.printStackTrace();
}
if (jarFile != null) {
getClassNameFromJar(jarFile.entries(), packageName, isRecursion);
}
}
} else {
/*从所有的jar包中查找包名*/
classNames = getClassNameFromJars(((URLClassLoader) loader).getURLs(), packageName, isRecursion);
}
return classNames;
}
/**
* 从项目文件获取某包下所有类
* @param filePath 文件路径
* @param packageName 类名集合
* @param isRecursion 是否遍历子包
* @return 类的完整名称
*/
private static Set<String> getClassNameFromDir(String filePath, String packageName, boolean isRecursion) {
Set<String> className = new HashSet<String>();
File file = new File(filePath);
File[] files = file.listFiles();
for (File childFile : files) {
if (childFile.isDirectory()) {
if (isRecursion) {
className.addAll(getClassNameFromDir(childFile.getPath(), packageName + "." + childFile.getName(), isRecursion));
}
} else {
String fileName = childFile.getName();
if (fileName.endsWith(".class") && !fileName.contains("$")) {
className.add(packageName + "." + fileName.replace(".class", ""));
}
}
}
return className;
}
/**
* @param jarEntries
* @param packageName
* @param isRecursion
* @return
*/
private static Set<String> getClassNameFromJar(Enumeration<JarEntry> jarEntries, String packageName, boolean isRecursion) {
Set<String> classNames = new HashSet<String>();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
if (!jarEntry.isDirectory()) {
// 这里是为了方便先把"/" 转成 "." 再判断 ".class" 的做法可能会有bug
String entryName = jarEntry.getName().replace("/", ".");
if (entryName.endsWith(".class") && !entryName.contains("$") && entryName.startsWith(packageName)) {
entryName = entryName.replace(".class", "");
if (isRecursion) {
classNames.add(entryName);
} else if (!entryName.replace(packageName + ".", "").contains(".")) {
classNames.add(entryName);
}
}
}
}
return classNames;
}
/**
* 从所有jar中搜索该包并获取该包下所有类
* @param urls URL集合
* @param packageName 包路径
* @param isRecursion 是否遍历子包
* @return 类的完整名称
*/
private static Set<String> getClassNameFromJars(URL[] urls, String packageName, boolean isRecursion) {
Set<String> classNames = new HashSet<String>();
for (int i = 0; i < urls.length; i++) {
String classPath = urls[i].getPath();
//不必搜索classes文件夹
if (classPath.endsWith("classes/")) {
continue;
}
JarFile jarFile = null;
try {
jarFile = new JarFile(classPath.substring(classPath.indexOf("/")));
} catch (IOException e) {
e.printStackTrace();
}
if (jarFile != null) {
classNames.addAll(getClassNameFromJar(jarFile.entries(), packageName, isRecursion));
}
}
return classNames;
}
}

View File

@ -1,33 +0,0 @@
package com.sunyard.ssp.utils;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FileUtils {
public static void writeFile(String filePath, byte[] data) throws IOException {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filePath, "rw");
raf.write(data);
} finally {
if (raf != null) {
raf.close();
}
}
}
public static byte[] readFile(String filePath) throws IOException {
RandomAccessFile raf = null;
byte[] data;
try {
raf = new RandomAccessFile(filePath, "r");
data = new byte[(int) raf.length()];
raf.read(data);
return data;
} finally {
if (raf != null) {
raf.close();
}
}
}
}

View File

@ -1,27 +0,0 @@
package com.sunyard.ssp.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* @author fyc
* @date 2020-6-3
*/
public class JsonUtil {
public static String getJsonStrFromJsonFile(File jsonFile) throws Exception {
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
return sb.toString();
}
}

View File

@ -1,20 +0,0 @@
package com.sunyard.ssp.utils;
import com.sunyard.ssp.vo.KeyVo;
/**
* @date:2020/6/10
* @description:
*/
public class KeyUtil {
public static KeyVo parseKeyName(String keyName){
String[] split = keyName.split("\\.");
KeyVo keyVo = new KeyVo();
keyVo.setSolutionNumber(split[0]);
keyVo.setNodeNumber(split[1]);
keyVo.setTmplNumber(split[2]);
keyVo.setKeyNumber(split[3]);
return keyVo;
}
}

View File

@ -1,11 +0,0 @@
package com.sunyard.ssp.utils;
/**
* @author:tsz
* @date:2020/4/28
* @description:
*/
public class ProtobufUtil {
}

View File

@ -1,17 +0,0 @@
package com.sunyard.ssp.utils;
import java.util.UUID;
/**
* 处理UUID
*/
public class UuidUtil {
/**
* 生成一个UUID
* @return
*/
public static String generate(){
return UUID.randomUUID().toString().replace("-", "");
}
}

View File

@ -1,500 +0,0 @@
package com.sunyard.ssp.utils.sm2;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X962Parameters;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9ECPoint;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECKeyParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util;
import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.util.io.pem.PemWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* 这个工具类的方法也适用于其他基于BC库的ECC算法
*/
public class BCECUtil {
private static final String ALGO_NAME_EC = "EC";
private static final String PEM_STRING_PUBLIC = "PUBLIC KEY";
private static final String PEM_STRING_ECPRIVATEKEY = "EC PRIVATE KEY";
/**
* 生成ECC密钥对
*
* @return ECC密钥对
*/
public static AsymmetricCipherKeyPair generateKeyPairParameter(
ECDomainParameters domainParameters, SecureRandom random) {
ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(domainParameters,
random);
ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
keyGen.init(keyGenerationParams);
return keyGen.generateKeyPair();
}
public static KeyPair generateKeyPair(ECDomainParameters domainParameters, SecureRandom random)
throws NoSuchProviderException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
ECParameterSpec parameterSpec = new ECParameterSpec(domainParameters.getCurve(), domainParameters.getG(),
domainParameters.getN(), domainParameters.getH());
kpg.initialize(parameterSpec, random);
return kpg.generateKeyPair();
}
public static int getCurveLength(ECKeyParameters ecKey) {
return getCurveLength(ecKey.getParameters());
}
public static int getCurveLength(ECDomainParameters domainParams) {
return (domainParams.getCurve().getFieldSize() + 7) / 8;
}
public static byte[] fixToCurveLengthBytes(int curveLength, byte[] src) {
if (src.length == curveLength) {
return src;
}
byte[] result = new byte[curveLength];
if (src.length > curveLength) {
System.arraycopy(src, src.length - result.length, result, 0, result.length);
} else {
System.arraycopy(src, 0, result, result.length - src.length, src.length);
}
return result;
}
/**
* @param dHex 十六进制字符串形式的私钥d值如果是SM2算法Hex字符串长度应该是64即32字节
* @param domainParameters EC Domain参数一般是固定的如果是SM2算法的可参考{@link SM2Util#DOMAIN_PARAMS}
* @return
*/
public static ECPrivateKeyParameters createECPrivateKeyParameters(
String dHex, ECDomainParameters domainParameters) {
return createECPrivateKeyParameters(ByteUtils.fromHexString(dHex), domainParameters);
}
/**
* @param dBytes 字节数组形式的私钥d值如果是SM2算法应该是32字节
* @param domainParameters EC Domain参数一般是固定的如果是SM2算法的可参考{@link SM2Util#DOMAIN_PARAMS}
* @return
*/
public static ECPrivateKeyParameters createECPrivateKeyParameters(
byte[] dBytes, ECDomainParameters domainParameters) {
return createECPrivateKeyParameters(new BigInteger(1, dBytes), domainParameters);
}
/**
* @param d 大数形式的私钥d值
* @param domainParameters EC Domain参数一般是固定的如果是SM2算法的可参考{@link SM2Util#DOMAIN_PARAMS}
* @return
*/
public static ECPrivateKeyParameters createECPrivateKeyParameters(
BigInteger d, ECDomainParameters domainParameters) {
return new ECPrivateKeyParameters(d, domainParameters);
}
/**
* @param x 大数形式的公钥x分量
* @param y 大数形式的公钥y分量
* @param curve EC曲线参数一般是固定的如果是SM2算法的可参考{@link SM2Util#CURVE}
* @param domainParameters EC Domain参数一般是固定的如果是SM2算法的可参考{@link SM2Util#DOMAIN_PARAMS}
* @return
*/
public static ECPublicKeyParameters createECPublicKeyParameters(
BigInteger x, BigInteger y, ECCurve curve, ECDomainParameters domainParameters) {
return createECPublicKeyParameters(x.toByteArray(), y.toByteArray(), curve, domainParameters);
}
/**
* @param xHex 十六进制形式的公钥x分量如果是SM2算法Hex字符串长度应该是64即32字节
* @param yHex 十六进制形式的公钥y分量如果是SM2算法Hex字符串长度应该是64即32字节
* @param curve EC曲线参数一般是固定的如果是SM2算法的可参考{@link SM2Util#CURVE}
* @param domainParameters EC Domain参数一般是固定的如果是SM2算法的可参考{@link SM2Util#DOMAIN_PARAMS}
* @return
*/
public static ECPublicKeyParameters createECPublicKeyParameters(
String xHex, String yHex, ECCurve curve, ECDomainParameters domainParameters) {
return createECPublicKeyParameters(ByteUtils.fromHexString(xHex), ByteUtils.fromHexString(yHex),
curve, domainParameters);
}
/**
* @param xBytes 十六进制形式的公钥x分量如果是SM2算法应该是32字节
* @param yBytes 十六进制形式的公钥y分量如果是SM2算法应该是32字节
* @param curve EC曲线参数一般是固定的如果是SM2算法的可参考{@link SM2Util#CURVE}
* @param domainParameters EC Domain参数一般是固定的如果是SM2算法的可参考{@link SM2Util#DOMAIN_PARAMS}
* @return
*/
public static ECPublicKeyParameters createECPublicKeyParameters(
byte[] xBytes, byte[] yBytes, ECCurve curve, ECDomainParameters domainParameters) {
final byte uncompressedFlag = 0x04;
int curveLength = getCurveLength(domainParameters);
xBytes = fixToCurveLengthBytes(curveLength, xBytes);
yBytes = fixToCurveLengthBytes(curveLength, yBytes);
byte[] encodedPubKey = new byte[1 + xBytes.length + yBytes.length];
encodedPubKey[0] = uncompressedFlag;
System.arraycopy(xBytes, 0, encodedPubKey, 1, xBytes.length);
System.arraycopy(yBytes, 0, encodedPubKey, 1 + xBytes.length, yBytes.length);
return new ECPublicKeyParameters(curve.decodePoint(encodedPubKey), domainParameters);
}
public static ECPrivateKeyParameters convertPrivateKeyToParameters(BCECPrivateKey ecPriKey) {
ECParameterSpec parameterSpec = ecPriKey.getParameters();
ECDomainParameters domainParameters = new ECDomainParameters(parameterSpec.getCurve(), parameterSpec.getG(),
parameterSpec.getN(), parameterSpec.getH());
return new ECPrivateKeyParameters(ecPriKey.getD(), domainParameters);
}
public static ECPublicKeyParameters convertPublicKeyToParameters(BCECPublicKey ecPubKey) {
ECParameterSpec parameterSpec = ecPubKey.getParameters();
ECDomainParameters domainParameters = new ECDomainParameters(parameterSpec.getCurve(), parameterSpec.getG(),
parameterSpec.getN(), parameterSpec.getH());
return new ECPublicKeyParameters(ecPubKey.getQ(), domainParameters);
}
public static BCECPublicKey createPublicKeyFromSubjectPublicKeyInfo(SubjectPublicKeyInfo subPubInfo)
throws NoSuchProviderException,
NoSuchAlgorithmException, InvalidKeySpecException, IOException {
return BCECUtil.convertX509ToECPublicKey(subPubInfo.toASN1Primitive().getEncoded(ASN1Encoding.DER));
}
/**
* 将ECC私钥转换为PKCS8标准的字节流
*
* @param priKey
* @param pubKey 可以为空但是如果为空的话得到的结果OpenSSL可能解析不了
* @return
*/
public static byte[] convertECPrivateKeyToPKCS8(
ECPrivateKeyParameters priKey, ECPublicKeyParameters pubKey) {
ECDomainParameters domainParams = priKey.getParameters();
ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(),
domainParams.getN(), domainParams.getH());
BCECPublicKey publicKey = null;
if (pubKey != null) {
publicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec,
BouncyCastleProvider.CONFIGURATION);
}
BCECPrivateKey privateKey = new BCECPrivateKey(ALGO_NAME_EC, priKey, publicKey,
spec, BouncyCastleProvider.CONFIGURATION);
return privateKey.getEncoded();
}
/**
* 将PKCS8标准的私钥字节流转换为私钥对象
*
* @param pkcs8Key
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
*/
public static BCECPrivateKey convertPKCS8ToECPrivateKey(byte[] pkcs8Key)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec(pkcs8Key);
KeyFactory kf = KeyFactory.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
return (BCECPrivateKey) kf.generatePrivate(peks);
}
/**
* 将PKCS8标准的私钥字节流转换为PEM
*
* @param encodedKey
* @return
* @throws IOException
*/
public static String convertECPrivateKeyPKCS8ToPEM(byte[] encodedKey) throws IOException {
return convertEncodedDataToPEM(PEM_STRING_ECPRIVATEKEY, encodedKey);
}
/**
* 将PEM格式的私钥转换为PKCS8标准字节流
*
* @param pemString
* @return
* @throws IOException
*/
public static byte[] convertECPrivateKeyPEMToPKCS8(String pemString) throws IOException {
return convertPEMToEncodedData(pemString);
}
/**
* 将ECC私钥转换为SEC1标准的字节流
* openssl d2i_ECPrivateKey函数要求的DER编码的私钥也是SEC1标准的
* 这个工具函数的主要目的就是为了能生成一个openssl可以直接识别的ECC私钥.
* 相对RSA私钥的PKCS1标准ECC私钥的标准为SEC1
*
* @param priKey
* @param pubKey
* @return
* @throws IOException
*/
public static byte[] convertECPrivateKeyToSEC1(
ECPrivateKeyParameters priKey, ECPublicKeyParameters pubKey) throws IOException {
byte[] pkcs8Bytes = convertECPrivateKeyToPKCS8(priKey, pubKey);
PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes);
ASN1Encodable encodable = pki.parsePrivateKey();
ASN1Primitive primitive = encodable.toASN1Primitive();
byte[] sec1Bytes = primitive.getEncoded();
return sec1Bytes;
}
/**
* 将SEC1标准的私钥字节流恢复为PKCS8标准的字节流
*
* @param sec1Key
* @return
* @throws IOException
*/
public static byte[] convertECPrivateKeySEC1ToPKCS8(byte[] sec1Key) throws IOException {
/**
* 参考org.bouncycastle.asn1.pkcs.PrivateKeyInfo和
* org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey逆向拼装
*/
X962Parameters params = getDomainParametersFromName(SM2Util.JDK_EC_SPEC, false);
ASN1OctetString privKey = new DEROctetString(sec1Key);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(0)); //版本号
v.add(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params)); //算法标识
v.add(privKey);
DERSequence ds = new DERSequence(v);
return ds.getEncoded(ASN1Encoding.DER);
}
/**
* 将SEC1标准的私钥字节流转为BCECPrivateKey对象
*
* @param sec1Key
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
* @throws IOException
*/
public static BCECPrivateKey convertSEC1ToBCECPrivateKey(byte[] sec1Key)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException {
PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec(convertECPrivateKeySEC1ToPKCS8(sec1Key));
KeyFactory kf = KeyFactory.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
return (BCECPrivateKey) kf.generatePrivate(peks);
}
/**
* 将SEC1标准的私钥字节流转为ECPrivateKeyParameters对象
* openssl i2d_ECPrivateKey函数生成的DER编码的ecc私钥是SEC1标准的带有EC_GROUP带有公钥的
* 这个工具函数的主要目的就是为了使Java程序能够识别openssl生成的ECC私钥
*
* @param sec1Key
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
*/
public static ECPrivateKeyParameters convertSEC1ToECPrivateKey(byte[] sec1Key)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, IOException {
BCECPrivateKey privateKey = convertSEC1ToBCECPrivateKey(sec1Key);
return convertPrivateKeyToParameters(privateKey);
}
/**
* 将ECC公钥对象转换为X509标准的字节流
*
* @param pubKey
* @return
*/
public static byte[] convertECPublicKeyToX509(ECPublicKeyParameters pubKey) {
ECDomainParameters domainParams = pubKey.getParameters();
ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(),
domainParams.getN(), domainParams.getH());
BCECPublicKey publicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec,
BouncyCastleProvider.CONFIGURATION);
return publicKey.getEncoded();
}
/**
* 将X509标准的公钥字节流转为公钥对象
*
* @param x509Bytes
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static BCECPublicKey convertX509ToECPublicKey(byte[] x509Bytes) throws NoSuchProviderException,
NoSuchAlgorithmException, InvalidKeySpecException {
X509EncodedKeySpec eks = new X509EncodedKeySpec(x509Bytes);
KeyFactory kf = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
return (BCECPublicKey) kf.generatePublic(eks);
}
/**
* 将X509标准的公钥字节流转为PEM
*
* @param encodedKey
* @return
* @throws IOException
*/
public static String convertECPublicKeyX509ToPEM(byte[] encodedKey) throws IOException {
return convertEncodedDataToPEM(PEM_STRING_PUBLIC, encodedKey);
}
/**
* 将PEM格式的公钥转为X509标准的字节流
*
* @param pemString
* @return
* @throws IOException
*/
public static byte[] convertECPublicKeyPEMToX509(String pemString) throws IOException {
return convertPEMToEncodedData(pemString);
}
/**
* copy from BC
*
* @param genSpec
* @return
*/
public static X9ECParameters getDomainParametersFromGenSpec(ECGenParameterSpec genSpec) {
return getDomainParametersFromName(genSpec.getName());
}
/**
* copy from BC
*
* @param curveName
* @return
*/
public static X9ECParameters getDomainParametersFromName(String curveName) {
X9ECParameters domainParameters;
try {
if (curveName.charAt(0) >= '0' && curveName.charAt(0) <= '2') {
ASN1ObjectIdentifier oidID = new ASN1ObjectIdentifier(curveName);
domainParameters = ECUtil.getNamedCurveByOid(oidID);
} else {
if (curveName.indexOf(' ') > 0) {
curveName = curveName.substring(curveName.indexOf(' ') + 1);
domainParameters = ECUtil.getNamedCurveByName(curveName);
} else {
domainParameters = ECUtil.getNamedCurveByName(curveName);
}
}
} catch (IllegalArgumentException ex) {
domainParameters = ECUtil.getNamedCurveByName(curveName);
}
return domainParameters;
}
/**
* copy from BC
*
* @param ecSpec
* @param withCompression
* @return
*/
public static X962Parameters getDomainParametersFromName(
java.security.spec.ECParameterSpec ecSpec, boolean withCompression) {
X962Parameters params;
if (ecSpec instanceof ECNamedCurveSpec) {
ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveSpec) ecSpec).getName());
if (curveOid == null) {
curveOid = new ASN1ObjectIdentifier(((ECNamedCurveSpec) ecSpec).getName());
}
params = new X962Parameters(curveOid);
} else if (ecSpec == null) {
params = new X962Parameters(DERNull.INSTANCE);
} else {
ECCurve curve = EC5Util.convertCurve(ecSpec.getCurve());
X9ECParameters ecP = new X9ECParameters(
curve,
new X9ECPoint(EC5Util.convertPoint(curve, ecSpec.getGenerator()), withCompression),
ecSpec.getOrder(),
BigInteger.valueOf(ecSpec.getCofactor()),
ecSpec.getCurve().getSeed());
//// 如果是1.62或更低版本的bcprov-jdk15on应该使用以下这段代码因为高版本的EC5Util.convertPoint没有向下兼容
/*
X9ECParameters ecP = new X9ECParameters(
curve,
EC5Util.convertPoint(curve, ecSpec.getGenerator(), withCompression),
ecSpec.getOrder(),
BigInteger.valueOf(ecSpec.getCofactor()),
ecSpec.getCurve().getSeed());
*/
params = new X962Parameters(ecP);
}
return params;
}
private static String convertEncodedDataToPEM(String type, byte[] encodedData) throws IOException {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut));
try {
PemObject pemObj = new PemObject(type, encodedData);
pWrt.writeObject(pemObj);
} finally {
pWrt.close();
}
return new String(bOut.toByteArray());
}
private static byte[] convertPEMToEncodedData(String pemString) throws IOException {
ByteArrayInputStream bIn = new ByteArrayInputStream(pemString.getBytes());
PemReader pRdr = new PemReader(new InputStreamReader(bIn));
try {
PemObject pemObject = pRdr.readPemObject();
return pemObject.getContent();
} finally {
pRdr.close();
}
}
}

View File

@ -1,11 +0,0 @@
package com.sunyard.ssp.utils.sm2;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;
public class GMBaseUtil {
static {
Security.addProvider(new BouncyCastleProvider());
}
}

View File

@ -1,6 +1,7 @@
package com.sunyard.ssp.utils.sm2;
import cn.hutool.core.util.ReflectUtil;
import com.sunyard.chsm.utils.gm.BCECUtils;
import com.sunyard.ssp.BytesUtil;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.ASN1Encodable;
@ -41,7 +42,7 @@ import java.security.spec.EllipticCurve;
import java.util.Base64;
@Slf4j
public class SM2Util extends GMBaseUtil {
public class SM2Util {
//////////////////////////////////////////////////////////////////////////////////////
/*
* 以下为SM2推荐曲线参数
@ -59,7 +60,7 @@ public class SM2Util extends GMBaseUtil {
public static final ECPoint G_POINT = CURVE.createPoint(SM2_ECC_GX, SM2_ECC_GY);
public static final ECDomainParameters DOMAIN_PARAMS = new ECDomainParameters(CURVE, G_POINT,
SM2_ECC_N, SM2_ECC_H);
public static final int CURVE_LEN = BCECUtil.getCurveLength(DOMAIN_PARAMS);
public static final int CURVE_LEN = BCECUtils.getCurveLength(DOMAIN_PARAMS);
//////////////////////////////////////////////////////////////////////////////////////
public static final EllipticCurve JDK_CURVE = new EllipticCurve(new ECFieldFp(SM2_ECC_P), SM2_ECC_A, SM2_ECC_B);
@ -99,7 +100,7 @@ public class SM2Util extends GMBaseUtil {
// log.info("x=" + xHex);
// log.info("y=" + yHex);
ECPublicKeyParameters pubKey = BCECUtil.createECPublicKeyParameters(xHex, yHex, SM2Util.CURVE, SM2Util.DOMAIN_PARAMS);
ECPublicKeyParameters pubKey = BCECUtils.createECPublicKeyParameters(xHex, yHex, SM2Util.CURVE, SM2Util.DOMAIN_PARAMS);
byte[] s = com.sunyard.ssp.util.BytesUtil.decodeBase64( sign );
@ -121,7 +122,7 @@ public class SM2Util extends GMBaseUtil {
*/
public static AsymmetricCipherKeyPair generateKeyPairParameter() {
SecureRandom random = new SecureRandom();
return BCECUtil.generateKeyPairParameter(DOMAIN_PARAMS, random);
return BCECUtils.generateKeyPairParameter(DOMAIN_PARAMS, random);
}
/**
@ -135,7 +136,7 @@ public class SM2Util extends GMBaseUtil {
public static KeyPair generateKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
SecureRandom random = new SecureRandom();
return BCECUtil.generateKeyPair(DOMAIN_PARAMS, random);
return BCECUtils.generateKeyPair(DOMAIN_PARAMS, random);
}
/**
@ -168,7 +169,7 @@ public class SM2Util extends GMBaseUtil {
* @throws InvalidCipherTextException
*/
public static byte[] encrypt(BCECPublicKey pubKey, byte[] srcData) throws InvalidCipherTextException {
ECPublicKeyParameters pubKeyParameters = BCECUtil.convertPublicKeyToParameters(pubKey);
ECPublicKeyParameters pubKeyParameters = BCECUtils.convertPublicKeyToParameters(pubKey);
return encrypt(Mode.C1C3C2, pubKeyParameters, srcData);
}
@ -180,7 +181,7 @@ public class SM2Util extends GMBaseUtil {
* @throws InvalidCipherTextException
*/
public static byte[] encrypt(Mode mode, BCECPublicKey pubKey, byte[] srcData) throws InvalidCipherTextException {
ECPublicKeyParameters pubKeyParameters = BCECUtil.convertPublicKeyToParameters(pubKey);
ECPublicKeyParameters pubKeyParameters = BCECUtils.convertPublicKeyToParameters(pubKey);
return encrypt(mode, pubKeyParameters, srcData);
}
@ -217,7 +218,7 @@ public class SM2Util extends GMBaseUtil {
* @throws InvalidCipherTextException
*/
public static byte[] decrypt(BCECPrivateKey priKey, byte[] sm2Cipher) throws InvalidCipherTextException {
ECPrivateKeyParameters priKeyParameters = BCECUtil.convertPrivateKeyToParameters(priKey);
ECPrivateKeyParameters priKeyParameters = BCECUtils.convertPrivateKeyToParameters(priKey);
return decrypt(Mode.C1C3C2, priKeyParameters, sm2Cipher);
}
@ -229,7 +230,7 @@ public class SM2Util extends GMBaseUtil {
* @throws InvalidCipherTextException
*/
public static byte[] decrypt(Mode mode, BCECPrivateKey priKey, byte[] sm2Cipher) throws InvalidCipherTextException {
ECPrivateKeyParameters priKeyParameters = BCECUtil.convertPrivateKeyToParameters(priKey);
ECPrivateKeyParameters priKeyParameters = BCECUtils.convertPrivateKeyToParameters(priKey);
return decrypt(mode, priKeyParameters, sm2Cipher);
}
@ -267,7 +268,7 @@ public class SM2Util extends GMBaseUtil {
* @throws IOException
*/
public static byte[] encodeSM2CipherToDER(byte[] cipher) throws Exception {
int curveLength = BCECUtil.getCurveLength(DOMAIN_PARAMS);
int curveLength = BCECUtils.getCurveLength(DOMAIN_PARAMS);
return encodeSM2CipherToDER(Mode.C1C3C2, curveLength, SM3_DIGEST_LENGTH, cipher);
}
@ -280,7 +281,7 @@ public class SM2Util extends GMBaseUtil {
* @throws Exception
*/
public static byte[] encodeSM2CipherToDER(Mode mode, byte[] cipher) throws Exception {
int curveLength = BCECUtil.getCurveLength(DOMAIN_PARAMS);
int curveLength = BCECUtils.getCurveLength(DOMAIN_PARAMS);
return encodeSM2CipherToDER(mode, curveLength, SM3_DIGEST_LENGTH, cipher);
}
@ -407,7 +408,7 @@ public class SM2Util extends GMBaseUtil {
* @throws CryptoException
*/
public static byte[] sign(BCECPrivateKey priKey, byte[] srcData) throws CryptoException {
ECPrivateKeyParameters priKeyParameters = BCECUtil.convertPrivateKeyToParameters(priKey);
ECPrivateKeyParameters priKeyParameters = BCECUtils.convertPrivateKeyToParameters(priKey);
return sign(priKeyParameters, null, srcData);
}
@ -434,7 +435,7 @@ public class SM2Util extends GMBaseUtil {
* @throws CryptoException
*/
public static byte[] sign(BCECPrivateKey priKey, byte[] withId, byte[] srcData) throws CryptoException {
ECPrivateKeyParameters priKeyParameters = BCECUtil.convertPrivateKeyToParameters(priKey);
ECPrivateKeyParameters priKeyParameters = BCECUtils.convertPrivateKeyToParameters(priKey);
return sign(priKeyParameters, withId, srcData);
}
@ -510,7 +511,7 @@ public class SM2Util extends GMBaseUtil {
* @return
*/
public static boolean verify(BCECPublicKey pubKey, byte[] srcData, byte[] sign) {
ECPublicKeyParameters pubKeyParameters = BCECUtil.convertPublicKeyToParameters(pubKey);
ECPublicKeyParameters pubKeyParameters = BCECUtils.convertPublicKeyToParameters(pubKey);
return verify(pubKeyParameters, null, srcData, sign);
}
@ -537,7 +538,7 @@ public class SM2Util extends GMBaseUtil {
* @return
*/
public static boolean verify(BCECPublicKey pubKey, byte[] withId, byte[] srcData, byte[] sign) {
ECPublicKeyParameters pubKeyParameters = BCECUtil.convertPublicKeyToParameters(pubKey);
ECPublicKeyParameters pubKeyParameters = BCECUtils.convertPublicKeyToParameters(pubKey);
return verify(pubKeyParameters, withId, srcData, sign);
}

View File

@ -1,24 +0,0 @@
package com.sunyard.ssp.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @date:2020/6/10
* @description:
*/
@Data
public class KeyVo {
@ApiModelProperty(value = "方案编号")
private String solutionNumber;
@ApiModelProperty(value = "模板编号")
private String tmplNumber;
@ApiModelProperty(value = "节点编号")
private String nodeNumber;
@ApiModelProperty(value = "密钥编号")
private String keyNumber;
}