客户端的代码在项目启动时在指定路径下检测是否存在license认证文件,若果存在则进行安装;在登录接口以及系统核心接口处处添加认证标识,同时添加license文件认证拦截器进行拦截验证。
服务端负责生成license认证文件,生成后部署到客户端指定的路径下。
2.1使用jdk中keytool 工具生成秘钥对
以下命令在 window cmd 命令窗口执行,注意当前执行目录,最后生成的密钥对即在该目录下:
1、首先要用 KeyTool 工具来生成私匙库:(-alias别名 -validity 3650 表示10年有效)
keytool -genkey -alias privatekey -keysize 1024 -keystore privateKeys.store -validity 3650
2、然后把私匙库内的证书导出到一个文件当中
keytool -export -alias privatekey -file certfile.cer -keystore privateKeys.store
3、然后再把这个证书文件导入到公匙库
keytool -import -alias publiccert -file certfile.cer -keystore publicCerts.store
最后生成的文件 privateKeys.store(私钥)、publicCerts.store(公钥)拷贝出来备用。
2.2服务端代码实现
参考链接:https://gitee.com/zifangsky/LicenseDemo/tree/master/ServerDemo
2.3客户端代码实现
参考链接:https://gitee.com/zifangsky/LicenseDemo/tree/master/ClientDemo
https://gitee.com/zifangsky/LicenseDemo
4.1在pom文件中添加核心依赖
de.schlichtherle.truelicense
truelicense-core
1.33
provided
4.2校验自定义的license参数
TrueLicense的 de.schlichtherle.license.LicenseManager 类自带的verify方法只校验了我们后面颁发的许可文件的生效和过期时间,然而在实际项目中我们可能需要额外校验应用部署的服务器的IP地址、MAC地址、CPU序列号、主板序列号等信息,因此我们需要复写框架的部分方法以实现校验自定义参数的目的。
首先需要添加一个自定义的可被允许的服务器硬件信息的实体类(如果校验其他参数,可自行补充):
package cn.zifangsky.license;
import java.io.Serializable;
import java.util.List;
/**
* 自定义需要校验的License参数
*
* @author zifangsky
* @date 2018/4/23
* @since 1.0.0
*/
public class LicenseCheckModel implements Serializable{
private static final long serialVersionUID = 8600137500316662317L;
/**
* 可被允许的IP地址
*/
private List ipAddress;
/**
* 可被允许的MAC地址
*/
private List macAddress;
/**
* 可被允许的CPU序列号
*/
private String cpuSerial;
/**
* 可被允许的主板序列号
*/
private String mainBoardSerial;
//省略setter和getter方法
@Override
public String toString() {
return "LicenseCheckModel{" +
"ipAddress=" + ipAddress +
", macAddress=" + macAddress +
", cpuSerial='" + cpuSerial + '\'' +
", mainBoardSerial='" + mainBoardSerial + '\'' +
'}';
}
}
注意
自定义的license参数类路径必须和客户端license参数类路径相同,否则客户端在进行证书安装时会出现ClassNotFind
4.3添加license生成类需要的参数
package cn.zifangsky.license;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
/**
* License生成类需要的参数
*
* @author zifangsky
* @date 2018/4/19
* @since 1.0.0
*/
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;
//省略setter和getter方法
@Override
public String toString() {
return "LicenseCreatorParam{" +
"subject='" + subject + '\'' +
", privateAlias='" + privateAlias + '\'' +
", keyPass='" + keyPass + '\'' +
", storePass='" + storePass + '\'' +
", licensePath='" + licensePath + '\'' +
", privateKeysStorePath='" + privateKeysStorePath + '\'' +
", issuedTime=" + issuedTime +
", expiryTime=" + expiryTime +
", consumerType='" + consumerType + '\'' +
", consumerAmount=" + consumerAmount +
", description='" + description + '\'' +
", licenseCheckModel=" + licenseCheckModel +
'}';
}
}
4.4添加抽象类AbstractServerInfos,用户获取服务器的硬件信息
package cn.zifangsky.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;
/**
* 用于获取客户服务器的基本信息,如:IP、Mac地址、CPU序列号、主板序列号等
*
* @author zifangsky
* @date 2018/4/23
* @since 1.0.0
*/
public abstract class AbstractServerInfos {
private static Logger logger = LogManager.getLogger(AbstractServerInfos.class);
/**
* 组装需要额外校验的License参数
* @author zifangsky
* @date 2018/4/23 14:23
* @since 1.0.0
* @return demo.LicenseCheckModel
*/
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;
}
/**
* 获取IP地址
* @author zifangsky
* @date 2018/4/23 11:32
* @since 1.0.0
* @return java.util.List
*/
protected abstract List<String> getIpAddress() throws Exception;
/**
* 获取Mac地址
* @author zifangsky
* @date 2018/4/23 11:32
* @since 1.0.0
* @return java.util.List
*/
protected abstract List<String> getMacAddress() throws Exception;
/**
* 获取CPU序列号
* @author zifangsky
* @date 2018/4/23 11:35
* @since 1.0.0
* @return java.lang.String
*/
protected abstract String getCPUSerial() throws Exception;
/**
* 获取主板序列号
* @author zifangsky
* @date 2018/4/23 11:35
* @since 1.0.0
* @return java.lang.String
*/
protected abstract String getMainBoardSerial() throws Exception;
/**
* 获取当前服务器所有符合条件的InetAddress
* @author zifangsky
* @date 2018/4/23 17:38
* @since 1.0.0
* @return java.util.List
*/
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;
}
/**
* 获取某个网络接口的Mac地址
* @author zifangsky
* @date 2018/4/23 18:08
* @since 1.0.0
* @param
* @return void
*/
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;
}
}
5.5获取客户Linux服务器的基本信息
package cn.zifangsky.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;
/**
* 用于获取客户Linux服务器的基本信息
*
* @author zifangsky
* @date 2018/4/23
* @since 1.0.0
*/
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;
}
}
5.6获取客户Windows服务器的基本信息:
package cn.zifangsky.license;
import java.net.InetAddress;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* 用于获取客户Windows服务器的基本信息
*
* @author zifangsky
* @date 2018/4/23
* @since 1.0.0
*/
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;
}
}