Commit 5b89ce31 by yangyang

时空安全配置相关提交

parent 4882c162
package com.founder.commonutils.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* Created by admin on 2023
*/
public class propertiesUtil {
public static Properties propertiesUtil(String file){
Properties properties = new Properties();
InputStream inStream = propertiesUtil.class.getClassLoader().getResourceAsStream(file);
try {
properties.load(inStream);
} catch (IOException e) {
//e.printStackTrace();
}
return properties;
}
public static String getProConfig(String file,String key){
Properties pros = new Properties();
String value="";
try {
pros.load(new InputStreamReader(propertiesUtil.class.getClassLoader().getResourceAsStream(file),"UTF-8"));//chent 默认从classpath根下获取
value=pros.get(key).toString();
} catch (IOException e) {
//e.printStackTrace();
}
return value;
}
public static String getConfig(String file,String key){
Properties pros = new Properties();
String value="";
try {
String filePath = propertiesUtil.getProConfig("linuxPath.properties","filePath");
pros.load(new FileInputStream(filePath + file));
value=pros.get(key).toString();
} catch (IOException e) {
// e.printStackTrace();
}
return value;
}
}
...@@ -150,6 +150,22 @@ ...@@ -150,6 +150,22 @@
<artifactId>easyexcel</artifactId> <artifactId>easyexcel</artifactId>
<version>2.2.6</version> <version>2.2.6</version>
</dependency> </dependency>
<!-- License -->
<dependency>
<groupId>de.schlichtherle.truelicense</groupId>
<artifactId>truelicense-core</artifactId>
<version>1.33</version>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
......
...@@ -3,6 +3,7 @@ package com.founder.servicebase.config; ...@@ -3,6 +3,7 @@ package com.founder.servicebase.config;
import com.founder.servicebase.controller.SkInterceptorController; import com.founder.servicebase.controller.SkInterceptorController;
import com.founder.servicebase.interceptor.TokenInterceptor; import com.founder.servicebase.interceptor.TokenInterceptor;
import com.founder.servicebase.license.LicenseCheckInterceptor;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;
...@@ -32,6 +33,8 @@ public class TokenConfig implements WebMvcConfigurer { ...@@ -32,6 +33,8 @@ public class TokenConfig implements WebMvcConfigurer {
.excludePathPatterns(skInterceptorController.findAllUrl()) .excludePathPatterns(skInterceptorController.findAllUrl())
.excludePathPatterns(tokenInterceptor.getName()) .excludePathPatterns(tokenInterceptor.getName())
.excludePathPatterns(excludePatterns); .excludePathPatterns(excludePatterns);
registry.addInterceptor(new LicenseCheckInterceptor());
} }
@Override @Override
......
package com.founder.servicebase.license;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @ProjectName AbstractServerInfos
* @author Administrator
* @version 1.0.0
* @Description 用于获取客户服务器的基本信息,如:IP、Mac地址、CPU序列号、主板序列号等
* @createTime 2022/4/30 0030 18:24
*/
public abstract class AbstractServerInfos {
/**
* @title getServerInfos
* @description 组装需要额外校验的License参数
* @author Administrator
* @updateTime 2022/4/30 0030 18:24
*/
public LicenseCheckModel getServerInfos(){
LicenseCheckModel result = new LicenseCheckModel();
try {
result.setIpAddress(this.getIpAddress());
result.setMacAddress(this.getMacAddress());
result.setCpuSerial(this.getCPUSerial());
result.setMainBoardSerial(this.getMainBoardSerial());
}catch (Exception e){
//System.out.println("获取服务器硬件信息失败"+e);
}
return result;
}
/**
* @title getIpAddress
* @description 获取IP地址
* @author Administrator
* @updateTime 2022/4/30 0030 18:24
*/
protected abstract List<String> getIpAddress() throws Exception;
/**
* @title getMacAddress
* @description 获取Mac地址
* @author Administrator
* @updateTime 2022/4/30 0030 18:24
*/
protected abstract List<String> getMacAddress() throws Exception;
/**
* @title getCPUSerial
* @description 获取CPU序列号
* @author Administrator
* @updateTime 2022/4/30 0030 18:25
*/
protected abstract String getCPUSerial() throws Exception;
/**
* @title getMainBoardSerial
* @description 获取主板序列号
* @author Administrator
* @updateTime 2022/4/30 0030 18:25
*/
protected abstract String getMainBoardSerial() throws Exception;
/**
* @title getLocalAllInetAddress
* @description 获取当前服务器所有符合条件的InetAddress
* @author Administrator
* @updateTime 2022/4/30 0030 18:25
*/
protected List<InetAddress> getLocalAllInetAddress() throws Exception {
List<InetAddress> result = new ArrayList<>(4);
// 遍历所有的网络接口
for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) {
NetworkInterface iface = (NetworkInterface) networkInterfaces.nextElement();
// 在所有的接口下再遍历IP
for (Enumeration inetAddresses = iface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {
InetAddress inetAddr = (InetAddress) inetAddresses.nextElement();
//排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress类型的IP地址
if(!inetAddr.isLoopbackAddress() /*&& !inetAddr.isSiteLocalAddress()*/
&& !inetAddr.isLinkLocalAddress() && !inetAddr.isMulticastAddress()){
result.add(inetAddr);
}
}
}
return result;
}
/**
* @title getMacByInetAddress
* @description 获取某个网络接口的Mac地址
* @author Administrator
* @updateTime 2022/4/30 0030 18:25
*/
protected String getMacByInetAddress(InetAddress inetAddr){
try {
byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress();
StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<mac.length;i++){
if(i != 0) {
stringBuffer.append("-");
}
//将十六进制byte转化为字符串
String temp = Integer.toHexString(mac[i] & 0xff);
if(temp.length() == 1){
stringBuffer.append("0" + temp);
}else{
stringBuffer.append(temp);
}
}
return stringBuffer.toString().toUpperCase();
} catch (SocketException e) {
//e.printStackTrace();
}
return null;
}
}
package com.founder.servicebase.license;
import de.schlichtherle.license.AbstractKeyStoreParam;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @ProjectName CustomKeyStoreParam
* @author Administrator
* @version 1.0.0
* @Description 自定义KeyStoreParam,用于将公私钥存储文件存放到其他磁盘位置而不是项目中
* @createTime 2022/4/30 0030 18:25
*/
public class CustomKeyStoreParam extends AbstractKeyStoreParam {
/**
* 公钥/私钥在磁盘上的存储路径
*/
private String storePath;
private String alias;
private String storePwd;
private String keyPwd;
public CustomKeyStoreParam(Class clazz, String resource, String alias, String storePwd, String keyPwd) {
super(clazz, resource);
this.storePath = resource;
this.alias = alias;
this.storePwd = storePwd;
this.keyPwd = keyPwd;
}
@Override
public String getAlias() {
return alias;
}
@Override
public String getStorePwd() {
return storePwd;
}
@Override
public String getKeyPwd() {
return keyPwd;
}
/**
* @title getStream
* @description
* 复写de.schlichtherle.license.AbstractKeyStoreParam的getStream()方法<br/>
* 用于将公私钥存储文件存放到其他磁盘位置而不是项目中
* @author Administrator
* @updateTime 2022/4/30 0030 18:25
*/
@Override
public InputStream getStream() throws IOException {
final InputStream in = new FileInputStream(new File(storePath));
if (null == in){
//throw new FileNotFoundException(storePath);
}
return in;
}
}
package com.founder.servicebase.license;
import de.schlichtherle.license.*;
import de.schlichtherle.xml.GenericCertificate;
import org.apache.commons.lang3.StringUtils;
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
/**
* @ProjectName CustomLicenseManager
* @author Administrator
* @version 1.0.0
* @Description 自定义LicenseManager,用于增加额外的服务器硬件信息校验
* @createTime 2022/4/30 0030 18:26
*/
public class CustomLicenseManager extends LicenseManager{
//XML编码
private static final String XML_CHARSET = "UTF-8";
//默认BUFSIZE
private static final int DEFAULT_BUFSIZE = 8 * 1024;
public CustomLicenseManager() {
}
public CustomLicenseManager(LicenseParam param) {
super(param);
}
/**
* @title create
* @description 复写create方法
* @author Administrator
* @updateTime 2022/4/30 0030 18:26
*/
@Override
protected synchronized byte[] create(
LicenseContent content,
LicenseNotary notary)
throws Exception {
initialize(content);
this.validateCreate(content);
final GenericCertificate certificate = notary.sign(content);
return getPrivacyGuard().cert2key(certificate);
}
/**
* @title install
* @description 复写install方法,其中validate方法调用本类中的validate方法,校验IP地址、Mac地址等其他信息
* @author Administrator
* @updateTime 2022/4/30 0030 18:26
*/
@Override
protected synchronized LicenseContent install(
final byte[] key,
final LicenseNotary notary)
throws Exception {
final GenericCertificate certificate = getPrivacyGuard().key2cert(key);
notary.verify(certificate);
final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded());
this.validate(content);
setLicenseKey(key);
setCertificate(certificate);
return content;
}
/**
* @title verify
* @description 复写verify方法,调用本类中的validate方法,校验IP地址、Mac地址等其他信息
* @author Administrator
* @updateTime 2022/4/30 0030 18:26
*/
@Override
protected synchronized LicenseContent verify(final LicenseNotary notary)
throws Exception {
GenericCertificate certificate = getCertificate();
// Load license key from preferences,
final byte[] key = getLicenseKey();
if (null == key){
throw new NoLicenseInstalledException(getLicenseParam().getSubject());
}
certificate = getPrivacyGuard().key2cert(key);
notary.verify(certificate);
final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded());
this.validate(content);
setCertificate(certificate);
return content;
}
/**
* @title validateCreate
* @description 校验生成证书的参数信息
* @author Administrator
* @updateTime 2022/4/30 0030 18:26
*/
protected synchronized void validateCreate(final LicenseContent content)
throws LicenseContentException {
final LicenseParam param = getLicenseParam();
final Date now = new Date();
final Date notBefore = content.getNotBefore();
final Date notAfter = content.getNotAfter();
if (null != notAfter && now.after(notAfter)){
//throw new LicenseContentException("证书失效时间不能早于当前时间");
}
if (null != notBefore && null != notAfter && notAfter.before(notBefore)){
//throw new LicenseContentException("证书生效时间不能晚于证书失效时间");
}
final String consumerType = content.getConsumerType();
if (null == consumerType){
//throw new LicenseContentException("用户类型不能为空");
}
}
/**
* @title validate
* @description 复写validate方法,增加IP地址、Mac地址等其他信息校验
* @author Administrator
* @updateTime 2022/4/30 0030 18:26
*/
@Override
protected synchronized void validate(final LicenseContent content)
throws LicenseContentException {
//1. 首先调用父类的validate方法
super.validate(content);
//2. 然后校验自定义的License参数
//License中可被允许的参数信息
LicenseCheckModel expectedCheckModel = (LicenseCheckModel) content.getExtra();
//当前服务器真实的参数信息
LicenseCheckModel serverCheckModel = getServerInfos();
if(expectedCheckModel != null && serverCheckModel != null){
//校验IP地址
if(!checkIpAddress(expectedCheckModel.getIpAddress(),serverCheckModel.getIpAddress())){
//throw new LicenseContentException("当前服务器的IP没在授权范围内");
}
//校验Mac地址
if(!checkIpAddress(expectedCheckModel.getMacAddress(),serverCheckModel.getMacAddress())){
//throw new LicenseContentException("当前服务器的Mac地址没在授权范围内");
}
//校验主板序列号
if(!checkSerial(expectedCheckModel.getMainBoardSerial(),serverCheckModel.getMainBoardSerial())){
//throw new LicenseContentException("当前服务器的主板序列号没在授权范围内");
}
//校验CPU序列号
if(!checkSerial(expectedCheckModel.getCpuSerial(),serverCheckModel.getCpuSerial())){
//throw new LicenseContentException("当前服务器的CPU序列号没在授权范围内");
}
}else{
//throw new LicenseContentException("不能获取服务器硬件信息");
}
}
/**
* @title load
* @description 重写XMLDecoder解析XML
* @author Administrator
* @updateTime 2022/4/30 0030 18:27
*/
private Object load(String encoded){
BufferedInputStream inputStream = null;
XMLDecoder decoder = null;
try {
inputStream = new BufferedInputStream(new ByteArrayInputStream(encoded.getBytes(XML_CHARSET)));
decoder = new XMLDecoder(new BufferedInputStream(inputStream, DEFAULT_BUFSIZE),null,null);
return decoder.readObject();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
try {
if(decoder != null){
decoder.close();
}
if(inputStream != null){
inputStream.close();
}
} catch (Exception e) {
System.out.println("XMLDecoder解析XML失败"+e);
}
}
return null;
}
/**
* @title getServerInfos
* @description 获取当前服务器需要额外校验的License参数
* @author Administrator
* @updateTime 2022/4/30 0030 18:27
*/
private LicenseCheckModel getServerInfos(){
//操作系统类型
String osName = System.getProperty("os.name").toLowerCase();
AbstractServerInfos abstractServerInfos = null;
//根据不同操作系统类型选择不同的数据获取方法
if (osName.startsWith("windows")) {
abstractServerInfos = new WindowsServerInfos();
} else if (osName.startsWith("linux")) {
abstractServerInfos = new LinuxServerInfos();
}else{//其他服务器类型
abstractServerInfos = new LinuxServerInfos();
}
return abstractServerInfos.getServerInfos();
}
/**
* @title checkIpAddress
* @description
* 校验当前服务器的IP/Mac地址是否在可被允许的IP范围内<br/>
* 如果存在IP在可被允许的IP/Mac地址范围内,则返回true
* @author Administrator
* @updateTime 2022/4/30 0030 18:27
*/
private boolean checkIpAddress(List<String> expectedList, List<String> serverList){
if(expectedList != null && expectedList.size() > 0){
if(serverList != null && serverList.size() > 0){
for(String expected : expectedList){
if(serverList.contains(expected.trim())){
return true;
}
}
}
return false;
}else {
return true;
}
}
/**
* @title checkSerial
* @description 校验当前服务器硬件(主板、CPU等)序列号是否在可允许范围内
* @author Administrator
* @updateTime 2022/4/30 0030 18:27
*/
private boolean checkSerial(String expectedSerial, String serverSerial){
if(StringUtils.isNotBlank(expectedSerial)){
if(StringUtils.isNotBlank(serverSerial)){
if(expectedSerial.equals(serverSerial)){
return true;
}
}
return false;
}else{
return true;
}
}
}
package com.founder.servicebase.license;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;
@Component
public class JarNameGetter {
@Autowired
private ApplicationArguments applicationArguments;
public String getJarFileName() {
return this.applicationArguments.getNonOptionArgs().stream()
.findFirst()
.orElse(""); // 默认返回空字符串
}
}
package com.founder.servicebase.license;
import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* @ProjectName LicenseCheckInterceptor
* @author Administrator
* @version 1.0.0
* @Description LicenseCheckInterceptor
* @createTime 2022/4/30 0030 18:27
*/
public class LicenseCheckInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
LicenseVerify licenseVerify = new LicenseVerify();
//校验证书是否有效
boolean verifyResult = licenseVerify.verify();
if(verifyResult){
return true;
}else{
response.setCharacterEncoding("utf-8");
Map<String,String> result = new HashMap<>(1);
result.put("result",null);
response.getWriter().write(JSON.toJSONString(result));
return false;
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
package com.founder.servicebase.license;
import com.founder.commonutils.util.propertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
/**
* @ProjectName LicenseCheckListener
* @author Administrator
* @version 1.0.0
* @Description 在项目启动时安装证书
* @createTime 2022/4/30 0030 18:28
*/
@Component
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
String subject = propertiesUtil.getProConfig("secure-config.properties", "secureJob");
String publicAlias = propertiesUtil.getProConfig("secure-config.properties", "securePublic");
String storePass = propertiesUtil.getProConfig("secure-config.properties", "securePass");
String licensePath = propertiesUtil.getProConfig("secure-config.properties", "securePath");
String publicKeysStorePath = propertiesUtil.getProConfig("secure-config.properties", "secureStorePath");
//root application context 没有parent
if (StringUtils.isNotBlank(licensePath)) {
LicenseVerifyParam param = new LicenseVerifyParam();
param.setSubject(subject);
param.setPublicAlias(publicAlias);
param.setStorePass(storePass);
param.setLicensePath(licensePath);
param.setPublicKeysStorePath(publicKeysStorePath);
LicenseVerify licenseVerify = new LicenseVerify();
//安装证书
licenseVerify.install(param);
}
}
}
package com.founder.servicebase.license;
import java.io.Serializable;
import java.util.List;
/**
* @ProjectName LicenseCheckModel
* @author Administrator
* @version 1.0.0
* @Description 自定义需要校验的License参数
* @createTime 2022/4/30 0030 18:28
*/
public class LicenseCheckModel implements Serializable {
private static final long serialVersionUID = 8600137500316662317L;
/**
* 可被允许的IP地址
*/
private List<String> ipAddress;
/**
* 可被允许的MAC地址
*/
private List<String> macAddress;
/**
* 可被允许的CPU序列号
*/
private String cpuSerial;
/**
* 可被允许的主板序列号
*/
private String mainBoardSerial;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public List<String> getIpAddress() {
return ipAddress;
}
public void setIpAddress(List<String> ipAddress) {
this.ipAddress = ipAddress;
}
public List<String> getMacAddress() {
return macAddress;
}
public void setMacAddress(List<String> macAddress) {
this.macAddress = macAddress;
}
public String getCpuSerial() {
return cpuSerial;
}
public void setCpuSerial(String cpuSerial) {
this.cpuSerial = cpuSerial;
}
public String getMainBoardSerial() {
return mainBoardSerial;
}
public void setMainBoardSerial(String mainBoardSerial) {
this.mainBoardSerial = mainBoardSerial;
}
}
package com.founder.servicebase.license;
import de.schlichtherle.license.LicenseManager;
import de.schlichtherle.license.LicenseParam;
/**
* @ProjectName LicenseManagerHolder
* @author Administrator
* @version 1.0.0
* @Description LicenseManager的单例
* @createTime 2022/4/30 0030 18:28
*/
public class LicenseManagerHolder {
private static volatile LicenseManager LICENSE_MANAGER;
public static LicenseManager getInstance(LicenseParam param){
if(LICENSE_MANAGER == null){
synchronized (LicenseManagerHolder.class){
if(LICENSE_MANAGER == null){
LICENSE_MANAGER = new CustomLicenseManager(param);
}
}
}
return LICENSE_MANAGER;
}
}
package com.founder.servicebase.license;
import de.schlichtherle.license.*;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;
/**
* @ProjectName LicenseVerify
* @author Administrator
* @version 1.0.0
* @Description License校验类
* @createTime 2022/4/30 0030 18:28
*/
public class LicenseVerify {
/**
* @title install
* @description 安装License证书
* @author Administrator
* @updateTime 2022/4/30 0030 18:29
*/
public synchronized LicenseContent install(LicenseVerifyParam param){
LicenseContent result = null;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//1. 安装证书
try{
LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
licenseManager.uninstall();
result = licenseManager.install(new File(param.getLicensePath()));
// System.out.println(MessageFormat.format("证书安装成功,证书有效期:{0} - {1}",format.format(result.getNotBefore()),format.format(result.getNotAfter())));
}catch (Exception e){
//System.out.println("证书安装失败!"+e);
}
return result;
}
/**
* @title verify
* @description 校验License证书
* @author Administrator
* @updateTime 2022/4/30 0030 18:29
*/
public boolean verify(){
LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//2. 校验证书
try {
LicenseContent licenseContent = licenseManager.verify();
// System.out.println(licenseContent.getSubject());
// System.out.println(MessageFormat.format("证书校验通过,证书有效期:{0} - {1}",format.format(licenseContent.getNotBefore()),format.format(licenseContent.getNotAfter())));
return true;
}catch (Exception e){
//System.out.println("证书校验失败!"+e);
return false;
}
}
/**
* @title initLicenseParam
* @description 初始化证书生成参数
* @author Administrator
* @updateTime 2022/4/30 0030 18:29
*/
private LicenseParam initLicenseParam(LicenseVerifyParam param){
Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);
CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class
,param.getPublicKeysStorePath()
,param.getPublicAlias()
,param.getStorePass()
,null);
return new DefaultLicenseParam(param.getSubject()
,preferences
,publicStoreParam
,cipherParam);
}
}
package com.founder.servicebase.license;
/**
* @ProjectName LicenseVerifyParam
* @author Administrator
* @version 1.0.0
* @Description License校验类需要的参数
* @createTime 2022/4/30 0030 18:29
*/
public class LicenseVerifyParam {
/**
* 证书subject
*/
private String subject;
/**
* 公钥别称
*/
private String publicAlias;
/**
* 访问公钥库的密码
*/
private String storePass;
/**
* 证书生成路径
*/
private String licensePath;
/**
* 密钥库存储路径
*/
private String publicKeysStorePath;
public LicenseVerifyParam() {
}
public LicenseVerifyParam(String subject, String publicAlias, String storePass, String licensePath, String publicKeysStorePath) {
this.subject = subject;
this.publicAlias = publicAlias;
this.storePass = storePass;
this.licensePath = licensePath;
this.publicKeysStorePath = publicKeysStorePath;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPublicAlias() {
return publicAlias;
}
public void setPublicAlias(String publicAlias) {
this.publicAlias = publicAlias;
}
public String getStorePass() {
return storePass;
}
public void setStorePass(String storePass) {
this.storePass = storePass;
}
public String getLicensePath() {
return licensePath;
}
public void setLicensePath(String licensePath) {
this.licensePath = licensePath;
}
public String getPublicKeysStorePath() {
return publicKeysStorePath;
}
public void setPublicKeysStorePath(String publicKeysStorePath) {
this.publicKeysStorePath = publicKeysStorePath;
}
}
package com.founder.servicebase.license;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.List;
import java.util.stream.Collectors;
/**
* @ProjectName LinuxServerInfos
* @author Administrator
* @version 1.0.0
* @Description 用于获取客户Linux服务器的基本信息
* @createTime 2022/4/30 0030 18:30
*/
public class LinuxServerInfos extends AbstractServerInfos {
@Override
protected List<String> getIpAddress() throws Exception {
List<String> result = null;
//获取所有网络接口
List<InetAddress> inetAddresses = getLocalAllInetAddress();
if(inetAddresses != null && inetAddresses.size() > 0){
result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList());
}
return result;
}
@Override
protected List<String> getMacAddress() throws Exception {
List<String> result = null;
//1. 获取所有网络接口
List<InetAddress> inetAddresses = getLocalAllInetAddress();
if(inetAddresses != null && inetAddresses.size() > 0){
//2. 获取所有网络接口的Mac地址
result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
}
return result;
}
@Override
protected String getCPUSerial() throws Exception {
//序列号
String serialNumber = "";
//使用dmidecode命令获取CPU序列号
String[] shell = {"/bin/bash","-c","dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"};
Process process = Runtime.getRuntime().exec(shell);
process.getOutputStream().close();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine().trim();
if(StringUtils.isNotBlank(line)){
serialNumber = line;
}
reader.close();
return serialNumber;
}
@Override
protected String getMainBoardSerial() throws Exception {
//序列号
String serialNumber = "";
//使用dmidecode命令获取主板序列号
String[] shell = {"/bin/bash","-c","dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"};
Process process = Runtime.getRuntime().exec(shell);
process.getOutputStream().close();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine().trim();
if(StringUtils.isNotBlank(line)){
serialNumber = line;
}
reader.close();
return serialNumber;
}
}
package com.founder.servicebase.license;
import java.net.InetAddress;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* @ProjectName WindowsServerInfos
* @author Administrator
* @version 1.0.0
* @Description 用于获取客户Windows服务器的基本信息
* @createTime 2022/4/30 0030 18:30
*/
public class WindowsServerInfos extends AbstractServerInfos {
@Override
protected List<String> getIpAddress() throws Exception {
List<String> result = null;
//获取所有网络接口
List<InetAddress> inetAddresses = getLocalAllInetAddress();
if(inetAddresses != null && inetAddresses.size() > 0){
result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList());
}
return result;
}
@Override
protected List<String> getMacAddress() throws Exception {
List<String> result = null;
//1. 获取所有网络接口
List<InetAddress> inetAddresses = getLocalAllInetAddress();
if(inetAddresses != null && inetAddresses.size() > 0){
//2. 获取所有网络接口的Mac地址
result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
}
return result;
}
@Override
protected String getCPUSerial() throws Exception {
//序列号
String serialNumber = "";
//使用WMIC获取CPU序列号
Process process = Runtime.getRuntime().exec("wmic cpu get processorid");
process.getOutputStream().close();
Scanner scanner = new Scanner(process.getInputStream());
if(scanner != null && scanner.hasNext()){
scanner.next();
}
if(scanner.hasNext()){
serialNumber = scanner.next().trim();
}
scanner.close();
return serialNumber;
}
@Override
protected String getMainBoardSerial() throws Exception {
//序列号
String serialNumber = "";
//使用WMIC获取主板序列号
Process process = Runtime.getRuntime().exec("wmic baseboard get serialnumber");
process.getOutputStream().close();
Scanner scanner = new Scanner(process.getInputStream());
if(scanner != null && scanner.hasNext()){
scanner.next();
}
if(scanner.hasNext()){
serialNumber = scanner.next().trim();
}
scanner.close();
return serialNumber;
}
}
#secure
#
secureJob=map-parent
securePublic=publicCert
securePass=public_dgzhituv1.0
securePath=D:\\license\\secure.lic
secureStorePath=D:\\license\\secureCerts.keystore
#
#securePath=/data/secure/secure.lic
#secureStorePath=/data/secure/secureCerts.keystore
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>licenseDemo</artifactId>
<groupId>com.sgw</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>license-server</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
\ No newline at end of file
package com.founder.servicebase;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@ServletComponentScan
@PropertySource({"license-config.properties"})
public class LicenseServer {
public static void main(String[] args) {
SpringApplication.run(LicenseServer.class, args);
}
}
\ No newline at end of file
package com.founder.servicebase.controller;
import com.founder.servicebase.license.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @ProjectName LicenseCreatorController
* @author Administrator
* @version 1.0.0
* @Description 于生成证书文件,不能放在给客户部署的代码里
* @createTime 2022/4/30 0030 18:13
*/
@RestController
@RequestMapping("/license")
public class LicenseCreatorController {
/**
* 证书生成路径
*/
@Value("${license.licensePath}")
private String licensePath;
/**
* @title 获取服务器硬件信息
* @description @param osName 操作系统类型,如果为空则自动判断
* @author Administrator
* @updateTime 2022/4/30 0030 18:14
*/
@RequestMapping(value = "/getServerInfos")
public LicenseCheckModel getServerInfos(@RequestParam(value = "osName",required = false) String osName) {
//操作系统类型
if(StringUtils.isBlank(osName)){
osName = System.getProperty("os.name");
}
osName = osName.toLowerCase();
AbstractServerInfos abstractServerInfos = null;
//根据不同操作系统类型选择不同的数据获取方法
if (osName.startsWith("windows")) {
abstractServerInfos = new WindowsServerInfos();
} else if (osName.startsWith("linux")) {
abstractServerInfos = new LinuxServerInfos();
}else{//其他服务器类型
abstractServerInfos = new LinuxServerInfos();
}
return abstractServerInfos.getServerInfos();
}
/**
* @title 生成证书
* @description
* {
* "result": "ok",
* "msg": {
* "subject": "license_demo",
* "privateAlias": "privateKey",
* "keyPass": "private_password1234",
* "storePass": "public_password1234",
* "licensePath": "D:/license/license.lic",
* "privateKeysStorePath": "D:/license/privateKeys.keystore",
* "issuedTime": "2022-04-10 00:00:01",
* "expiryTime": "2022-05-31 23:59:59",
* "consumerType": "User",
* "consumerAmount": 1,
* "description": "这是证书描述信息",
* "licenseCheckModel": {
* "ipAddress": [],
* "macAddress": [],
* "cpuSerial": "",
* "mainBoardSerial": ""
* }
* }
* }
* @author Administrator
* @updateTime 2022/4/30 0030 18:14
*/
@RequestMapping(value = "/generateLicense",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public Map<String,Object> generateLicense(@RequestBody(required = true) LicenseCreatorParam param) {
Map<String,Object> resultMap = new HashMap<>(2);
if(StringUtils.isBlank(param.getLicensePath())){
param.setLicensePath(licensePath);
}
LicenseCreator licenseCreator = new LicenseCreator(param);
boolean result = licenseCreator.generateLicense();
if(result){
resultMap.put("result","ok");
resultMap.put("msg",param);
}else{
resultMap.put("result","error");
resultMap.put("msg","证书文件生成失败!");
}
return resultMap;
}
}
package com.founder.servicebase.license;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @ProjectName AbstractServerInfos
* @author Administrator
* @version 1.0.0
* @Description 用于获取客户服务器的基本信息,如:IP、Mac地址、CPU序列号、主板序列号等
* @createTime 2022/4/30 0030 18:15
*/
public abstract class AbstractServerInfos {
private static Logger logger = LogManager.getLogger(AbstractServerInfos.class);
/**
* @title getServerInfos
* @description 组装需要额外校验的License参数
* @author Administrator
* @updateTime 2022/4/30 0030 18:15
*/
public LicenseCheckModel getServerInfos(){
LicenseCheckModel result = new LicenseCheckModel();
try {
result.setIpAddress(this.getIpAddress());
result.setMacAddress(this.getMacAddress());
result.setCpuSerial(this.getCPUSerial());
result.setMainBoardSerial(this.getMainBoardSerial());
}catch (Exception e){
logger.error("获取服务器硬件信息失败",e);
}
return result;
}
/**
* @title getIpAddress
* @description 获取IP地址
* @author Administrator
* @updateTime 2022/4/30 0030 18:15
*/
protected abstract List<String> getIpAddress() throws Exception;
/**
* @title getMacAddress
* @description 获取Mac地址
* @author Administrator
* @updateTime 2022/4/30 0030 18:16
*/
protected abstract List<String> getMacAddress() throws Exception;
/**
* @title getCPUSerial
* @description 获取CPU序列号
* @author Administrator
* @updateTime 2022/4/30 0030 18:16
*/
protected abstract String getCPUSerial() throws Exception;
/**
* @title getMainBoardSerial
* @description 获取主板序列号
* @author Administrator
* @updateTime 2022/4/30 0030 18:16
*/
protected abstract String getMainBoardSerial() throws Exception;
/**
* @title getLocalAllInetAddress
* @description 获取当前服务器所有符合条件的InetAddress
* @author Administrator
* @updateTime 2022/4/30 0030 18:16
*/
protected List<InetAddress> getLocalAllInetAddress() throws Exception {
List<InetAddress> result = new ArrayList<>(4);
// 遍历所有的网络接口
for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) {
NetworkInterface iface = (NetworkInterface) networkInterfaces.nextElement();
// 在所有的接口下再遍历IP
for (Enumeration inetAddresses = iface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {
InetAddress inetAddr = (InetAddress) inetAddresses.nextElement();
//排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress类型的IP地址
if(!inetAddr.isLoopbackAddress() /*&& !inetAddr.isSiteLocalAddress()*/
&& !inetAddr.isLinkLocalAddress() && !inetAddr.isMulticastAddress()){
result.add(inetAddr);
}
}
}
return result;
}
/**
* @title getMacByInetAddress
* @description 获取某个网络接口的Mac地址
* @author Administrator
* @updateTime 2022/4/30 0030 18:16
*/
protected String getMacByInetAddress(InetAddress inetAddr){
try {
byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress();
StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<mac.length;i++){
if(i != 0) {
stringBuffer.append("-");
}
//将十六进制byte转化为字符串
String temp = Integer.toHexString(mac[i] & 0xff);
if(temp.length() == 1){
stringBuffer.append("0" + temp);
}else{
stringBuffer.append(temp);
}
}
return stringBuffer.toString().toUpperCase();
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
}
package com.founder.servicebase.license;
import de.schlichtherle.license.AbstractKeyStoreParam;
import java.io.*;
/**
* @ProjectName CustomKeyStoreParam
* @author Administrator
* @version 1.0.0
* @Description 自定义KeyStoreParam,用于将公私钥存储文件存放到其他磁盘位置而不是项目中
* @createTime 2022/4/30 0030 18:16
*/
public class CustomKeyStoreParam extends AbstractKeyStoreParam {
/**
* 公钥/私钥在磁盘上的存储路径
*/
private String storePath;
private String alias;
private String storePwd;
private String keyPwd;
public CustomKeyStoreParam(Class clazz, String resource,String alias,String storePwd,String keyPwd) {
super(clazz, resource);
this.storePath = resource;
this.alias = alias;
this.storePwd = storePwd;
this.keyPwd = keyPwd;
}
@Override
public String getAlias() {
return alias;
}
@Override
public String getStorePwd() {
return storePwd;
}
@Override
public String getKeyPwd() {
return keyPwd;
}
/**
* @title getStream
* @description
* 复写de.schlichtherle.license.AbstractKeyStoreParam的getStream()方法<br/>
* 用于将公私钥存储文件存放到其他磁盘位置而不是项目中
* @author Administrator
* @updateTime 2022/4/30 0030 18:16
*/
@Override
public InputStream getStream() throws IOException {
final InputStream in = new FileInputStream(new File(storePath));
if (null == in){
throw new FileNotFoundException(storePath);
}
return in;
}
}
package com.founder.servicebase.license;
import de.schlichtherle.license.*;
import de.schlichtherle.xml.GenericCertificate;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
/**
* @title CustomLicenseManager
* @description 自定义LicenseManager,用于增加额外的服务器硬件信息校验
* @author Administrator
* @updateTime 2022/4/30 0030 18:17
*/
public class CustomLicenseManager extends LicenseManager{
private static Logger logger = LogManager.getLogger(CustomLicenseManager.class);
//XML编码
private static final String XML_CHARSET = "UTF-8";
//默认BUFSIZE
private static final int DEFAULT_BUFSIZE = 8 * 1024;
public CustomLicenseManager() {
}
public CustomLicenseManager(LicenseParam param) {
super(param);
}
/**
* @title create
* @description 复写create方法
* @author Administrator
* @updateTime 2022/4/30 0030 18:17
*/
@Override
protected synchronized byte[] create(
LicenseContent content,
LicenseNotary notary)
throws Exception {
initialize(content);
this.validateCreate(content);
final GenericCertificate certificate = notary.sign(content);
return getPrivacyGuard().cert2key(certificate);
}
/**
* @title install
* @description 复写install方法,其中validate方法调用本类中的validate方法,校验IP地址、Mac地址等其他信息
* @author Administrator
* @updateTime 2022/4/30 0030 18:17
*/
@Override
protected synchronized LicenseContent install(
final byte[] key,
final LicenseNotary notary)
throws Exception {
final GenericCertificate certificate = getPrivacyGuard().key2cert(key);
notary.verify(certificate);
final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded());
this.validate(content);
setLicenseKey(key);
setCertificate(certificate);
return content;
}
/**
* @title verify
* @description 复写verify方法,调用本类中的validate方法,校验IP地址、Mac地址等其他信息
* @author Administrator
* @updateTime 2022/4/30 0030 18:17
*/
@Override
protected synchronized LicenseContent verify(final LicenseNotary notary)
throws Exception {
GenericCertificate certificate = getCertificate();
// Load license key from preferences,
final byte[] key = getLicenseKey();
if (null == key){
throw new NoLicenseInstalledException(getLicenseParam().getSubject());
}
certificate = getPrivacyGuard().key2cert(key);
notary.verify(certificate);
final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded());
this.validate(content);
setCertificate(certificate);
return content;
}
/**
* @title validateCreate
* @description 校验生成证书的参数信息
* @author Administrator
* @updateTime 2022/4/30 0030 18:18
*/
protected synchronized void validateCreate(final LicenseContent content)
throws LicenseContentException {
final LicenseParam param = getLicenseParam();
final Date now = new Date();
final Date notBefore = content.getNotBefore();
final Date notAfter = content.getNotAfter();
if (null != notAfter && now.after(notAfter)){
throw new LicenseContentException("证书失效时间不能早于当前时间");
}
if (null != notBefore && null != notAfter && notAfter.before(notBefore)){
throw new LicenseContentException("证书生效时间不能晚于证书失效时间");
}
final String consumerType = content.getConsumerType();
if (null == consumerType){
throw new LicenseContentException("用户类型不能为空");
}
}
/**
* @title validate
* @description 复写validate方法,增加IP地址、Mac地址等其他信息校验
* @author Administrator
* @updateTime 2022/4/30 0030 18:18
*/
@Override
protected synchronized void validate(final LicenseContent content)
throws LicenseContentException {
//1. 首先调用父类的validate方法
super.validate(content);
//2. 然后校验自定义的License参数
//License中可被允许的参数信息
LicenseCheckModel expectedCheckModel = (LicenseCheckModel) content.getExtra();
//当前服务器真实的参数信息
LicenseCheckModel serverCheckModel = getServerInfos();
if(expectedCheckModel != null && serverCheckModel != null){
//校验IP地址
if(!checkIpAddress(expectedCheckModel.getIpAddress(),serverCheckModel.getIpAddress())){
throw new LicenseContentException("当前服务器的IP没在授权范围内");
}
//校验Mac地址
if(!checkIpAddress(expectedCheckModel.getMacAddress(),serverCheckModel.getMacAddress())){
throw new LicenseContentException("当前服务器的Mac地址没在授权范围内");
}
//校验主板序列号
if(!checkSerial(expectedCheckModel.getMainBoardSerial(),serverCheckModel.getMainBoardSerial())){
throw new LicenseContentException("当前服务器的主板序列号没在授权范围内");
}
//校验CPU序列号
if(!checkSerial(expectedCheckModel.getCpuSerial(),serverCheckModel.getCpuSerial())){
throw new LicenseContentException("当前服务器的CPU序列号没在授权范围内");
}
}else{
throw new LicenseContentException("不能获取服务器硬件信息");
}
}
/**
* @title load
* @description 重写XMLDecoder解析XML
* @author Administrator
* @updateTime 2022/4/30 0030 18:18
*/
private Object load(String encoded){
BufferedInputStream inputStream = null;
XMLDecoder decoder = null;
try {
inputStream = new BufferedInputStream(new ByteArrayInputStream(encoded.getBytes(XML_CHARSET)));
decoder = new XMLDecoder(new BufferedInputStream(inputStream, DEFAULT_BUFSIZE),null,null);
return decoder.readObject();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
try {
if(decoder != null){
decoder.close();
}
if(inputStream != null){
inputStream.close();
}
} catch (Exception e) {
logger.error("XMLDecoder解析XML失败",e);
}
}
return null;
}
/**
* @title getServerInfos
* @description 获取当前服务器需要额外校验的License参数
* @author Administrator
* @updateTime 2022/4/30 0030 18:18
*/
private LicenseCheckModel getServerInfos(){
//操作系统类型
String osName = System.getProperty("os.name").toLowerCase();
AbstractServerInfos abstractServerInfos = null;
//根据不同操作系统类型选择不同的数据获取方法
if (osName.startsWith("windows")) {
abstractServerInfos = new WindowsServerInfos();
} else if (osName.startsWith("linux")) {
abstractServerInfos = new LinuxServerInfos();
}else{//其他服务器类型
abstractServerInfos = new LinuxServerInfos();
}
return abstractServerInfos.getServerInfos();
}
/**
* @title checkIpAddress
* @description
* 校验当前服务器的IP/Mac地址是否在可被允许的IP范围内<br/>
* 如果存在IP在可被允许的IP/Mac地址范围内,则返回true
* @author Administrator
* @updateTime 2022/4/30 0030 18:18
*/
private boolean checkIpAddress(List<String> expectedList,List<String> serverList){
if(expectedList != null && expectedList.size() > 0){
if(serverList != null && serverList.size() > 0){
for(String expected : expectedList){
if(serverList.contains(expected.trim())){
return true;
}
}
}
return false;
}else {
return true;
}
}
/**
* @title checkSerial
* @description 校验当前服务器硬件(主板、CPU等)序列号是否在可允许范围内
* @author Administrator
* @updateTime 2022/4/30 0030 18:18
*/
private boolean checkSerial(String expectedSerial,String serverSerial){
if(StringUtils.isNotBlank(expectedSerial)){
if(StringUtils.isNotBlank(serverSerial)){
if(expectedSerial.equals(serverSerial)){
return true;
}
}
return false;
}else{
return true;
}
}
}
package com.founder.servicebase.license;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @title LicenseCheckModel
* @description 自定义需要校验的License参数
* @author Administrator
* @updateTime 2022/4/30 0030 18:19
*/
@Data
public class LicenseCheckModel implements Serializable{
private static final long serialVersionUID = 8600137500316662317L;
/**
* 可被允许的IP地址
*/
private List<String> ipAddress;
/**
* 可被允许的MAC地址
*/
private List<String> macAddress;
/**
* 可被允许的CPU序列号
*/
private String cpuSerial;
/**
* 可被允许的主板序列号
*/
private String mainBoardSerial;
}
package com.founder.servicebase.license;
import de.schlichtherle.license.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.text.MessageFormat;
import java.util.prefs.Preferences;
/**
* @ProjectName LicenseCreator
* @author Administrator
* @version 1.0.0
* @Description License生成类
* @createTime 2022/4/30 0030 18:19
*/
public class LicenseCreator {
private static Logger logger = LogManager.getLogger(LicenseCreator.class);
private final static X500Principal DEFAULT_HOLDER_AND_ISSUER = new X500Principal("CN=localhost, OU=localhost, O=localhost, L=SH, ST=SH, C=CN");
private LicenseCreatorParam param;
public LicenseCreator(LicenseCreatorParam param) {
this.param = param;
}
/**
* @title generateLicense
* @description 生成License证书
* @author Administrator
* @updateTime 2022/4/30 0030 18:19
*/
public boolean generateLicense(){
try {
LicenseManager licenseManager = new CustomLicenseManager(initLicenseParam());
LicenseContent licenseContent = initLicenseContent();
licenseManager.store(licenseContent,new File(param.getLicensePath()));
return true;
}catch (Exception e){
logger.error(MessageFormat.format("证书生成失败:{0}",param),e);
return false;
}
}
/**
* @title initLicenseParam
* @description 初始化证书生成参数
* @author Administrator
* @updateTime 2022/4/30 0030 18:19
*/
private LicenseParam initLicenseParam(){
Preferences preferences = Preferences.userNodeForPackage(LicenseCreator.class);
//设置对证书内容加密的秘钥
CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
//自定义KeyStoreParam,用于将公私钥存储文件存放到其他磁盘位置而不是项目中
KeyStoreParam privateStoreParam = new CustomKeyStoreParam(LicenseCreator.class
,param.getPrivateKeysStorePath()
,param.getPrivateAlias()
,param.getStorePass()
,param.getKeyPass());
//组织License参数
LicenseParam licenseParam = new DefaultLicenseParam(param.getSubject()
,preferences
,privateStoreParam
,cipherParam);
return licenseParam;
}
/**
* @title initLicenseContent
* @description 设置证书生成正文信息
* @author Administrator
* @updateTime 2022/4/30 0030 18:19
*/
private LicenseContent initLicenseContent(){
LicenseContent licenseContent = new LicenseContent();
licenseContent.setHolder(DEFAULT_HOLDER_AND_ISSUER);
licenseContent.setIssuer(DEFAULT_HOLDER_AND_ISSUER);
licenseContent.setSubject(param.getSubject());
licenseContent.setIssued(param.getIssuedTime());
licenseContent.setNotBefore(param.getIssuedTime());
licenseContent.setNotAfter(param.getExpiryTime());
licenseContent.setConsumerType(param.getConsumerType());
licenseContent.setConsumerAmount(param.getConsumerAmount());
licenseContent.setInfo(param.getDescription());
//扩展校验服务器硬件信息
licenseContent.setExtra(param.getLicenseCheckModel());
return licenseContent;
}
}
package com.founder.servicebase.license;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @ProjectName LicenseCreatorParam
* @author Administrator
* @version 1.0.0
* @Description License生成类需要的参数
* @createTime 2022/4/30 0030 18:19
*/
@Data
public class LicenseCreatorParam implements Serializable {
private static final long serialVersionUID = -7793154252684580872L;
/**
* 证书subject
*/
private String subject;
/**
* 密钥别称
*/
private String privateAlias;
/**
* 密钥密码(需要妥善保管,不能让使用者知道)
*/
private String keyPass;
/**
* 访问秘钥库的密码
*/
private String storePass;
/**
* 证书生成路径
*/
private String licensePath;
/**
* 密钥库存储路径
*/
private String privateKeysStorePath;
/**
* 证书生效时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date issuedTime = new Date();
/**
* 证书失效时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date expiryTime;
/**
* 用户类型
*/
private String consumerType = "user";
/**
* 用户数量
*/
private Integer consumerAmount = 1;
/**
* 描述信息
*/
private String description = "";
/**
* 额外的服务器硬件校验信息
*/
private LicenseCheckModel licenseCheckModel;
}
package com.founder.servicebase.license;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.List;
import java.util.stream.Collectors;
/**
* @ProjectName LinuxServerInfos
* @author Administrator
* @version 1.0.0
* @Description 用于获取客户Linux服务器的基本信息
* @createTime 2022/4/30 0030 18:20
*/
public class LinuxServerInfos extends AbstractServerInfos {
@Override
protected List<String> getIpAddress() throws Exception {
List<String> result = null;
//获取所有网络接口
List<InetAddress> inetAddresses = getLocalAllInetAddress();
if(inetAddresses != null && inetAddresses.size() > 0){
result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList());
}
return result;
}
@Override
protected List<String> getMacAddress() throws Exception {
List<String> result = null;
//1. 获取所有网络接口
List<InetAddress> inetAddresses = getLocalAllInetAddress();
if(inetAddresses != null && inetAddresses.size() > 0){
//2. 获取所有网络接口的Mac地址
result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
}
return result;
}
@Override
protected String getCPUSerial() throws Exception {
//序列号
String serialNumber = "";
//使用dmidecode命令获取CPU序列号
String[] shell = {"/bin/bash","-c","dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"};
Process process = Runtime.getRuntime().exec(shell);
process.getOutputStream().close();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine().trim();
if(StringUtils.isNotBlank(line)){
serialNumber = line;
}
reader.close();
return serialNumber;
}
@Override
protected String getMainBoardSerial() throws Exception {
//序列号
String serialNumber = "";
//使用dmidecode命令获取主板序列号
String[] shell = {"/bin/bash","-c","dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"};
Process process = Runtime.getRuntime().exec(shell);
process.getOutputStream().close();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine().trim();
if(StringUtils.isNotBlank(line)){
serialNumber = line;
}
reader.close();
return serialNumber;
}
}
package com.founder.servicebase.license;
import java.net.InetAddress;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* @ProjectName WindowsServerInfos
* @author Administrator
* @version 1.0.0
* @Description 用于获取客户Windows服务器的基本信息
* @createTime 2022/4/30 0030 18:20
*/
public class WindowsServerInfos extends AbstractServerInfos {
@Override
protected List<String> getIpAddress() throws Exception {
List<String> result = null;
//获取所有网络接口
List<InetAddress> inetAddresses = getLocalAllInetAddress();
if(inetAddresses != null && inetAddresses.size() > 0){
result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList());
}
return result;
}
@Override
protected List<String> getMacAddress() throws Exception {
List<String> result = null;
//1. 获取所有网络接口
List<InetAddress> inetAddresses = getLocalAllInetAddress();
if(inetAddresses != null && inetAddresses.size() > 0){
//2. 获取所有网络接口的Mac地址
result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
}
return result;
}
@Override
protected String getCPUSerial() throws Exception {
//序列号
String serialNumber = "";
//使用WMIC获取CPU序列号
Process process = Runtime.getRuntime().exec("wmic cpu get processorid");
process.getOutputStream().close();
Scanner scanner = new Scanner(process.getInputStream());
if(scanner.hasNext()){
scanner.next();
}
if(scanner.hasNext()){
serialNumber = scanner.next().trim();
}
scanner.close();
return serialNumber;
}
@Override
protected String getMainBoardSerial() throws Exception {
//序列号
String serialNumber = "";
//使用WMIC获取主板序列号
Process process = Runtime.getRuntime().exec("wmic baseboard get serialnumber");
process.getOutputStream().close();
Scanner scanner = new Scanner(process.getInputStream());
if(scanner.hasNext()){
scanner.next();
}
if(scanner.hasNext()){
serialNumber = scanner.next().trim();
}
scanner.close();
return serialNumber;
}
}
#使用哪个环境的配置
spring.profiles.active=dev
#License相关配置
license.licensePath=D:/license/license.lic
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
<module>publicapi</module> <module>publicapi</module>
<module>monitoring</module> <module>monitoring</module>
<module>powerjob</module> <module>powerjob</module>
<module>licenseServer</module>
</modules> </modules>
<artifactId>service</artifactId> <artifactId>service</artifactId>
<dependencies> <dependencies>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment