将如下类复制到工程中:
为了不影响阅读,这些类的源码放在了文章末尾!!!
cd D:installjdl_8u271bin # 按顺序执行如下三个命令: # 利用jdk keytool工具制作证书: todo 该命令过时了,会在不久废弃,有时间换成最新的 keytool -genkeypair -keysize 1024 -validity 3650 -alias "project_xxx.privateKey" -keystore "project_xxx.privateKeys.keystore" -storepass "project_xxx_store_pwdxxxxxxxxxxxxxxxx" -keypass "project_xxx_key_pwdyyyyyyyyyyyyyyyyyyyyyy" -dname "CN=localhost, OU=localhost, O=localhost, L=SH, ST=SH, C=CN" # 利用jdk keytool工具导出证书文件: keytool -exportcert -alias "project_xxx.privateKey" -keystore "project_xxx.privateKeys.keystore" -storepass "project_xxx_store_pwdxxxxxxxxxxxxxxxx" -file "project_xxx.certfile.cer" # 利用jdk keytool工具将证书文件导入到证书库中: keytool -import -alias "project_xxx.publicCert" -file "project_xxx.certfile.cer" -keystore "project_xxx.publicCerts.keystore" -storepass "project_xxx_store_pwdxxxxxxxxxxxxxxxx"
执行完毕会在D:installjdl_8u271bin下生成如下三个文件:
其中 project_xxx.publicCerts.keystore 是公钥,到时候会和证书文件( 即下面要生成的 E:/license/xxx/project_xxx.license.lic )随项目一同部署到客户服务器上;project_xxx.privateKeys.keystore 是私钥,绝对不要让客户知道。
生成证书文件( E:/license/xxx/project_xxx.license.lic ):
public static void main(String[] args) {
LicenseCreatorParam param = new LicenseCreatorParam();
param.setSubject("project_xxx_license");
param.setPrivateAlias("project_xxx.privateKey");
param.setKeyPass("project_xxx_key_pwdyyyyyyyyyyyyyyyyyyyyyy");
param.setStorePass("project_xxx_store_pwdxxxxxxxxxxxxxxxx");
// 生成的证书的路径
param.setLicensePath("E:/license/xxx/project_xxx.license.lic");
# 私钥的路径
param.setPrivateKeysStorePath("D:/install/jdl_8u271/bin/project_xxx.privateKeys.keystore");
try {
Date issuedTime = new Date();
# 设置使用时间为60天
Date expiryTime = new Date(issuedTime.getTime() + 60L * 24L * 3600L * 1000L);
param.setIssuedTime( issuedTime );
param.setExpiryTime( expiryTime );
} catch (Exception e) { e.printStackTrace();}
LicenseCheckModel licenseCheckModel = new LicenseCheckModel();
List ipList = new ArrayList<>( 0 );
List macList = new ArrayList<>();
macList.add( "xx-xx-xx-xx-xx-xx" );
licenseCheckModel.setMacAddress(macList);
param.setLicenseCheckModel(licenseCheckModel);
LicenseCreator licenseCreator = new LicenseCreator(param);
licenseCreator.generateLicense();
}
在你的 bootstrap.yml中添加如下配置:
license: subject: project_xxx_license publicAlias: project_xxx.publicCert storePass: project_xxx_store_pwdxxxxxxxxxxxxxxxx licensePath: E:/license/xxx/project_xxx.license.lic #证书文件 publicKeysStorePath: E:/license/xxx/project_xxx.publicCerts.keystore #公钥
这样项目启动时会安装证书:
在请求的时候会校验证书:
如果不想安装证书,把这两个地方注释掉即可 。
涉及到的类的源码:
package xxx.intercepter;
import com.alibaba.fastjson.JSONObject;
import xxx.common.api.Result;
import xxx.license.LicenseVerify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@Component
public class LicenseInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object obj) throws Exception {
LicenseVerify licenseVerify = new LicenseVerify();
//校验证书是否有效
boolean verifyResult = licenseVerify.verify();
if(verifyResult){
return true;
}else{
// 证书校验失败
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
Result result = new Result();
result.setSuccess( false );
result.setMessage( "您的证书无效,请核查服务器是否取得授权或重新申请证书!" );
PrintWriter writer = response.getWriter();
writer.print( JSONObject.toJSONString( result ) );
writer.close();
return false;
}
}
@Override
public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object obj, Exception err) throws Exception {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,Object obj, ModelAndView mav) throws Exception {
}
}
package xxx.license.bo;
import de.schlichtherle.license.AbstractKeyStoreParam;
import lombok.Getter;
import lombok.Setter;
import java.io.*;
@Getter
@Setter
public class CustomKeyStoreParam extends AbstractKeyStoreParam {
//公钥/私钥在磁盘上的存储路径
private String storePath;
//访问秘钥库的密码
private String storePwd;
//别称
private String alias;
//密钥密码(需要妥善保管,不能让使用者知道)
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 InputStream getStream() throws IOException {
final InputStream in = new FileInputStream(new File(storePath));
if (null == in){
throw new FileNotFoundException(storePath);
}
return in;
}
}
package xxx.license.bo;
import xxx.license.os.AbstractServerInfo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import java.io.Serializable;
import java.util.List;
@Setter
@Getter
@ToString
@Slf4j
public class LicenseCheckModel implements Serializable {
// private List ipAddress;
private List macAddress;
// private String cpuSerial;
// private String mainBoardSerial;
public static LicenseCheckModel installServerInfo(AbstractServerInfo serverInfo){
LicenseCheckModel result = new LicenseCheckModel();
try {
// result.setIpAddress(serverInfo.getIpAddress());
result.setMacAddress(serverInfo.getMacAddress());
// result.setCpuSerial(serverInfo.getCPUSerial());
// result.setMainBoardSerial(serverInfo.getMainBoardSerial());
}catch (Exception e){
log.error("获取服务器硬件信息失败",e);
}
return result;
}
}
package xxx.license.bo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
public class LicenseVerifyParam {
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;
}
}
package xxx.license.creater;
import xxx.license.CustomLicenseManager;
import xxx.license.bo.CustomKeyStoreParam;
import de.schlichtherle.license.*;
import lombok.extern.slf4j.Slf4j;
import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.text.MessageFormat;
import java.util.prefs.Preferences;
@Slf4j
public class LicenseCreator {
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;
}
public boolean generateLicense() {
try {
LicenseManager licenseManager = new CustomLicenseManager(initLicenseParam());
LicenseContent licenseContent = initLicenseContent();
licenseManager.store(licenseContent, new File(param.getLicensePath()));
log.info("证书生成成功!");
return true;
} catch (Exception e) {
log.error(MessageFormat.format("证书生成失败:{0}", param), e);
return false;
}
}
private LicenseParam initLicenseParam() {
Preferences preferences = Preferences.userNodeForPackage(LicenseCreator.class);
//设置对证书内容加密的秘钥
CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
KeyStoreParam privateStoreParam = new CustomKeyStoreParam(LicenseCreator.class
, param.getPrivateKeysStorePath()
, param.getPrivateAlias()
, param.getStorePass()
, param.getKeyPass());
LicenseParam licenseParam = new DefaultLicenseParam(param.getSubject()
, preferences
, privateStoreParam
, cipherParam);
return licenseParam;
}
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 xxx.license.creater;
import com.fasterxml.jackson.annotation.JsonFormat;
import xxx.license.bo.LicenseCheckModel;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.Date;
@Setter
@Getter
public class LicenseCreatorParam implements Serializable {
private static final long serialVersionUID = -7793154252684580872L;
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 xxx.license.creater;
import com.alibaba.fastjson.JSONObject;
import xxx.license.bo.LicenseCheckModel;
import xxx.license.os.AbstractServerInfo;
import xxx.license.os.LinuxServerInfo;
import xxx.license.os.WindowsServerInfo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Test {
public static void printServerInfo(){
String osName = System.getProperty("os.name").toLowerCase();
AbstractServerInfo serverInfo;
//根据不同操作系统类型选择不同的数据获取方法
if (osName.startsWith("windows")) {
serverInfo = new WindowsServerInfo();
} else if (osName.startsWith("linux")) {
serverInfo = new LinuxServerInfo();
}else{//其他服务器类型
serverInfo = new LinuxServerInfo();
}
System.out.println( "服务器信息:" + JSONObject.toJSONString( serverInfo ) );
}
public static void main(String[] args) {
LicenseCreatorParam param = new LicenseCreatorParam();
param.setSubject("project_xxx_license");
param.setPrivateAlias("project_xxx.privateKey");
param.setKeyPass("project_xxx_key_pwdyyyyyyyyyyyyyyyyyyyyyy");
param.setStorePass("project_xxx_store_pwdxxxxxxxxxxxxxxxx");
// 生成的证书的路径
param.setLicensePath("E:/license/xxx/project_xxx.license.lic");
param.setPrivateKeysStorePath("D:/install/jdl_8u271/bin/project_xxx.privateKeys.keystore");
try {
Date issuedTime = new Date();
Date expiryTime = new Date(issuedTime.getTime() + 60L * 24L * 3600L * 1000L);
param.setIssuedTime( issuedTime );
param.setExpiryTime( expiryTime );
} catch (Exception e) { e.printStackTrace();}
LicenseCheckModel licenseCheckModel = new LicenseCheckModel();
List ipList = new ArrayList<>( 0 );
List macList = new ArrayList<>();
macList.add( "xx-xx-xx-xx-xx-xx" );
licenseCheckModel.setMacAddress(macList);
param.setLicenseCheckModel(licenseCheckModel);
LicenseCreator licenseCreator = new LicenseCreator(param);
licenseCreator.generateLicense();
}
}
package xxx.license.os;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public abstract class AbstractServerInfo {
// todo public abstract List getIpAddress() throws Exception;
public abstract List getMacAddress() throws Exception;
// todo public abstract String getCPUSerial() throws Exception;
// todo public abstract String getMainBoardSerial() throws Exception;
protected List getLocalAllInetAddress() throws Exception {
List 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.isLinkLocalAddress() && !inetAddr.isMulticastAddress()) {
result.add(inetAddr);
}
}
}
return result;
}
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 xxx.license.os;
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;
public class LinuxServerInfo extends AbstractServerInfo {
@Override
public List getMacAddress() throws Exception {
List result = null;
//1. 获取所有网络接口
List inetAddresses = getLocalAllInetAddress();
if (inetAddresses != null && inetAddresses.size() > 0) {
//2. 获取所有网络接口的Mac地址
result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
}
return result;
}
}
package xxx.license.os;
import java.net.InetAddress;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class WindowsServerInfo extends AbstractServerInfo {
@Override
public List getMacAddress() throws Exception {
List result = null;
//1. 获取所有网络接口
List inetAddresses = getLocalAllInetAddress();
if (inetAddresses != null && inetAddresses.size() > 0) {
//2. 获取所有网络接口的Mac地址
result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
}
return result;
}
}
package xxx.license;
import com.alibaba.fastjson.JSONObject;
import xxx.license.bo.LicenseCheckModel;
import xxx.license.creater.Test;
import xxx.license.os.AbstractServerInfo;
import xxx.license.os.LinuxServerInfo;
import xxx.license.os.WindowsServerInfo;
import de.schlichtherle.license.*;
import de.schlichtherle.xml.GenericCertificate;
import lombok.NoArgsConstructor;
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;
@NoArgsConstructor
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(LicenseParam param) {
super(param);
}
@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);
}
@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;
}
@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;
}
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("用户类型不能为空");
}
}
@Override
protected synchronized void validate(final LicenseContent content)
throws LicenseContentException {
//1. 首先调用父类的validate方法
super.validate(content);
//2. 然后校验自定义的License参数
//License中可被允许的参数信息
// todo 为啥为空
LicenseCheckModel expectedCheckModel = (LicenseCheckModel) content.getExtra();
System.out.println(JSONObject.toJSONString( expectedCheckModel ));
System.out.println( "服务器真实信息:" );
Test.printServerInfo();
//当前服务器真实的参数信息
LicenseCheckModel serverCheckModel = getServerInfos();
if (expectedCheckModel != null && serverCheckModel != null) {
//校验IP地址
//校验Mac地址
if (!checkIpAddress(expectedCheckModel.getMacAddress(), serverCheckModel.getMacAddress())) {
throw new LicenseContentException("当前服务器的Mac地址没在授权范围内");
}
//校验主板序列号
//校验CPU序列号
} else {
// todo win10上报错???
throw new LicenseContentException("不能获取服务器硬件信息");
}
}
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) {
e.printStackTrace();
// logger.error("XMLDecoder解析XML失败",e);
}
}
return null;
}
private LicenseCheckModel getServerInfos() {
//操作系统类型
String osName = System.getProperty("os.name").toLowerCase();
AbstractServerInfo abstractServerInfo = null;
//根据不同操作系统类型选择不同的数据获取方法
if (osName.startsWith("windows")) {
abstractServerInfo = new WindowsServerInfo();
} else if (osName.startsWith("linux")) {
abstractServerInfo = new LinuxServerInfo();
} else {//其他服务器类型
abstractServerInfo = new LinuxServerInfo();
}
return LicenseCheckModel.installServerInfo(abstractServerInfo);
}
private boolean checkIpAddress(List expectedList, List 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;
}
}
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 xxx import xxx.license.bo.LicenseVerifyParam; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component @Slf4j // public class LicenseCheckListener implements ApplicationListener{ public class LicenseCheckListener implements InitializingBean { @Value("${license.subject}") private String subject; @Value("${license.publicAlias}") private String publicAlias; @Value("${license.storePass}") private String storePass; @Value("${license.licensePath}") private String licensePath; @Value("${license.publicKeysStorePath}") private String publicKeysStorePath; @Override public void afterPropertiesSet() throws Exception { // 安装证书 this.installLicense(); } private void installLicense() { if(StringUtils.isNotBlank(licensePath)){ log.info("++++++++ 开始安装证书 ++++++++"); LicenseVerifyParam param = new LicenseVerifyParam(); param.setSubject(subject); param.setPublicAlias(publicAlias); param.setStorePass(storePass); param.setLicensePath(licensePath); param.setPublicKeysStorePath(publicKeysStorePath); LicenseVerify licenseVerify = new LicenseVerify(); //安装证书 try { licenseVerify.install(param); log.info("++++++++ 证书安装成功 ++++++++"); } catch (Exception e) { e.printStackTrace(); } } } }
package xxx.license;
import de.schlichtherle.license.LicenseManager;
import de.schlichtherle.license.LicenseParam;
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 xxx.license;
import xxx.license.bo.CustomKeyStoreParam;
import xxx.license.bo.LicenseVerifyParam;
import de.schlichtherle.license.*;
import de.schlichtherle.util.ObfuscatedString;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;
@Slf4j
public class LicenseVerify {
private static final String EXC_LICENSE_HAS_EXPIRED = (new ObfuscatedString(new long[]{1000558500458715757L, -6998261911041258483L, -5490039629745846648L, 3561172928787106880L})).toString();
public synchronized LicenseContent install(LicenseVerifyParam param) throws Exception {
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()));
log.info(MessageFormat.format("证书安装成功,证书有效期:{0} - {1}", format.format(result.getNotBefore()), format.format(result.getNotAfter())));
} catch (LicenseContentException lce) {
if(EXC_LICENSE_HAS_EXPIRED.equals(lce.getMessage())) {
log.error("证书安装失败,证书已过期!");
} else {
log.error("证书安装失败!", lce);
}
throw lce;
} catch (Exception e) {
log.error("证书安装失败!", e);
throw e;
}
return result;
}
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());
log.debug(MessageFormat.format("证书校验通过,证书有效期:{0} - {1}",format.format(licenseContent.getNotBefore()),format.format(licenseContent.getNotAfter())));
return true;
} catch (Exception e) {
log.error("证书校验失败!",e);
return false;
}
}
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);
}
}



