阿里孩舞 / 幂等了吗?赛博炼丹与生活支线 · AI alchemy, side quests and legacy code
紫色调铠甲女性持剑的角色插画

古法编程 2022年12月31日 · 23 分钟 · JAVA

SpringBoot集成TrueLicense实现授权管理

记录 SpringBoot 集成 TrueLicense 的授权模块实现,涵盖密钥库与证书生成、License 创建和校验、服务器硬件信息绑定、拦截器及启动验证,并附配置与请求示例。

文中配图可点击放大查看原始大小,再点一次缩回屏幕大小。

前言

之前做低代码平台,为了保护平台知识产权,需要对低代码平台增加授权管理功能。功能已经实现好久了,最近梳理总结。所谓授权(License)就是对软件使用时间及使用范围进行管控,初步想法是校验部署机器特征码并添加时间范围校验,调研许久发现TrueLicense方案比较成熟,SO 安排~

一、公钥、私钥及证书

在互联网通信中,为了保证信息传输的安全,通常使用对称秘钥、非对称秘钥以及密码散列函数的方式对通信信息进行加密以及通信身份进行验证。对称秘钥即通信双方使用相同的秘钥对通信内容进行加密,这种方式应该是比较老旧的通信加密方式,通信安全程度较低。现在使用的较多的应该是非对称加密,每个人有自己的私钥,然后拥有授权的公钥。每人可以利用自己的私钥对要发送的信息进行加密,然后接受者通过发送者的公钥对信息进行解密。可以类比信箱,拥有公钥的人,可以向 信箱投送信件,拥有私钥的人可以打开信箱,读取信件。 在这种通信方式中,可能存在C偷偷将B持有的A公钥换成自己的公钥,而B不知道自己拥有的A的公钥已经被替换,那么C就可以冒充A给B发送信息,而B相信此信息来自A。为了解决这个问题,需要对B持有的A的公钥进行认证,从而确定此公钥确实是A的公钥,而不是被别人篡改过的。而认证机构必须是第三方可信赖的机构,就是CA,由此发送过程就变成如下:

  1. A发给B数据的时候,除了要发送签名和数据实体,还要发送CA颁发的证书。
  2. B接收到A发送过来的数据后,首先用CA的公钥区解密证书,如果能解,表明这个证书里的信息可信赖,从而得到证书里A的公钥,然后B再用到后的公钥去做下一步动作。

综上,我们就有实现思路了:在Truelicense中,license将和公钥一起发送给被授权者,在程序中,使用公钥对license进行解密,并校验其许可信息。

二、使用Java自带的KeyTool生成公私钥库

Keytool 是一个Java 数据证书的管理工具 ,Keytool 将密钥(key)和证书(certificates)存在一个称为keystore的文件中 在keystore里,包含两种数据: 密钥条目(Key entity)——密钥(secret key)又或者是私钥和配对公钥(采用非对称加密) 可信任的证书实体(trusted certificate entries)——只包含公钥

1、生成秘钥库

anchor@Alihaiwu > ~/Downloads/KeyTool> keytool -genkey -alias privatekeys -keysize 1024 -keystore privateKeys.store -validity 3650 # -alias别名 –validity 3650表示10年有效
输入密钥库口令:  #密码,注意使用字母+数字,否则后期校验会抛异常
再次输入新口令: 
您的名字与姓氏是什么?
  [Unknown]:  Anchor
您的组织单位名称是什么?
  [Unknown]:  Alihai5
您的组织名称是什么?
  [Unknown]:  阿里孩舞
您所在的城市或区域名称是什么?
  [Unknown]:  beijing
您所在的省/市/自治区名称是什么?
  [Unknown]:  beijing
该单位的双字母国家/地区代码是什么?
  [Unknown]:  cn
CN=Anchor, OU=Alihai5, O=阿里孩舞, L=beijing, ST=beijing, C=cn是否正确?
  [否]:  y

输入 <privatekeys> 的密钥口令
        (如果和密钥库口令相同, 按回车):  #密码,注意使用字母+数字,否则后期校验会抛异常
再次输入新口令: 

Warning:
JKS 密钥库使用专用格式,建议使用 "keytool -importkeystore -srckeystore privateKeys.store -destkeystore privateKeys.store -deststoretype pkcs12" 迁移到行业标准格式 PKCS12

2、导出证书及私钥

# 然后将密钥库中名称为privatekeys的证书条目导出到证书文件certfile.cer中
keytool -export -alias privatekeys -file certfile.cer -keystore privateKeys.store
输入密钥库口令:  #输入第一步创建秘钥库时使用的密码
存储在文件 <certfile.cer> 中的证书

Warning:
JKS 密钥库使用专用格式,建议使用 "keytool -importkeystore -srckeystore privateKeys.store -destkeystore privateKeys.store -deststoretype pkcs12" 迁移到行业标准格式 PKCS12

3、导出公钥

anchor@Alihaiwu > ~/Downloads/KeyTool> keytool -import -alias publicCerts -file certfile.cer -keystore publicCerts.store
输入密钥库口令:  #输入秘钥密码
再次输入新口令: 
所有者: CN=Anchor, OU=Alihai5, O=阿里孩舞, L=beijing, ST=beijing, C=cn
发布者: CN=Anchor, OU=Alihai5, O=阿里孩舞, L=beijing, ST=beijing, C=cn
序列号: 731c7b1b
有效期为 Wed Jan 04 13:08:18 CST 2023 至 Sat Jan 01 13:08:18 CST 2033
证书指纹:
         MD5:  E2:7E:AE:07:6C:74:50:CD:08:BF:68:74:79:84:27:66
         SHA1: C9:52:ED:A6:A2:97:FC:4A:23:97:0B:C2:85:42:D3:3A:60:E5:D5:83
         SHA256: 88:A7:0C:5E:78:1B:B1:3E:7B:6F:F9:93:99:FE:24:5F:4F:21:C7:8D:FB:2D:49:F2:FB:92:F6:2A:B4:80:C9:3D
签名算法名称: SHA256withDSA
主体公共密钥算法: 1024 位 DSA 密钥
版本: 3

扩展: 

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 57 25 93 29 B5 7D 87 0B   BA F8 B3 A4 CE 25 51 82  W%.).........%Q.
0010: 58 BD 29 C4                                        X.).
]
]

是否信任此证书? [否]:  y
证书已添加到密钥库中

按以上步骤执行完成后,会在当前目录下生成3个文件:

anchor@Alihaiwu > ~/Downloads/KeyTool> ll
total 24
-rw-r--r--  1 anchor  staff   827B Jan  4 13:14 certfile.cer #此为临时文件可以删除
-rw-r--r--  1 anchor  staff   1.3K Jan  4 13:08 privateKeys.store #此为私钥,用于生成License文件
-rw-r--r--  1 anchor  staff   895B Jan  4 13:16 publicCerts.store #此为公钥,用于解密License文件并校验其许可信息

三、TrueLicense

TrueLicense是一个开源的证书管理引擎,使用trueLicense来做软件产品的保护,基于TrueLicense实现产品License验证功能,给产品加上License验证功能,进行试用期授权,在试用期过后,产品不再可用。其实现原理:

  1. 生成秘钥对,使用Keytool生成公私钥证书库。
  2. 授权者保留私钥,使用私钥对包含授权信息(如使用截止日期,MAC地址等)的license进行数字签名。
  3. 公钥给使用者(放在验证的代码中使用),用于验证license是否符合使用条件。

四、SpringBoot集成TrueLicense实现

先上整体代码结构,因为使用场景是为低代码开发平台增加授权,所以整个授权逻辑为平台中的一个模块,此处仅介绍授权模块的实现,了解原理后可自行扩展集成入其他框架中:

  • license-boot-start 模块为授权验证模块,兼具授权文件生成接口功能,内部使用
  • license-core 模块为授权校验核心处理模块
  • license-creator 模块为授权License生成模块
  • license-verify 模块为授权校验模块

在此之前先在项目中引入TrueLicense包:

<!-- truelicense的依赖配置-->
<dependency>
    <groupId>de.schlichtherle.truelicense</groupId>
    <artifactId>truelicense-core</artifactId>
    <version>1.33</version>
</dependency>

1、license-core

还是先上代码结构,由于creator与verify模块license生成与校验逻辑一致,所以抽取出来作为core模块使用,注释比较详细,直接看代码:

config

LicenseCoreAutoConfigure
/**
* @program: groot-license
* @description:自动装填配置类
* @author: Anchor
* @create: 2021-09-01
**/
@Configuration
    @ComponentScan(basePackages = {"com.alihai5.license.core"})
    public class LicenseCoreAutoConfigure {

    }

controller

HardWareInfoController
/**
 * @program: groot-license
 * @description: 服务器硬件信息获取
 * @author: Anchor
 * @create: 2021-09-01
 **/
@CrossOrigin
@RestController
@RequestMapping("/license")
public class HardWareInfoController {

    @RequestMapping(value = "/getServerInfos")
    public AjaxResult getServerInfos(@RequestParam(value = "osName",required = false) String osName) throws LicenseContentException {
        return AjaxResult.success(AServerInfos.getServer(osName).getServerInfos());
    }
}

helper

ParamInitHelper
/**
 * @Description
 * GxParamInitHelper
 * @author Anchor
 * @Date 2021/9/1
*/
public class ParamInitHelper {

    /** 证书的发行者和主体字段信息 */
    private final static X500Principal DEFAULT_HOLDER_AND_ISSUER = new X500Principal("CN=a, OU=a, O=a, L=a, ST=a, C=a");

    /**
     * <p>初始化证书生成参数</p>
     * @param param GxLicenseCreatorParam 生成证书参数
     * @return LicenseParam 证书参数
     */
    public static LicenseParam initLicenseParam(LicenseCreatorParam param){
        Preferences preferences = Preferences.userNodeForPackage(LicenseCreator.class);
        /** 设置对证书内容加密的秘钥 */
        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
        KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(LicenseCreator.class
                ,param.getPrivateKeysStorePath()
                ,param.getPrivateAlias()
                ,param.getStorePass()
                ,param.getKeyPass());
        return new DefaultLicenseParam(param.getSubject(),preferences,privateStoreParam,cipherParam);
    }

    /**
     * <p>初始化证书内容信息对象</p>
     * @param param GxLicenseCreatorParam 生成证书参数
     * @return LicenseContent 证书内容
     */
    public static LicenseContent initLicenseContent(LicenseCreatorParam param){
        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());
        /** 设置证书扩展信息(对象 -- 额外的ip、mac、cpu等信息) */
        licenseContent.setExtra(param.getLicenseCheck());
        return licenseContent;
    }

    /**
     * <p>初始化证书生成参数</p>
     * @param param License校验类需要的参数
     */
    public static LicenseParam initLicenseParam(LicenseVerifyParam param){
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerifyManager.class);
        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
        KeyStoreParam publicStoreParam = new DefaultKeyStoreParam(LicenseVerifyManager.class
                /** 公钥库存储路径 */
                ,param.getPublicKeysStorePath()
                /** 公匙别名 */
                ,param.getPublicAlias()
                /** 公钥库访问密码 */
                ,param.getStorePass()
                ,null);
        return new DefaultLicenseParam(param.getSubject(),preferences,publicStoreParam,cipherParam);
    }
}

model

LicenseCreatorManager
/**
 * @Description
 * 系统软件证书生成管理器
 * @author Anchor
 * @Date 2021/9/1
*/
public class LicenseCreatorManager {

    private static final Logger log = LoggerFactory.getLogger(LicenseCreatorManager.class);

    private LicenseCreatorParam param;

    public LicenseCreatorManager(LicenseCreatorParam param) {
        this.param = param;
    }

    /**
     * <p>生成License证书</p>
     * @return GxLicenseResult 证书生成结果
     */
    public LicenseResult generateLicense(){
        try {
            // 1、根据外部传入的创建Lic的参数信息初始化lic参数(秘钥部分)
            LicenseParam licenseParam = ParamInitHelper.initLicenseParam(param);
            // 2、根据外部传入的创建Lic的属性信息初始化lic内容(除了truelicense自带的还包括自己定义的)
            LicenseContent licenseContent = ParamInitHelper.initLicenseContent(param);
            // 3、构建Lic管理器
            LicenseManager licenseManager = new LicenseCustomManager(licenseParam);
            // 4、根据param传入的lic生成的路径创建空文件
            File licenseFile = new File(this.param.getLicensePath());
            // 5、通过Lic管理器,将内容写入Lic文件中
            licenseManager.store(licenseContent, licenseFile);
            return new LicenseResult("证书生成成功!",licenseContent);
        }catch (Exception e){
            log.error(e.getMessage());
            String message = MessageFormat.format("证书生成失败!:{0}", param);
            log.error(message,e);
            return new LicenseResult(message,e);
        }
    }

    /**
     * <p>下载License证书</p>
     * @return InputStream 证书文件输入流
     * @throws Exception 证书下载失败
     */
    public InputStream download() throws Exception {
        try {
            LicenseParam licenseParam = ParamInitHelper.initLicenseParam(param);
            LicenseContent licenseContent = ParamInitHelper.initLicenseContent(param);
            LicenseManager licenseManager = new LicenseCustomManager(licenseParam);
            File licenseFile = new File(param.getLicensePath());
            licenseManager.store(licenseContent,licenseFile);
            return new FileInputStream(licenseFile);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            log.error(MessageFormat.format("证书下载失败:{0}",param),e);
            throw new UtilException("证书下载失败",e);
        }
    }

}
LicenseCreatorParam
/**
 * @Description
 * License创建(生成)需要的参数
 * @author Anchor
 * @Date 2021/9/1
*/
public class LicenseCreatorParam implements Serializable {

    private static final long serialVersionUID = -7793154252684580872L;

    /**证书主题*/
    private String subject;

    /**私钥别名*/
    private String privateAlias;

    /**私钥密码(需要妥善保管,不能让使用者知道*/
    private String keyPass;

    /**私钥库存储路径*/
    private String privateKeysStorePath;

    /**访问私钥库的密码*/
    private String storePass;

    /**证书生成路径*/
    private String licensePath;

    /** 证书生效时间*/
    @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 LicenseExtraParam licenseCheck;

    /**证书下载地址 == 一旦证书create成功,这个值就会填充上*/
    private String licUrl;

    public LicenseCreatorParam(){

    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getPrivateAlias() {
        return privateAlias;
    }

    public void setPrivateAlias(String privateAlias) {
        this.privateAlias = privateAlias;
    }

    public String getKeyPass() {
        return keyPass;
    }

    public void setKeyPass(String keyPass) {
        this.keyPass = keyPass;
    }

    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 getPrivateKeysStorePath() {
        return privateKeysStorePath;
    }

    public void setPrivateKeysStorePath(String privateKeysStorePath) {
        this.privateKeysStorePath = privateKeysStorePath;
    }

    public Date getIssuedTime() {
        return issuedTime;
    }

    public void setIssuedTime(Date issuedTime) {
        this.issuedTime = issuedTime;
    }

    public Date getExpiryTime() {
        return expiryTime;
    }

    public void setExpiryTime(Date expiryTime) {
        this.expiryTime = expiryTime;
    }

    public String getConsumerType() {
        return consumerType;
    }

    public void setConsumerType(String consumerType) {
        this.consumerType = consumerType;
    }

    public Integer getConsumerAmount() {
        return consumerAmount;
    }

    public void setConsumerAmount(Integer consumerAmount) {
        this.consumerAmount = consumerAmount;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public LicenseExtraParam getLicenseCheck() {
        return licenseCheck;
    }

    public void setLicenseCheck(LicenseExtraParam licenseCheck) {
        this.licenseCheck = licenseCheck;
    }

    public String getLicUrl() {
        return licUrl;
    }

    public void setLicUrl(String licUrl) {
        this.licUrl = licUrl;
    }

    @Override
    public String toString() {
        return "LicenseCreatorParam{" +
                "subject='" + subject + '\'' +
                ", privateAlias='" + privateAlias + '\'' +
                ", keyPass='" + keyPass + '\'' +
                ", privateKeysStorePath='" + privateKeysStorePath + '\'' +
                ", storePass='" + storePass + '\'' +
                ", licensePath='" + licensePath + '\'' +
                ", issuedTime=" + issuedTime +
                ", expiryTime=" + expiryTime +
                ", consumerType='" + consumerType + '\'' +
                ", consumerAmount=" + consumerAmount +
                ", description='" + description + '\'' +
                ", licenseCheck=" + licenseCheck +
                ", licUrl='" + licUrl + '\'' +
                '}';
    }
}
LicenseCustomManager
/**
 * @Description
 * 自定义LicenseManager,用于增加额外的服务器硬件信息校验
 * @author Anchor
 * @Date 2021/9/1
*/
public class LicenseCustomManager extends LicenseManager {

    private static final Logger log = LoggerFactory.getLogger(LicenseCustomManager.class);

    /** XML编码 */
    private static final String XML_CHARSET = "UTF-8";
    /** 默认BUFF_SIZE */
    private static final int DEFAULT_BUFF_SIZE = 8 * 1024;

    public LicenseCustomManager() {
    }

    public LicenseCustomManager(LicenseParam param) {
        super(param);
    }

    /**
     * <p>重写LicenseManager的create方法</p>
     * @param content LicenseContent 证书信息
     * @param notary notary 公正信息
     * @return byte[]
     * @throws Exception 默认异常
     */
    @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);
    }


    /**
     * <p>重写install方法</p>
     * @param key 密匙
     * @param notary 公正信息
     * @return LicenseContent 证书信息
     * @throws Exception 默认异常
     */
    @Override
    protected synchronized LicenseContent install(final byte[] key, final LicenseNotary notary) throws Exception {
        final GenericCertificate certificate = getPrivacyGuard().key2cert(key);
        notary.verify(certificate);
        final LicenseContent licenseContent = (LicenseContent)this.load(certificate.getEncoded());
        /** 增加额外的自己的license校验方法,校验ip、mac、cpu序列号等 */
        this.validate(licenseContent);
        setLicenseKey(key);
        setCertificate(certificate);
        return licenseContent;
    }

    /**
     * <p>重写verify方法</p>
     * @param notary 公正信息
     * @return LicenseContent 证书信息
     * @throws Exception 默认异常
     */
    @Override
    protected synchronized LicenseContent verify(final LicenseNotary notary) throws Exception {
        final byte[] key = getLicenseKey();
        if (null == key){
            throw new NoLicenseInstalledException(getLicenseParam().getSubject());
        }
        GenericCertificate certificate = getPrivacyGuard().key2cert(key);
        notary.verify(certificate);
        final LicenseContent content = (LicenseContent)this.load(certificate.getEncoded());
        /** 增加额外的自己的license校验方法,校验ip、mac、cpu序列号等 */
        this.validate(content);
        setCertificate(certificate);
        return content;
    }

    /**
     * <p>校验生成证书的参数信息</p>
     * @param content LicenseContent 证书内容
     * @throws LicenseContentException 证书内容错误异常
     */
    protected synchronized void validateCreate(final LicenseContent content) throws LicenseContentException {

        // 当前时间
        final Date now = new Date();
        // 生效时间
        final Date notBefore = content.getNotBefore();
        // 失效时间
        final Date notAfter = content.getNotAfter();

        if (null != notAfter && now.after(notAfter)){
            String message = "证书失效时间不能早于当前时间";
            log.error(message);
            throw new LicenseContentException(message);
        }
        if (null != notBefore && null != notAfter && notAfter.before(notBefore)){
            String message = "证书生效时间不能晚于证书失效时间";
            log.error(message);
            throw new LicenseContentException(message);
        }
        final String consumerType = content.getConsumerType();
        if (null == consumerType){
            String message = "用户类型不能为空";
            log.error(message);
            throw new LicenseContentException(message);
        }

    }

    /**
     * <p>重写validate方法,增加ip地址、mac地址、cpu序列号等其他信息的校验</p>
     * @param content LicenseContent 证书内容
     */
    @Override
    protected synchronized void validate(final LicenseContent content) throws LicenseContentException {
        // 当前时间
        final Date now = new Date();
        final Date notAfter = content.getNotAfter();
        if(now.after(notAfter)){
            throw new LicenseContentException("系统证书过期,当前时间已超过证书有效期 -- "+
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,notAfter));
        }
        //1、 首先调用父类的validate方法
        super.validate(content);
        //2、 然后校验自定义的License参数 License中可被允许的参数信息
        LicenseExtraParam expectedCheck = (LicenseExtraParam) content.getExtra();
        //当前服务器真实的参数信息
        LicenseExtraParam serverCheckModel = AServerInfos.getServer(null).getServerInfos();
        if(expectedCheck != null && serverCheckModel != null){
            //校验IP地址
            if(expectedCheck.isIpCheck() && !checkIpAddress(expectedCheck.getIpAddress(),serverCheckModel.getIpAddress())){
                String message = "系统证书无效,当前服务器的IP没在授权范围内";
                log.error(message);
                throw new LicenseContentException(message);
            }
            //校验Mac地址
            if(expectedCheck.isMacCheck() && !checkIpAddress(expectedCheck.getMacAddress(),serverCheckModel.getMacAddress())){
                String message = "系统证书无效,当前服务器的Mac地址没在授权范围内";
                log.error(message);
                throw new LicenseContentException(message);
            }
            //校验主板序列号
            if(expectedCheck.isBoardCheck() && !checkSerial(expectedCheck.getMainBoardSerial(),serverCheckModel.getMainBoardSerial())){
                String message = "系统证书无效,当前服务器的主板序列号没在授权范围内";
                log.error(message);
                throw new LicenseContentException(message);
            }
            //校验CPU序列号
            if(expectedCheck.isCpuCheck() && !checkSerial(expectedCheck.getCpuSerial(),serverCheckModel.getCpuSerial())){
                String message = "系统证书无效,当前服务器的CPU序列号没在授权范围内";
                log.error(message);
                throw new LicenseContentException(message);
            }
        }else{
            throw new LicenseContentException("不能获取服务器硬件信息");
        }
    }

    /**
     * <p>重写XMLDecoder解析XML</p>
     */
    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_BUFF_SIZE),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) {
                log.error("XMLDecoder解析XML失败",e);
            }
        }
        return null;

    }

    /**
     * <p>
     *     校验当前服务器的IP/Mac地址是否在可被允许的IP范围内<br/>
     *     如果存在IP在可被允许的IP/Mac地址范围内,则返回true
     * </p>
     *
     */
    private boolean checkIpAddress(List<String> expectedList, List<String> serverList){

        /** 如果期望的IP列表空直接返回false,因为既然验证ip,这一项必须要有元素 */
        if(CommonUtils.isEmpty(expectedList)){
            return false ;
        }
        /** 如果当前服务器的IP列表空直接返回false,因为服务器不可能获取不到ip,没有的话验证个锤子 */
        if(CommonUtils.isEmpty(serverList)){
            return false ;
        }
        for(String expected : expectedList){
            if(serverList.contains(expected.trim())){
                return true;
            }
        }
        return false;

    }

    /**
     * <p>校验当前服务器硬件(主板、CPU等)序列号是否在可允许范围内</p>
     * @param expectedSerial 主板信息
     * @param serverSerial 服务器信息
     * @return boolean
     */
    private boolean checkSerial(String expectedSerial, String serverSerial){
        if(CommonUtils.isNotEmpty(expectedSerial)){
            if(CommonUtils.isNotEmpty(serverSerial)){
                return expectedSerial.equals(serverSerial);
            }
            return false;
        }else{
            return true;
        }
    }
}
LicenseExtraParam
/**
* @Description
* 自定义需要校验的License参数
* @author Anchor
* @Date 2021/9/1
*/
public class LicenseExtraParam implements Serializable {

    private static final long serialVersionUID = 8600137500316662317L;

    /** 是否认证ip*/
    private boolean isIpCheck ;

    /** 可被允许的IP地址*/
    private List<String> ipAddress;

    /**是否认证mac*/
    private boolean isMacCheck ;

    /** 可被允许的mac地址*/
    private List<String> macAddress;

    /**是否认证cpu序列号*/
    private boolean isCpuCheck ;

    /** 可被允许的CPU序列号*/
    private String cpuSerial;

    /** 是否认证主板号*/
    private boolean isBoardCheck ;

    /**可被允许的主板序列号*/
    private String mainBoardSerial;

    /** 是否限制注册人数*/
    private boolean isRegisterCheck;

    /** 限制系统中可注册的人数*/
    private Long registerAmount;

    /**其他可自行扩展字段*/

    public LicenseExtraParam(){

    }

    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;
    }

    public boolean isIpCheck() {
        return isIpCheck;
    }

    public void setIpCheck(boolean ipCheck) {
        isIpCheck = ipCheck;
    }

    public boolean isMacCheck() {
        return isMacCheck;
    }

    public void setMacCheck(boolean macCheck) {
        isMacCheck = macCheck;
    }

    public boolean isCpuCheck() {
        return isCpuCheck;
    }

    public void setCpuCheck(boolean cpuCheck) {
        isCpuCheck = cpuCheck;
    }

    public boolean isBoardCheck() {
        return isBoardCheck;
    }

    public void setBoardCheck(boolean boardCheck) {
        isBoardCheck = boardCheck;
    }

    public Long getRegisterAmount() {
        return registerAmount;
    }

    public void setRegisterAmount(Long registerAmount) {
        this.registerAmount = registerAmount;
    }

    public boolean isRegisterCheck() {
        return isRegisterCheck;
    }

    public void setRegisterCheck(boolean registerCheck) {
        isRegisterCheck = registerCheck;
    }

    @Override
    public String toString() {
        return "LicenseExtraParam{" +
            "ipAddress=" + ipAddress +
            ", macAddress=" + macAddress +
            ", cpuSerial='" + cpuSerial + '\'' +
            ", mainBoardSerial='" + mainBoardSerial + '\'' +
            ", registerAmount='" + registerAmount + '\'' +
            '}';
    }
}
LicenseResult
/**
 * @Description
 * License证书验证结果对象
 * @author Anchor
 * @Date 2021/9/1
*/
public class LicenseResult {

    /** 检验结果 */
    private Boolean result;
    /** 附加信息 */
    private String message;
    /** 证书内容 */
    private LicenseContent content;
    /** 检验失败错误 */
    private Exception exception;

    public LicenseResult(LicenseContent content) {
        this.result = true;
        this.content = content;
    }

    public LicenseResult(String message, LicenseContent content) {
        this.result = true;
        this.message = message;
        this.content = content;
    }

    public LicenseResult(Exception exception) {
        this.result = false;
        this.exception = exception;
    }

    public LicenseResult(String message, Exception exception) {
        this.result = false;
        this.message = message;
        this.exception = exception;
    }

    public LicenseResult(boolean result , String message, Exception exception) {
        this.result = result;
        this.message = message;
        this.exception = exception;
    }

    public Boolean getResult() {
        return result;
    }

    public void setResult(Boolean result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public LicenseContent getContent() {
        return content;
    }

    public void setContent(LicenseContent content) {
        this.content = content;
    }

    public Exception getException() {
        return exception;
    }

    public void setException(Exception exception) {
        this.exception = exception;
    }
}
LicenseVerifyManager
/**
 * @Description
 * License校验类
 * @author Anchor
 * @Date 2021/9/1
*/
public class LicenseVerifyManager {

    private static final Logger log = LoggerFactory.getLogger(LicenseVerifyManager.class);

    /**
     * <p>安装License证书</p>
     * @param param License校验类需要的参数
     */
    public synchronized LicenseResult install(LicenseVerifyParam param){
        try{
            /** 1、初始化License证书参数 */
            LicenseParam licenseParam = ParamInitHelper.initLicenseParam(param);
            /** 2、创建License证书管理器对象 */
//          LicenseManager licenseManager =new LicenseManager(licenseParam);
            //走自定义的Lic管理
            LicenseCustomManager licenseManager = new LicenseCustomManager(licenseParam);
            /** 3、获取要安装的证书文件 */
            File licenseFile = ResourceUtils.getFile(param.getLicensePath());
            /** 4、如果之前安装过证书,先卸载之前的证书 == 给null */
            licenseManager.uninstall();
            /** 5、开始安装 */
            LicenseContent content = licenseManager.install(licenseFile);
            String message = MessageFormat.format("证书安装成功,证书有效期:{0} - {1}",
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,content.getNotBefore()),
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,content.getNotAfter()));
            log.info(message);
            return new LicenseResult(message,content);
        }catch (LicenseContentException contentExc){
            String message = contentExc.getMessage();
            log.error(message);
            return new LicenseResult(false,message,contentExc);
        } catch (Exception e){
            log.error(e.getMessage(),e);
            return new LicenseResult(false,e.getMessage(),e);
        }
    }

    /**
     * <p>校验License证书</p>
     * @param param License校验类需要的参数
     */
    public LicenseResult verify(LicenseVerifyParam param){

        /** 1、初始化License证书参数 */
        LicenseParam licenseParam = ParamInitHelper.initLicenseParam(param);
        /** 2、创建License证书管理器对象 */
        LicenseManager licenseManager = new LicenseCustomManager(licenseParam);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        /** 3、开始校验证书 */
        try {
            LicenseContent licenseContent = licenseManager.verify();
            String message = MessageFormat.format("证书校验通过,证书有效期:{0} - {1}",
                    format.format(licenseContent.getNotBefore()),format.format(licenseContent.getNotAfter()));
            log.info(message);
            return new LicenseResult(message,licenseContent);
        }catch (NoLicenseInstalledException ex){
            String message = "证书未安装!";
            log.error(message,ex);
            return new LicenseResult(false,message,ex);
        }catch (LicenseContentException cex){
            log.error(cex.getMessage(),cex);
            return new LicenseResult(false,cex.getMessage(),cex);
        } catch (Exception e){
            String message = "证书校验失败!";
            log.error(message,e);
            return new LicenseResult(false,message,e);
        }
    }


}
LicenseVerifyParam
/**
 * @Description
 * License校验类需要的参数
 * @author Anchor
 * @Date 2021/9/1
*/
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;
    }

    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;
    }

    @Override
    public String toString() {
        return "LicenseVerifyParam{" +
                "subject='" + subject + '\'' +
                ", publicAlias='" + publicAlias + '\'' +
                ", storePass='" + storePass + '\'' +
                ", licensePath='" + licensePath + '\'' +
                ", publicKeysStorePath='" + publicKeysStorePath + '\'' +
                '}';
    }
}

service

AServerInfos
/**
 * @Description
 * 服务器硬件信息抽象类 -- 模板方法,将通用的方法抽离到父类中
 * @author Anchor
 * @Date 2021/9/1
*/
public abstract class AServerInfos {

    private static class GxServerInfosContainer {
        private static List<String> ipAddress = null;
        private static List<String> macAddress = null;
        private static String cpuSerial = null;
        private static String mainBoardSerial = null;
    }

    /**
     * @Description
     * 组装需要额外校验的License参数
     * @return LicenseExtraParam 自定义校验参数
     * @author Anchor
     * @Date 2021/9/1
    */
    public LicenseExtraParam getServerInfos() throws LicenseContentException {
        LicenseExtraParam result = new LicenseExtraParam();
        try {
            initServerInfos();
            result.setIpAddress(GxServerInfosContainer.ipAddress);
            result.setMacAddress(GxServerInfosContainer.macAddress);
            result.setCpuSerial(GxServerInfosContainer.cpuSerial);
            result.setMainBoardSerial(GxServerInfosContainer.mainBoardSerial);
        } catch (Exception e) {
            throw new LicenseContentException("获取服务器硬件信息失败");
        }
        return result;
    }

    /**
     * <p>初始化服务器硬件信息,并将信息缓存到内存</p>
     *
     * @throws Exception 默认异常
     */
    private void initServerInfos() throws Exception {
        if (GxServerInfosContainer.ipAddress == null) {
            GxServerInfosContainer.ipAddress = this.getIpAddress();
        }
        if (GxServerInfosContainer.macAddress == null) {
            GxServerInfosContainer.macAddress = this.getMacAddress();
        }
        if (GxServerInfosContainer.cpuSerial == null) {
            GxServerInfosContainer.cpuSerial = this.getCPUSerial();
        }
        if (GxServerInfosContainer.mainBoardSerial == null) {
            GxServerInfosContainer.mainBoardSerial = this.getMainBoardSerial();
        }
    }

    /**
     * <p>获取IP地址</p>
     *
     * @return List<String> IP地址
     * @throws Exception 默认异常
     */
    public List<String> getIpAddress() throws Exception {
        /** 获取所有网络接口 */
        List<InetAddress> inetAddresses = getLocalAllInetAddress();
        if (CommonUtils.isNotEmpty(inetAddresses)) {
            return inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * <p>获取Mac地址</p>
     *
     * @return List<String> Mac地址
     * @throws Exception 默认异常
     */
    public List<String> getMacAddress() throws Exception {
        /** 获取所有网络接口 */
        List<InetAddress> inetAddresses = getLocalAllInetAddress();
        if (CommonUtils.isNotEmpty(inetAddresses)) {
            return inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
        }
        return null;
    }

    /**
     * <p>获取服务器信息</p>
     *
     * @param osName 系统类型
     * @return AGxServerInfos 服务信息
     */
    public static AServerInfos getServer(String osName) {
        if ("".equals(osName) || osName == null) {
            osName = System.getProperty("os.name").toLowerCase();
        }
        AServerInfos abstractServerInfos;
        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith(OsType.WINDOWS.getCode())) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith(OsType.LINUX.getCode())) {
            abstractServerInfos = new LinuxServerInfos();
        } else if (osName.startsWith(OsType.MACOS.getCode())){
            abstractServerInfos = new MacintoshServerInfos();
        } else {//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }
        return abstractServerInfos;
    }

    /**
     * <p>获取CPU序列号</p>
     *
     * @return String 主板序列号
     * @throws Exception 默认异常
     */
    protected abstract String getCPUSerial() throws Exception;

    /**
     * <p>获取主板序列号</p>
     *
     * @return String 主板序列号
     * @throws Exception 默认异常
     */
    protected abstract String getMainBoardSerial() throws Exception;

    /**
     * <p>获取当前服务器所有符合条件的网络地址</p>
     *
     * @return List<InetAddress> 网络地址列表
     * @throws Exception 默认异常
     */
    private List<InetAddress> getLocalAllInetAddress() throws Exception {
        List<InetAddress> result = new ArrayList<>(4);
        // 遍历所有的网络接口
        for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) {
            NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
            // 在所有的接口下再遍历IP
            for (Enumeration addresses = ni.getInetAddresses(); addresses.hasMoreElements(); ) {
                InetAddress address = (InetAddress) addresses.nextElement();
                //排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress类型的IP地址
                if (!address.isLoopbackAddress()
                        && !address.isLinkLocalAddress() && !address.isMulticastAddress()) {
                    result.add(address);
                }
            }
        }
        return result;
    }

    /**
     * <p>获取服务器临时磁盘位置</p>
     */
    public static String getServerTempPath() {
        String property = System.getProperty("user.dir");
        return property;
    }

    /**
     * <p>获取某个网络地址对应的Mac地址</p>
     *
     * @param inetAddr 网络地址
     * @return String Mac地址
     */
    private String getMacByInetAddress(InetAddress inetAddr) {
        try {
            byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    stringBuilder.append("-");
                }
                /** 将十六进制byte转化为字符串 */
                String temp = Integer.toHexString(mac[i] & 0xff);
                if (temp.length() == 1) {
                    stringBuilder.append("0").append(temp);
                } else {
                    stringBuilder.append(temp);
                }
            }
            return stringBuilder.toString().toUpperCase();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

}
LinuxServerInfos
/**
 * @Description
 * 用于获取客户Linux服务器的基本信息
 * @author Anchor
 * @Date 2021/9/1
*/
public class LinuxServerInfos extends AServerInfos {

    private final String[] CPU_SHELL = {"/bin/bash","-c","dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"};
    private final String[] MAIN_BOARD_SHELL = {"/bin/bash","-c","dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"};

    @Override
    protected String getCPUSerial() throws Exception {
        String result = "";
        String CPU_ID_CMD = "dmidecode";
        BufferedReader bufferedReader = null;
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(new String[] { "sh", "-c", CPU_ID_CMD });
            bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            int index = -1;
            while ((line = bufferedReader.readLine()) != null) {
                // 寻找标示字符串[hwaddr]
                index = line.toLowerCase().indexOf("uuid");
                if (index >= 0) {
                    // 取出mac地址并去除2边空格
                    result = line.substring(index + "uuid".length() + 1).trim();
                    break;
                }
            }
        } catch (IOException e) {
            throw new LicenseException("获取cpu信息错误", e);
        }
        return result.trim();
    }

    @Override
    protected String getMainBoardSerial() throws Exception {
        String result = "";
        String maniBord_cmd = "dmidecode | grep 'Serial Number' | awk '{print $3}' | tail -1";
        Process p;
        try {
            p = Runtime.getRuntime().exec(new String[] { "sh", "-c", maniBord_cmd });
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                result += line;
                break;
            }
            br.close();
        } catch (IOException e) {
            throw new LicenseException("获取主板信息错误", e);
        }
        return  result;
    }


}
MacintoshServerInfos
/**
 * @program: license
 * @description: Macintosh系统信息获取
 * @author: Anchor
 * @create: 2021-08-30
 **/
public class MacintoshServerInfos extends AServerInfos {

    private final String SERIAL_SHELL = "system_profiler SPHardwareDataType | grep Serial | awk '{print $4}'";
    private final String UUID_SHELL = "system_profiler SPHardwareDataType | grep UUID | awk  '{print $3}'";

    @Override
    protected String getCPUSerial() throws Exception {
        String result = "";
        try {
            // 管道
            Process p = Runtime.getRuntime().exec(new String[] { "sh", "-c", SERIAL_SHELL });
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            result = bufferedReader.readLine();
        } catch (IOException e) {
            throw new LicenseException("获取cpu信息错误", e);
        }
        return result.trim();
    }

    @Override
    protected String getMainBoardSerial() throws Exception {
        String result = "";
        try {
            // 管道
            Process p = Runtime.getRuntime().exec(new String[] { "sh", "-c", UUID_SHELL });
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            result = bufferedReader.readLine();
        } catch (IOException e) {
            throw new LicenseException("获取主板信息错误", e);
        }
        return result.trim();
    }
}
WindowsServerInfos
/**
 * @Description
 * 用于获取客户Windows服务器的基本信息
 * @author Anchor
 * @Date 2021/9/1
*/
public class WindowsServerInfos extends AServerInfos {

    private final String CPU_COMMAND = "wmic cpu get processorid";
    private final String MAIN_BOARD_COMMAND = "wmic baseboard get serialnumber";

    @Override
    protected String getCPUSerial() throws Exception {
        String result = "";
        try {
            File file = File.createTempFile("tmp", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new FileWriter(file);
            String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                    + "Set colItems = objWMIService.ExecQuery _ \n" + "   (\"Select * from Win32_Processor\") \n"
                    + "For Each objItem in colItems \n" + "    Wscript.Echo objItem.ProcessorId \n"
                    + "    exit for  ' do the first cpu only! \n" + "Next \n";

            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
            file.delete();
        } catch (Exception e) {
            throw new LicenseException("获取cpu信息错误", e);
        }
        return result.trim();
    }

    @Override
    protected String getMainBoardSerial() throws Exception {

        String result = "";
        try {
            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new FileWriter(file);

            String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                    + "Set colItems = objWMIService.ExecQuery _ \n" + "   (\"Select * from Win32_BaseBoard\") \n"
                    + "For Each objItem in colItems \n" + "    Wscript.Echo objItem.SerialNumber \n"
                    + "    exit for  ' do the first cpu only! \n" + "Next \n";

            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
            throw new LicenseException("获取主板信息错误", e);
        }
        return result.trim();
    }


}

2、license-creator

creator模块主要作用是根据获取到的机器特征信息生成授权license文件,所以模块中会用到第二章生成的私钥文件,整体代码结构如下:

config

LicenseCreatorAutoConfigure
/**
* @Description
* License生成模块自动扫包/装配Bean实例
* @author Anchor
* @Date 2021/9/1
*/
@Configuration
    @ComponentScan(basePackages = {"com.alihai5.license.creator"})
    @EnableConfigurationProperties({LicenseCreatorProperties.class})
    public class LicenseCreatorAutoConfigure {
        public LicenseCreatorAutoConfigure(){

        }
    }
LicenseCreatorProperties
/**
 * @Description
 * License生成配置类
 * @author Anchor
 * @Date 2021/9/1
*/
@ConfigurationProperties(prefix = "springboot.license.generate")
public class LicenseCreatorProperties {

    /**证书生成临时存放路径*/
    private String tempPath;

    public LicenseCreatorProperties() {
    }

    public String getTempPath() {
        return tempPath;
    }

    public void setTempPath(String tempPath) {
        this.tempPath = tempPath;
        File file = new File(tempPath);
        if(!file.exists()){
            file.mkdirs();
        }
    }
}

controller

LicenseCreatorController
/**
 * @Description
 * 用于生成证书文件
 * @author Anchor
 * @Date 2021/9/1
*/
@CrossOrigin
@RestController
@RequestMapping("/license")
public class LicenseCreatorController {

    @Value("${springboot.license.server.prefix:http://localhost:8080/license/}")
    private String licPrefixUrl ;

    @Autowired
    private LicenseCreatorService creatorService ;

    @Autowired
    private LicenseCreatorProperties properties;

    /**
     * <p>生成证书(硬件信息经过加密处理)</p>
     * @param param 生成证书需要的参数,如:
     *
     */
    @PostMapping("/generateFirst")
    public AjaxResult generateFirst(@RequestBody LicenseCreatorParam param,
                                    @RequestParam String extraParam) throws Exception {
        // 解密加密后的硬件信息
        LicenseExtraParam orginExtraParam = JSONObject.parseObject(new String(Base64.decode(extraParam),
                StandardCharsets.UTF_8), LicenseExtraParam.class);
        // 将解密后的硬件信息复制给处理对象
        LicenseExtraParam licenseExtraParam = param.getLicenseCheck();
        licenseExtraParam.setCpuSerial(orginExtraParam.getCpuSerial());
        licenseExtraParam.setIpAddress(orginExtraParam.getIpAddress());
        licenseExtraParam.setMacAddress(orginExtraParam.getMacAddress());
        licenseExtraParam.setMainBoardSerial(orginExtraParam.getMainBoardSerial());

        // 生成授权证书
        return generate(param);
    }

    /**
     * <p>生成证书</p>
     * @param param 生成证书需要的参数,如:
     *
     */
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody LicenseCreatorParam param) throws Exception {
        // 如果没有人为的指定lic要生成的位置,则程序自动处理
        if(CommonUtils.isEmpty(param.getLicensePath())){
            //设置格式
            SimpleDateFormat format =  new SimpleDateFormat("yyyyMMddHHmmss");
            String tempPath = properties.getTempPath();
            if(tempPath == null || "".equals(tempPath)){
                // 如果默认临时文件等于空的话,就获取当前服务执行的路径
                tempPath = AServerInfos.getServerTempPath();
            }
            // 根据时间戳,命名lic文件
            String licDir = tempPath+"/license/"+format.format(System.currentTimeMillis());
            File file = new File(licDir);
            if(!file.exists()){
               if(!file.mkdirs()){
                   throw new CustomException("创建目录"+licDir+",失败,请检查是是否有创建目录的权限或者手动进行创建!");
               }
            }
            param.setLicensePath(licDir + "/license.lic");
        }
        param.setLicUrl(licPrefixUrl+"download?path="+param.getLicensePath());
        return creatorService.generateLicense(param);
    }

    @GetMapping("/download")
    public void downLoad(@RequestParam(value = "path") String path, HttpServletRequest request, HttpServletResponse response) throws Exception{
        File file = new File(path);
        if(!file.exists()){
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        InputStream is = new FileInputStream(file);
        String fileName = file.getName();
        // 设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        // 设置编码格式
        response.setCharacterEncoding("UTF-8");
        // 设置可以识别Html文件
        response.setContentType("text/html");
        // 设置头中附件文件名的编码
        setAttachmentCoding(request, response, fileName);
        BufferedInputStream bis = new BufferedInputStream(is);
        OutputStream os = response.getOutputStream();
        byte[] buffer = new byte[1024 * 10];
        int length ;
        while ((length = bis.read(buffer, 0, buffer.length)) != -1) {
            os.write(buffer, 0, length);
        }
        os.close();
        bis.close();
        is.close();
    }

    private void setAttachmentCoding(HttpServletRequest request, HttpServletResponse response, String fileName) {
        String browser;
        try {
            browser = request.getHeader("User-Agent");
            if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
                // IE6, IE7 浏览器
                response.addHeader("content-disposition", "attachment;filename="
                        + new String(fileName.getBytes(), "ISO8859-1"));
            } else if (-1 < browser.indexOf("MSIE 8.0")) {
                // IE8
                response.addHeader("content-disposition", "attachment;filename="
                        + URLEncoder.encode(fileName, "UTF-8"));
            } else if (-1 < browser.indexOf("MSIE 9.0")) {
                // IE9
                response.addHeader("content-disposition", "attachment;filename="
                        + URLEncoder.encode(fileName, "UTF-8"));
            } else if (-1 < browser.indexOf("Chrome")) {
                // 谷歌
                response.addHeader("content-disposition",
                        "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
            } else if (-1 < browser.indexOf("Safari")) {
                // 苹果
                response.addHeader("content-disposition", "attachment;filename="
                        + new String(fileName.getBytes(), "ISO8859-1"));
            } else {
                // 火狐或者其他的浏览器
                response.addHeader("content-disposition",
                        "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

service

LicenseCreatorService
/**
 * @Description
 * 证书生成接口实现
 * @author Anchor
 * @Date 2021/9/1
*/
@Service
public class LicenseCreatorService {
    /**
     * <p>生成证书</p>
     * @param param 证书创建需要的参数对象
     * @return Map<String,Object>
     */
    public AjaxResult generateLicense(LicenseCreatorParam param) {
        LicenseCreatorManager licenseCreator = new LicenseCreatorManager(param);
        LicenseResult licenseResult = licenseCreator.generateLicense();
        if(licenseResult.getResult()){
            String message = MessageFormat.format("证书生成成功,证书有效期:{0} - {1}",
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,param.getIssuedTime()),
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,param.getExpiryTime()));
            return AjaxResult.success(message,param);
        }else{
            return AjaxResult.error("证书文件生成失败!");
        }
    }


}

3、license-verify

verify模块内嵌于客户端,用于校验授权license是否合法,所以模块中会用到第二章生成的公钥文件,项目启动后执行,如不合法则抛出异常并终止JVM,其结构如下:

annotion

VLicense
/**
 * @Description
 * License自定义注解
 * @author Anchor
 * @Date 2021/9/2
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface VLicense {
    String[] verifies() default{};
}

config

LicenseInterceptorConfig
/**
 * @Description
 * License拦截器配置类
 * @author Anchor
 * @Date 2021/9/2
*/
@Configuration
public class LicenseInterceptorConfig implements WebMvcConfigurer {

    @Bean
    public LicenseVerifyInterceptor getLicenseCheckInterceptor() {
        return new LicenseVerifyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.getLicenseCheckInterceptor()).addPathPatterns("/**");
    }
}
LicenseVerifyAutoConfigure
/**
 * @Description
 * License验证模块自动扫包/装配Bean实例
 * @author Anchor
 * @Date 2021/9/2
*/
@Configuration
@ComponentScan(basePackages = {"com.alihai5.license.verify"})
public class LicenseVerifyAutoConfigure {

    public LicenseVerifyAutoConfigure(){
        
    }
}
LicenseVerifyProperties
/**
 * @Description
 * License验证属性类
 * @author Anchor
 * @Date 2021/9/2
*/
@Component
@ConfigurationProperties(prefix = "groot.license.verify")
public class LicenseVerifyProperties {

    private String subject = "groot";
    private String publicAlias = "publicCerts";
    private String publicKeysStorePath = "/publicCerts.store";
    private String storePass = "groot7758";
    private String licensePath;

    public LicenseVerifyProperties() {
    }

    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 getPublicKeysStorePath() {
        return publicKeysStorePath;
    }

    public void setPublicKeysStorePath(String publicKeysStorePath) {
        this.publicKeysStorePath = publicKeysStorePath;
    }

    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 LicenseVerifyParam getVerifyParam() {
        LicenseVerifyParam param = new LicenseVerifyParam();
        param.setSubject(subject);
        param.setPublicAlias(publicAlias);
        param.setStorePass(storePass);
        param.setLicensePath(licensePath);
        param.setPublicKeysStorePath(publicKeysStorePath);
        return param;
    }
}

interceptor

LicenseVerifyInterceptor
/**
 * @Description
 * License验证拦截器
 * @author Anchor
 * @Date 2021/9/2
*/
public class LicenseVerifyInterceptor implements HandlerInterceptor {

    @Autowired
    private LicenseVerifyProperties properties;

    public LicenseVerifyInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            VLicense annotation = method.getAnnotation(VLicense.class);
            if (CommonUtils.isNotEmpty(annotation)) {
                LicenseVerifyManager licenseVerifyManager = new LicenseVerifyManager();
                /** 1、校验证书是否有效 */
                LicenseResult verifyResult = licenseVerifyManager.verify(properties.getVerifyParam());
                if(!verifyResult.getResult()){
                    throw  new LicenseException(verifyResult.getMessage());
                }
                LicenseContent content = verifyResult.getContent();
                LicenseExtraParam licenseCheck = (LicenseExtraParam) content.getExtra();
                if (verifyResult.getResult()) {
                    /** 增加业务系统监听,是否自定义验证 */
                    List<ACustomVerifyListener> customListenerList = ACustomVerifyListener.getCustomListenerList();
                    boolean compare = true;
                    for (ACustomVerifyListener listener : customListenerList) {
                        boolean verify = listener.verify(licenseCheck);
                        compare = compare && verify;
                    }
                    return compare;
                }
                throw new LicenseException(verifyResult.getException().getMessage());
            }
        }
        return true;
    }
}

listener

ACustomVerifyListener
/**
 * @Description
 * 增加业务系统中自定义证书验证监听器
 * @author Anchor
 * @Date 2021/9/2
*/
public abstract class ACustomVerifyListener {

    /**软件证书参数全局验证监听容器*/
    private static final List<ACustomVerifyListener> CUSTOM_VERIFY_LISTENER_LIST = new ArrayList<>(16);

    public static List<ACustomVerifyListener> getCustomListenerList(){
        return CUSTOM_VERIFY_LISTENER_LIST;
    }

    /***
     * 默认构造函数,干了一件事情,就是会把所有实现了这个抽象类的子类实例全部添加到全局自定义验证监听器列表中
     * 因为在调用子类的构造函数时,会首先调用父类的构造器
     */
    public ACustomVerifyListener() {
        addCustomListener(this);
    }

    public synchronized static void addCustomListener(ACustomVerifyListener verifyListener){
        CUSTOM_VERIFY_LISTENER_LIST.add(verifyListener);
    }

    /**
     * 业务系统自定义证书认证方法
     * @param licenseExtra 自定义验证参数
     * @return boolean 是否成功
     */
    public abstract boolean verify(LicenseExtraParam licenseExtra) throws LicenseException;

}
LicenseVerifyListener
/**
 * @Description
 * 项目启动时安装证书&定时检测lic变化,自动更替lic
 * @author Anchor
 * @Date 2021/9/2
*/
@Component
public class LicenseVerifyListener implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger log = LoggerFactory.getLogger(LicenseVerifyListener.class);

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Autowired
    private LicenseVerifyProperties properties;

    /**文件唯一身份标识 == 相当于人类的指纹一样*/
    private static String md5 = "";
    private static boolean isLoad = false;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(CommonUtils.isNotEmpty(properties.getLicensePath())){
            install();
            try{
                String readMd5 = getMd5(properties.getLicensePath());
                isLoad = true;
                if(LicenseVerifyListener.md5 == null || "".equals(LicenseVerifyListener.md5)){
                    LicenseVerifyListener.md5 =readMd5;
                }
            }catch (Exception e){

            }
        } else {
            HandlerLicenseRemider();
        }
    }

    private void install() {
        log.info("++++++++ 开始安装授权证书 ++++++++");
        LicenseVerifyManager licenseVerifyManager = new LicenseVerifyManager();
        /** 走定义校验证书并安装 */
        LicenseResult result = licenseVerifyManager.install(properties.getVerifyParam());
        if(result.getResult()){
            log.info("++++++++ 授权证书安装成功 ++++++++");
        }else{
            log.error("++++++++ 授权证书安装失败 ++++++++");
            HandlerLicenseRemider();
        }
    }

    /**
     * <p>获取文件的md5</p>
     */
    public String getMd5(String filePath) throws Exception {
        File file;
        String md5 = "";
        try {
            file = ResourceUtils.getFile(filePath);
            if (file.exists()) {
                FileInputStream is = new FileInputStream(file);
                byte[] data = new byte[is.available()];
                is.read(data);
                md5 = DigestUtils.md5DigestAsHex(data);
                is.close();
            }
        } catch (FileNotFoundException e) {

        }
        return md5;
    }

    /**
     * <p>日志打印授权提醒</p>
     */
    private void HandlerLicenseRemider() {
        try {
            log.warn("无有效授权证书,请联系管理员申请!申请参数[{}]",
                    Base64.encode(JSON.toJSONString(AServerInfos.getServer("").getServerInfos()).getBytes(StandardCharsets.UTF_8)));
        } catch (LicenseContentException e) {
            log.error("读取服务器硬件信息异常:"+e.getMessage());
        } finally {
            ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) applicationContext;
            ctx.close();
            ctx.stop();
        }
    }

}

4、license-boot-start

boot-start模块非必须,仅为了模块调试及方便授权文件生成使用,代码结构非常简单:

启动类

LicenseApplication
/**
 * @program: groot-license
 * @description: 启动类
 * @author: Anchor
 * @create: 2021-09-01
 **/
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class LicenseApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(LicenseApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(LicenseApplication.class);
    }
}

配置文件

Application.yml
server:
  # 服务器的HTTP端口,默认为8080
  port: 8080
groot:
  license:
    verify:
      prefix: http://localhost:8080/license/
      licensePath: /Users/anchor/Tools/alihai5/license.lic

使用效果

HTTP请求示例
POST /license/generate HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: 127.0.0.1:8080
Connection: close
User-Agent: RapidAPI/4.1.0 (Macintosh; OS X/13.0.1) GCDHTTPRequest
Content-Length: 550

{"subject":"groot","privateAlias":"privatekeys","keyPass":"groot7758","storePass":"groot7758","privateKeysStorePath":"/privateKeys.store","issuedTime":"2022-12-01 00:00:00","expiryTime":"2025-12-31 00:00:00","description":"\u7cfb\u7edf\u8f6f\u4ef6\u8bb8\u53ef\u8bc1\u4e66","licenseCheck":{"ipAddress":["192.168.1.111"],"macAddress":["B0-DE-28-10-CA-92"],"cpuSerial":"L6PHQYPWGW","mainBoardSerial":"D1F0CA19-227C-5B4C-8149-3DE736423365","registerAmount":1000,"macCheck":false,"boardCheck":false,"cpuCheck":false,"ipCheck":false,"registerCheck":false}}
Response接口返回示例
{
  "msg": "证书生成成功,证书有效期:2022-12-01 00:00:00 - 2025-12-31 00:00:00",
  "code": 200,
  "data": {
    "subject": "groot",
    "privateAlias": "privatekeys",
    "keyPass": "groot7758",
    "privateKeysStorePath": "/privateKeys.store",
    "storePass": "groot7758",
    "licensePath": "/Users/anchor/Workspase/Alihai5/groot/license/20221226162407/license.lic",
    "issuedTime": "2022-12-01 00:00:00",
    "expiryTime": "2025-12-31 00:00:00",
    "consumerType": "user",
    "consumerAmount": 1,
    "description": "系统软件许可证书",
    "licenseCheck": {
      "ipAddress": [
        "192.168.1.111"
      ],
      "macAddress": [
        "B0-DE-28-10-CA-92"
      ],
      "cpuSerial": "L6PHQYPWGW",
      "mainBoardSerial": "D1F0CA19-227C-5B4C-8149-3DE736423365",
      "registerAmount": 1000,
      "ipCheck": false,
      "macCheck": false,
      "cpuCheck": false,
      "boardCheck": false,
      "registerCheck": false
    },
    "licUrl": "http://localhost:8080/license/download?path=/Users/anchor/Workspase/Alihai5/groot/license/20221226162407/license.lic"
  }
}

5、实现效果

有授权启动

授权启动日志
2022-12-31 14:51:21 INFO  [restartedMain] org.apache.coyote.http11.Http11NioProtocol Starting ProtocolHandler ["http-nio-8080"]
2022-12-31 14:51:22 INFO  [restartedMain] c.a.license.verify.listener.LicenseVerifyListener ++++++++ 开始安装授权证书 ++++++++
2022-12-31 14:51:22 INFO  [restartedMain] c.alihai5.license.core.model.LicenseVerifyManager 证书安装成功,证书有效期:2022-12-01 00:00:00 - 2025-12-31 00:00:00
2022-12-31 14:51:22 INFO  [restartedMain] c.a.license.verify.listener.LicenseVerifyListener ++++++++ 授权证书安装成功 ++++++++
2022-12-31 14:51:22 INFO  [restartedMain] com.alihai5.GrootApplication Started GrootApplication in 10.422 seconds (JVM running for 11.916)

无授权启动

无授权启动日志
2022-12-31 14:52:56 INFO  [restartedMain] org.apache.coyote.http11.Http11NioProtocol Starting ProtocolHandler ["http-nio-8080"]
2022-12-31 14:52:56 WARN  [restartedMain] c.a.license.verify.listener.LicenseVerifyListener 无有效授权证书,请联系管理员申请!申请参数[eyJib2FyZENoZWNrIjpmYWxzZSwiY3B1Q2hlY2siOmZhbHNlLCJjcHVTZXJpYWwiOiJMNlBIUVlQV0dXIiwiaXBBZGRyZXNzIjpbIjE5Mi4xNjguMC4xNSJdLCJpcENoZWNrIjpmYWxzZSwibWFjQWRkcmVzcyI6WyJCMC1ERS0yOC0xMC1DQS05MiJdLCJtYWNDaGVjayI6ZmFsc2UsIm1haW5Cb2FyZFNlcmlhbCI6IkQxRjBDQTE5LTIyN0MtNUI0Qy04MTQ5LTNERTczNjQyMzM2NSIsInJlZ2lzdGVyQ2hlY2siOmZhbHNlfQ==]
2022-12-31 14:52:56 INFO  [restartedMain] org.apache.coyote.http11.Http11NioProtocol Pausing ProtocolHandler ["http-nio-8080"]
2022-12-31 14:52:56 INFO  [restartedMain] org.apache.catalina.core.StandardService Stopping service [Tomcat]
2022-12-31 14:52:56 WARN  [restartedMain] org.apache.catalina.loader.WebappClassLoaderBase The web application [ROOT] appears to have started a thread named [lettuce-timer-3-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Thread.sleep(Native Method)
 io.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:600)
 io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:496)
 io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
 java.lang.Thread.run(Thread.java:748)
2022-12-31 14:52:56 INFO  [restartedMain] org.apache.coyote.http11.Http11NioProtocol Stopping ProtocolHandler ["http-nio-8080"]
2022-12-31 14:52:56 INFO  [restartedMain] org.apache.coyote.http11.Http11NioProtocol Destroying ProtocolHandler ["http-nio-8080"]
2022-12-31 14:52:56 ERROR [restartedMain] org.springframework.boot.SpringApplication Application run failed

五、总结

有授权就一定有破解,没有绝对的防御,为防止被简单替换jar包被破解,可以尝试调整Maven引用层级,如将框架核心模块放入授权认证下,使之无法跳过验证逻辑,同时引入Allatori混淆代码等等措施,增加破解难度。