Java利用trueLicense實現(xiàn)項目離線證書授權(quán)操作步驟
0.引言
我們在實際項目中,會遇到開發(fā)的項目部署在服務(wù)器上,但可能要控制權(quán)限、控制項目授權(quán)周期等,部署的環(huán)境可能純內(nèi)網(wǎng)使用,因此通過網(wǎng)絡(luò)接口控制就不可行了,我們期望一種分發(fā)授權(quán)證書的形式,通過部署證書的形式,離線控制用戶能使用這個項目的哪個模塊、使用多久,甚至使用用戶的哪些設(shè)備、哪臺服務(wù)器可以使用。
今天我們來看看這樣的需求如何實現(xiàn)
1. trueLicense簡介
1.1 原理簡介
我們要實現(xiàn)的離線校驗,實際上就是通過公私鑰+證書的形式來實現(xiàn)的,首先生成公私鑰,然后利用私鑰生成證書,比如x509證書格式,x509證書由用戶公共密鑰和用戶標(biāo)識符組成。此外還包括版本號、證書序列號、CA標(biāo)識符、簽名算法標(biāo)識、簽發(fā)者名稱、證書有效期等信息
我們的核心目的就是要生成的證書中包含有效期,即可實現(xiàn)授權(quán)有效期,然后通過接口攔截器,每次訪問接口時利用公鑰對證書進行校驗,查看證書是否合法、是否在有效期內(nèi),即可實現(xiàn)我們進行離線控制的目的。
1.2 公鑰私鑰和證書
部分同學(xué)如果沒接觸過加密和驗簽的,可能對公私鑰和證書沒什么概念,所以我們先正對這幾個概念做個解釋,方便大家理解。
什么是公鑰和私鑰
公鑰和私鑰是一對相互匹配的密鑰,用于加密和解密數(shù)據(jù)。 公鑰用于加密數(shù)據(jù),而私鑰用于解密數(shù)據(jù)。公鑰可以公開,任何人都可以使用,而私鑰必須保密,只有持有者才能使用。一般會把公鑰提供給客戶,用于加密,私鑰保留在自己側(cè),用于解密。
那么當(dāng)自己需要加密數(shù)據(jù)發(fā)送給客戶時怎么辦呢? 這就需要客戶再生成一對公私鑰,由客戶保留私鑰,我方保留公鑰,發(fā)送數(shù)據(jù)時,我們使用客戶的公鑰加密數(shù)據(jù),客戶使用自己的私鑰進行解密
公私鑰一般用于非對稱加密中,與對稱加密最大的不同就是,對稱加密加密方和解密方使用的都是同一個密鑰,在密鑰交換過程中可能會產(chǎn)生泄漏的風(fēng)險,而密鑰對則只用交換雙方的公鑰,提高了安全性

公私鑰長什么樣呢,實際就是兩個字符串,當(dāng)然也可以保存為文件,但實質(zhì)就是字符串,如下我們生成的一對公私鑰,一般私鑰會比公鑰長:
Private key:
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIZDTf1Id19XgnWLfXqFbnKYqM/uzr0/K9EtNJaeQf2CL6cq1kk6AEWjp/j540CWH5qN4RYMzTeomrbPkWYsVvEMzBSNCKqtZSdgQkj8591xcUeiFtjBudzMNdUPRIFqScDgSjci6+Lo01TnFWz/CiuKe/AQJ0xHgpSY06IElYG3AgMBAAECgYBuKh996c347wbeh/wHYiCD6vro0lvUMFc1pU/3HherePy8v4tgPjUm7ufOhMuQnR2FZVEBFLP2LWP1CE+XdF5I7vOl1euc9Wqj+CgQmbFS8lISXbzzgauhL4EQdBOvqggjVnw3NsYWkSU5x+zlR51v2E4mXOalaNEdmpR1MXT+8QJBAMBAKQcqwwD0PZsHIReayGdj8fu4H3PQsOcbCE8GaYh5F0GSByI251B3+RU0whO7fw+gqT8A0FIxt4HV2if6BTsCQQCyyKmPqrlAkPlywdTaEPiSenb8JqMlLsSwFrch0QSmfRZcMjH87ilZSd+DbZstkBZ92xVA40pr3QtOy6lYpn21AkAvz0TkvWOlVxgC97DpF9sCqz5AZTedK6bysixMysFv6P05l0Ei5xh7UHqnJWmmUph0oHW2b1NfPXHvXelUy76FAkAxYGIUH56SSnfaTdYvc8hzDAeYlEMynbwMtflWCZgzMxDd3a8Yn94jntdwQPE+oDDWCY/RH/UJ3T6mQHFA3pqRAkEAwDvPrIZ1+SMqarQMycyYivVbVhAywHmTeNnQ0kgWW080wtvGECJ/UG20xtb3LFGLafqVw1L94hAqKmrh9uct6A==
Public key:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGQ039SHdfV4J1i316hW5ymKjP7s69PyvRLTSWnkH9gi+nKtZJOgBFo6f4+eNAlh+ajeEWDM03qJq2z5FmLFbxDMwUjQiqrWUnYEJI/OfdcXFHohbYwbnczDXVD0SBaknA4Eo3Iuvi6NNU5xVs/worinvwECdMR4KUmNOiBJWBtwIDAQAB
什么是證書
電子證書,通常指的是數(shù)字證書(Digital Certificate),在信息技術(shù)領(lǐng)域,它是一種用于在網(wǎng)絡(luò)上驗證身份和保障通信安全的電子證明。電子證書包含以下幾個關(guān)鍵組成部分:
證書持有者的公鑰:這是證書的主要部分,用于加密信息,只有證書持有者的私鑰可以解密。
證書持有者的身份信息:這包括持有者的名稱或其他標(biāo)識信息,用于驗證公鑰所屬的身份。
證書簽發(fā)機構(gòu)的數(shù)字簽名:證書由一個可信的第三方機構(gòu)——證書授權(quán)中心(Certificate Authority,簡稱CA)簽發(fā)。CA通過其私鑰對證書內(nèi)容進行數(shù)字簽名,以確保證書內(nèi)容的真實性和完整性。
有效期:證書在特定的時間段內(nèi)有效,過期后需要更新或更換。
證書使用目的:證書可能用于不同的目的,如網(wǎng)頁安全瀏覽(HTTPS)、電子郵件加密、數(shù)字簽名等。
電子證書的一般可用于:
身份驗證:確認網(wǎng)絡(luò)上的通信實體是真實的,不是假冒的。
數(shù)據(jù)加密:使用公鑰加密數(shù)據(jù),只有持有對應(yīng)私鑰的人才能解密。
數(shù)據(jù)完整性:確保在傳輸過程中數(shù)據(jù)沒有被篡改。
證書本身也可以用一串字符串表示,更直觀的我們可以在谷歌瀏覽器上點擊左側(cè)地址欄的圖標(biāo)查看網(wǎng)址https證書信息

如下展示了github的證書信息,就可以看到其中包含CA機構(gòu)、有效期、公鑰等基本信息

1.3 trueLicense簡介
有了以上基本概念后,我們再來介紹trueLicense:
TrueLicense是一個開源的證書管理引擎,主要用于軟件產(chǎn)品的授權(quán)管理。它的主要功能是在軟件項目交付給客戶后,通過簽名機制來確保客戶不能隨意使用該項目。TrueLicense的授權(quán)機制基于以下原理:
生成密鑰對:使用工具(如KeyTool)生成包含私鑰和公鑰的密鑰對。
授權(quán)者保留私鑰:授權(quán)者使用私鑰對包含授權(quán)信息(如使用截止日期、MAC地址等)的license進行數(shù)字簽名。
公鑰給使用者:將公鑰放在驗證代碼中使用,用于驗證license是否符合使用條件。
TrueLicense的使用場景包括設(shè)定軟件的試用期、綁定特定IP或MAC地址等。通過這種方式,可以在不修改源代碼的情況下,通過重新生成license來延長試用期或修改授權(quán)條件。
前面我們提到過,我們的核心目的就是要生成的證書中包含有效期,即可實現(xiàn)授權(quán)有效期,然后通過接口攔截器,每次訪問接口時利用公鑰對證書進行校驗,查看證書是否合法、是否在有效期內(nèi),而trueLicense就是幫助我們簡化這一流程,他內(nèi)部封裝了這一系列的操作,我們只需要簡單的集成即可實現(xiàn)功能
下面我們來具體實操。
2. 操作步驟
首先先介紹下,我們本次演示要構(gòu)造的模塊,一共分為3個模塊:
- 證書校驗?zāi)K:集成證書校驗核心邏輯,作為工具包引入到需要進行離線授權(quán)的服務(wù)中
- 證書生成模塊:用于生成證書,或?qū)ψC書進行續(xù)約
- 測試模塊:單獨的一個用于測試離線授權(quán)邏輯的模塊,模擬需要進行離線授權(quán)的web服務(wù)
2.1 生成公私鑰
2.1.1 keyTool工具介紹
前面提到我們需要生成一個公私鑰,然后再生成證書,那么公私鑰的生成就可以利用java自帶的KeyTool工具來實現(xiàn)
KeyTool 是一個Java密鑰和證書管理工具,它是Java SDK的一部分。KeyTool用于管理密鑰庫(KeyStore),在密鑰庫中可以存儲私鑰和公鑰證書。以下是KeyTool的一些主要功能和用途:
生成密鑰對:KeyTool可以生成密鑰對(公鑰和私鑰),這是加密和安全通信的基礎(chǔ)。
管理密鑰庫:它可以創(chuàng)建和管理密鑰庫文件,這些文件通常具有.keystore擴展名。密鑰庫用于存儲密鑰和證書。
導(dǎo)入和導(dǎo)出證書:KeyTool允許用戶將證書導(dǎo)入到密鑰庫中,或者從密鑰庫中導(dǎo)出證書。
生成證書請求:可以生成證書簽名請求(CSR),這是發(fā)送給證書頒發(fā)機構(gòu)(CA)以獲取證書的過程的一部分。
查看和管理證書:可以查看密鑰庫中的證書詳細信息,以及設(shè)置或更改其屬性。
設(shè)置別名:在密鑰庫中,可以為密鑰和證書設(shè)置別名,以便更容易地引用它們。
以下是KeyTool的一些常用命令:
keytool -genkeypair:生成密鑰對。
keytool -list:列出密鑰庫中的條目。
keytool -importcert:導(dǎo)入證書或證書鏈。
keytool -exportcert:導(dǎo)出證書。
keytool -keystore:指定密鑰庫的名稱和位置
2.1.2 生成公私鑰文件
1、生成私鑰庫文件(因為keytool基于jdk, 所以需要提前安裝jdk),執(zhí)行后可得到privateKeys.keystore文件
謹記這里的密碼庫密碼storepass為“wu@2024555”,私鑰密碼keypass為"wu@private2024",后續(xù)還會使用到,私鑰別名為“privateKey”
注意這里密碼至少由字母和數(shù)字組成不少于6位的字符串!
keytool -genkeypair -keysize 1024 -validity 36500 -alias "privateKey" -keystore "privateKeys.keystore" -storepass "wu@2024555" -keypass "wu@private2024" -dname "CN=wu.com, OU=wu, O=wu, L=GUIZHOU, ST=GUIZHOU, C=CN"
| 參數(shù) | 說明 |
|---|---|
-genkeypair | 生成一對非對稱密鑰 |
-keysize | 密鑰長度 |
-validity | 有效期,單位天 |
-alias | 私鑰別名 |
-keystore | 私鑰文件名 |
-storepass | 訪問整個密碼庫的密碼 |
-keypass | 別名對應(yīng)私鑰的密碼 |
-dname | 證書持有者詳細信息 |
CN=localhost:CN是Common Name的縮寫,通常用于指定域名或IP地址
OU=localhost:OU是Organizational Unit的縮寫,表示組織單位
O=localhost:O是Organization的縮寫,表示組織名
L=SH:L是Locality的縮寫,表示城市或地區(qū)
ST=SH:ST是State的縮寫,表示州或省
C=CN:C是Country的縮寫,表示國家代碼 |
2、導(dǎo)出別名為"privateKey"的密鑰對的證書文件,執(zhí)行后得到certfile.cer文件
keytool -exportcert -alias "privateKey" -keystore "privateKeys.keystore" -storepass "wu@2024555" -file "certfile.cer"
3、將證書文件導(dǎo)入公鑰庫,用于生成公鑰文件publicCerts.keystore
keytool -import -alias "publicCert" -file "certfile.cer" -keystore "publicCerts.keystore" -storepass "wu@2024555"

4、以上步驟執(zhí)行完后,我們會得到3個文件,其中文件privateKeys.keystore用來為用戶生成License文件,不可泄漏!publicCerts.keystore隨應(yīng)用工程部署到客戶服務(wù)器,用其解密License文件并校驗其許可信息,提供給客戶;證書文件certfile.cer文件為臨時文件,可刪除,后續(xù)我們單獨用trueLicense生成提供給客戶的證書

2.2 license校驗?zāi)K
注:如下僅貼出核心代碼,完整代碼可見如下代碼倉庫:
https://gitee.com/wuhanxue/wu_study/tree/master/demo/license_demo
1、首先定義如下配置路徑,用于后續(xù)安裝、校驗證書
license: # 證書subject subject: license-test-web # 公鑰別稱 publicAlias: publicCert # 訪問公鑰庫的密碼 storePass: wu@2024555 # 證書路徑 licensePath: /data/license/license.lic # 公鑰路徑 publicKeysStorePath: /data/license/publicCerts.keystore
2、創(chuàng)建springboot項目license-client,刪除啟動類,將該項目作為核心校驗?zāi)K,后續(xù)引入其他項目中使用,項目依賴及配置如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>license-client</artifactId>
<version>1.0.0</version>
<name>license-client</name>
<description>license-client</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
<!-- Java Servlet API -->
<javax.servlet-api>4.0.1</javax.servlet-api>
<!-- Apache Commons系列公共庫 -->
<commons-lang3>3.7</commons-lang3>
<commons-io>2.6</commons-io>
<commons-codec>1.11</commons-codec>
<!-- Apache HttpClient -->
<httpclient>4.5.5</httpclient>
<!-- Fastjson -->
<fastjson>1.2.47</fastjson>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Commons -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec}</version>
</dependency>
<!-- Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient}</version>
</dependency>
<!-- Fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson}</version>
</dependency>
<!-- Java Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api}</version>
<scope>provided</scope>
</dependency>
<!-- Jackson對自動解析JSON和XML格式的支持 -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<!-- SLF4J和LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
<!-- License -->
<dependency>
<groupId>de.schlichtherle.truelicense</groupId>
<artifactId>truelicense-core</artifactId>
<version>1.33</version>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!-- SpringBoot的依賴配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>3、創(chuàng)建證書校驗配置實體類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LicenseVerifyParam {
/**
* 證書subject
*/
private String subject;
/**
* 公鑰別稱
*/
private String publicAlias;
/**
* 訪問公鑰庫的密碼
*/
private String storePass;
/**
* 證書生成路徑
*/
private String licensePath;
/**
* 密鑰庫存儲路徑
*/
private String publicKeysStorePath;
}4、為了實現(xiàn)還可通設(shè)備、ip等控制授權(quán),我們需要創(chuàng)建擴展證書管理器,如不需要的可以省略該步,使用LicenseManager即可
該類中拓展了獲取linux、window等系統(tǒng)下ip地址、mac地址、cpu、主板信息等操作,完整類方法可見代碼倉庫
import com.example.licenseclient.core.LicenseCheckModel;
import com.example.licenseclient.serverinfo.AbstractServerInfos;
import com.example.licenseclient.serverinfo.LinuxServerInfos;
import com.example.licenseclient.serverinfo.WindowsServerInfos;
import de.schlichtherle.license.*;
import de.schlichtherle.xml.GenericCertificate;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
/**
* @author benjamin5
* @Description 自定義LicenseManager,用于增加額外的服務(wù)器硬件信息校驗
* @createTime 2024/10/31
*/
public class CustomLicenseManager extends LicenseManager {
private static Logger logger = LogManager.getLogger(CustomLicenseManager.class);
//XML編碼
private static final String XML_CHARSET = "UTF-8";
//默認BUFSIZE
private static final int DEFAULT_BUFSIZE = 8 * 1024;
public CustomLicenseManager() {
}
public CustomLicenseManager(LicenseParam param) {
super(param);
}
/**
* @title create
* @description 復(fù)寫create方法
*/
@Override
protected synchronized byte[] create(
LicenseContent content,
LicenseNotary notary)
throws Exception {
initialize(content);
this.validateCreate(content);
final GenericCertificate certificate = notary.sign(content);
return getPrivacyGuard().cert2key(certificate);
}
/**
* @title install
* @description 復(fù)寫install方法,其中validate方法調(diào)用本類中的validate方法,校驗IP地址、Mac地址等其他信息
*/
@Override
protected synchronized LicenseContent install(
final byte[] key,
final LicenseNotary notary)
throws Exception {
final GenericCertificate certificate = getPrivacyGuard().key2cert(key);
System.out.println("certificate.getEncoded() = " + certificate.getEncoded());
notary.verify(certificate);
final LicenseContent content = (LicenseContent) this.load(certificate.getEncoded());
this.validate(content);
setLicenseKey(key);
setCertificate(certificate);
return content;
}
/**
* @title verify
* @description 復(fù)寫verify方法,調(diào)用本類中的validate方法,校驗IP地址、Mac地址等其他信息
*/
@Override
protected synchronized LicenseContent verify(final LicenseNotary notary)
throws Exception {
GenericCertificate certificate = getCertificate();
// Load license key from preferences,
final byte[] key = getLicenseKey();
if (null == key) {
throw new NoLicenseInstalledException(getLicenseParam().getSubject());
}
certificate = getPrivacyGuard().key2cert(key);
notary.verify(certificate);
final LicenseContent content = (LicenseContent) this.load(certificate.getEncoded());
this.validate(content);
setCertificate(certificate);
return content;
}
/**
* @title validateCreate
* @description 校驗生成證書的參數(shù)信息
*/
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("證書失效時間不能早于當(dāng)前時間");
}
if (null != notBefore && null != notAfter && notAfter.before(notBefore)) {
throw new LicenseContentException("證書生效時間不能晚于證書失效時間");
}
final String consumerType = content.getConsumerType();
if (null == consumerType) {
throw new LicenseContentException("用戶類型不能為空");
}
}
/**
* @title validate
* @description 復(fù)寫validate方法,增加IP地址、Mac地址等其他信息校驗
*/
@Override
protected synchronized void validate(final LicenseContent content)
throws LicenseContentException {
//1. 首先調(diào)用父類的validate方法
super.validate(content);
//2. 然后校驗自定義的License參數(shù)
//License中可被允許的參數(shù)信息
LicenseCheckModel expectedCheckModel = (LicenseCheckModel) content.getExtra();
if (expectedCheckModel != null) {
//當(dāng)前服務(wù)器真實的參數(shù)信息
LicenseCheckModel serverCheckModel = getServerInfos();
if (serverCheckModel != null) {
//校驗IP地址
if (!checkIpAddress(expectedCheckModel.getIpAddress(), serverCheckModel.getIpAddress())) {
throw new LicenseContentException("當(dāng)前服務(wù)器的IP沒在授權(quán)范圍內(nèi)");
}
//校驗Mac地址
if (!checkIpAddress(expectedCheckModel.getMacAddress(), serverCheckModel.getMacAddress())) {
throw new LicenseContentException("當(dāng)前服務(wù)器的Mac地址沒在授權(quán)范圍內(nèi)");
}
//校驗主板序列號
if (!checkSerial(expectedCheckModel.getMainBoardSerial(), serverCheckModel.getMainBoardSerial())) {
throw new LicenseContentException("當(dāng)前服務(wù)器的主板序列號沒在授權(quán)范圍內(nèi)");
}
//校驗CPU序列號
if (!checkSerial(expectedCheckModel.getCpuSerial(), serverCheckModel.getCpuSerial())) {
throw new LicenseContentException("當(dāng)前服務(wù)器的CPU序列號沒在授權(quán)范圍內(nèi)");
}
} else {
throw new LicenseContentException("不能獲取服務(wù)器硬件信息");
}
}
}
/**
* @title load
* @description 重寫XMLDecoder解析XML
*/
private Object load(String encoded) {
BufferedInputStream inputStream = null;
XMLDecoder decoder = null;
try {
inputStream = new BufferedInputStream(new ByteArrayInputStream(encoded.getBytes(XML_CHARSET)));
decoder = new XMLDecoder(new BufferedInputStream(inputStream, DEFAULT_BUFSIZE), null, null);
return decoder.readObject();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
try {
if (decoder != null) {
decoder.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
logger.error("XMLDecoder解析XML失敗", e);
}
}
return null;
}
/**
* @title getServerInfos
* @description 獲取當(dāng)前服務(wù)器需要額外校驗的License參數(shù)
*/
private LicenseCheckModel getServerInfos() {
//操作系統(tǒng)類型
String osName = System.getProperty("os.name").toLowerCase();
AbstractServerInfos abstractServerInfos = null;
//根據(jù)不同操作系統(tǒng)類型選擇不同的數(shù)據(jù)獲取方法
if (osName.startsWith("windows")) {
abstractServerInfos = new WindowsServerInfos();
} else if (osName.startsWith("linux")) {
abstractServerInfos = new LinuxServerInfos();
} else if (osName.startsWith("mac os")) {
return null;
} else {//其他服務(wù)器類型
abstractServerInfos = new LinuxServerInfos();
}
return abstractServerInfos.getServerInfos();
}
/**
* @title checkIpAddress
* @description 校驗當(dāng)前服務(wù)器的IP/Mac地址是否在可被允許的IP范圍內(nèi)<br/>
* 如果存在IP在可被允許的IP/Mac地址范圍內(nèi),則返回true
*/
private boolean checkIpAddress(List<String> expectedList, List<String> serverList) {
if (expectedList != null && expectedList.size() > 0) {
if (serverList != null && serverList.size() > 0) {
for (String expected : expectedList) {
if (serverList.contains(expected.trim())) {
return true;
}
}
}
return false;
} else {
return true;
}
}
/**
* @title checkSerial
* @description 校驗當(dāng)前服務(wù)器硬件(主板、CPU等)序列號是否在可允許范圍內(nèi)
*/
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;
}
}
}5、實現(xiàn)證書管理器LicenseManager生成器,這里我們通過雙檢鎖來安全輸出單例
import com.example.licenseclient.custom.CustomLicenseManager;
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;
}
}6、實現(xiàn)密鑰參數(shù)擴展類CustomKeyStoreParam,用于聲明密鑰、證書位置在指定路徑,而非項目中
import de.schlichtherle.license.AbstractKeyStoreParam;
import java.io.*;
/**
* @author benjamin5
* @Description 自定義KeyStoreParam,用于將公私鑰存儲文件存放到其他磁盤位置而不是項目中
* @createTime 2024/10/31
*/
public class CustomKeyStoreParam extends AbstractKeyStoreParam {
/**
* 公鑰/私鑰在磁盤上的存儲路徑
*/
private String storePath;
private String alias;
private String storePwd;
private String keyPwd;
public CustomKeyStoreParam(Class clazz, String resource,String alias,String storePwd,String keyPwd) {
super(clazz, resource);
this.storePath = resource;
this.alias = alias;
this.storePwd = storePwd;
this.keyPwd = keyPwd;
}
@Override
public String getAlias() {
return alias;
}
@Override
public String getStorePwd() {
return storePwd;
}
@Override
public String getKeyPwd() {
return keyPwd;
}
/**
* 復(fù)寫de.schlichtherle.license.AbstractKeyStoreParam的getStream()方法
* 用于將公私鑰存儲文件存放到其他磁盤位置而不是項目中
*/
@Override
public InputStream getStream() throws IOException {
final InputStream in = new FileInputStream(new File(storePath));
if (null == in){
throw new FileNotFoundException(storePath);
}
return in;
}
}7、實現(xiàn)證書安裝和校驗類LicenseVerify
import com.example.licenseclient.custom.CustomKeyStoreParam;
import de.schlichtherle.license.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;
/**
* @author benjamin5
* @Description License校驗類
* @createTime 2024/10/31
*/
public class LicenseVerify {
private static Logger logger = LogManager.getLogger(LicenseVerify.class);
/**
* @title install
* @description 安裝License證書
*/
public synchronized LicenseContent install(LicenseVerifyParam param){
LicenseContent result = null;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//1. 安裝證書
try{
LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
licenseManager.uninstall();
result = licenseManager.install(new File(param.getLicensePath()));
logger.info(MessageFormat.format("證書安裝成功,證書有效期:{0} - {1}",format.format(result.getNotBefore()),format.format(result.getNotAfter())));
}catch (Exception e){
logger.error("證書安裝失敗!",e);
}
return result;
}
/**
* @title verify
* @description 校驗License證書
*/
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(MessageFormat.format("證書校驗通過,證書有效期:{0} - {1}",format.format(licenseContent.getNotBefore()),format.format(licenseContent.getNotAfter())));
return true;
}catch (Exception e){
logger.error("證書校驗失??!",e);
return false;
}
}
/**
* @title initLicenseParam
* @description 初始化證書生成參數(shù)
*/
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);
}
}8、然后在項目啟動時安裝證書,通過ApplicationListener實現(xiàn)項目啟動觸發(fā)
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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;
/**
* @author benjamin5
* @Description 在項目啟動時安裝證書
* @createTime 2024/10/31
*/
@Component
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {
private static Logger logger = LogManager.getLogger(LicenseCheckListener.class);
/**
* 證書subject
*/
@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 onApplicationEvent(ContextRefreshedEvent event) {
//root application context 沒有parent
ApplicationContext context = event.getApplicationContext().getParent();
if (context == null) {
logger.info("++++++++ 開始安裝證書 ++++++++");
LicenseVerifyParam param = new LicenseVerifyParam();
param.setSubject(subject);
param.setPublicAlias(publicAlias);
param.setStorePass(storePass);
param.setLicensePath(licensePath);
param.setPublicKeysStorePath(publicKeysStorePath);
LicenseVerify licenseVerify = new LicenseVerify();
//安裝證書
licenseVerify.install(param);
logger.info("++++++++ 證書安裝結(jié)束 ++++++++");
}
}
}9、最后實現(xiàn)接口攔截器,在攔截器中校驗證書
import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* @author benjamin5
* @Description 證書校驗攔截器
* @createTime 2024/10/31
*/
public class LicenseCheckInterceptor implements HandlerInterceptor {
private static Logger logger = LogManager.getLogger(LicenseCheckInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
LicenseVerify licenseVerify = new LicenseVerify();
//校驗證書是否有效
boolean verifyResult = licenseVerify.verify();
if(verifyResult){
return true;
}else{
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
Map<String,String> result = new HashMap<>(1);
result.put("code","500");
result.put("msg","您的許可證無效或過期,請重新申請!");
response.getWriter().write(JSON.toJSONString(result));
return false;
}
}
}10、聲明攔截器
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 添加攔截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LicenseCheckInterceptor())
.addPathPatterns("/**")
// .excludePathPatterns("/license/generateLicense","/license/getServerInfos")
;
}
}2.3 license生成模塊
1、創(chuàng)建springboot項目license-server,引入依賴,注意將上述的license-client項目也引入進去,生成證書需要使用client中的接口
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>license-client</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>2、創(chuàng)建證書生成參數(shù)類,LicenseCheckModel子類代碼詳見代碼倉庫
@Data
public class LicenseCreatorParam implements Serializable {
private static final long serialVersionUID = -7793154252684580872L;
/**
* 證書subject
*/
private String subject;
/**
* 密鑰別稱
*/
private String privateAlias;
/**
* 密鑰密碼(需要妥善保管,不能讓使用者知道)
*/
private String keyPass;
/**
* 訪問秘鑰庫的密碼
*/
private String storePass;
/**
* 證書生成路徑
*/
private String licensePath;
/**
* 密鑰庫存儲路徑
*/
private String privateKeysStorePath;
/**
* 證書生效時間
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date issuedTime = new Date();
/**
* 證書失效時間
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date expiryTime;
/**
* 用戶類型
*/
private String consumerType = "user";
/**
* 用戶數(shù)量
*/
private Integer consumerAmount = 1;
/**
* 描述信息
*/
private String description = "";
/**
* 額外的服務(wù)器硬件校驗信息
*/
private LicenseCheckModel licenseCheckModel;
}3、創(chuàng)建證書生成類LicenseCreator
import com.example.licenseclient.custom.CustomKeyStoreParam;
import com.example.licenseclient.custom.CustomLicenseManager;
import de.schlichtherle.license.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.text.MessageFormat;
import java.util.prefs.Preferences;
/**
* License生成類
*
*/
public class LicenseCreator {
private static Logger logger = LogManager.getLogger(LicenseCreator.class);
/**
* CN=localhost:CN是Common Name的縮寫,通常用于指定域名或IP地址
* OU=localhost:OU是Organizational Unit的縮寫,表示組織單位
* O=localhost:O是Organization的縮寫,表示組織名
* L=SH:L是Locality的縮寫,表示城市或地區(qū)
* ST=SH:ST是State的縮寫,表示州或省
* C=CN:C是Country的縮寫,表示國家代碼
*/
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;
}
/**
* 生成License證書
* @return boolean
*/
public boolean generateLicense(){
try {
LicenseManager licenseManager = new CustomLicenseManager(initLicenseParam());
LicenseContent licenseContent = initLicenseContent();
licenseManager.store(licenseContent,new File(param.getLicensePath()));
return true;
}catch (Exception e){
logger.error(MessageFormat.format("證書生成失敗:{0}",param),e);
return false;
}
}
/**
* 初始化證書生成參數(shù)
* @return de.schlichtherle.license.LicenseParam
*/
private LicenseParam initLicenseParam(){
Preferences preferences = Preferences.userNodeForPackage(LicenseCreator.class);
//設(shè)置對證書內(nèi)容加密的秘鑰
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;
}
/**
* 設(shè)置證書生成正文信息
* @return de.schlichtherle.license.LicenseContent
*/
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());
//擴展校驗服務(wù)器硬件信息
licenseContent.setExtra(param.getLicenseCheckModel());
return licenseContent;
}
}4、最后聲明證書創(chuàng)建接口
@RestController
@RequestMapping("/license")
public class LicenseCreatorController {
/**
* 證書生成路徑
*/
@Value("${license.licensePath}")
private String licensePath;
@Value("${license.privateKeysStorePath}")
private String privateKeysStorePath;
@Value("${license.keyPass}")
private String keyPass;
@Value("${license.privateAlias}")
private String privateAlias;
/**
* 生成證書
*
* @param param 生成證書需要的參數(shù),如:{"subject":"ccx-models","privateAlias":"privateKey","keyPass":"5T7Zz5Y0dJFcqTxvzkH5LDGJJSGMzQ","storePass":"3538cef8e7","licensePath":"C:/Users/zifangsky/Desktop/license.lic","privateKeysStorePath":"C:/Users/zifangsky/Desktop/privateKeys.keystore","issuedTime":"2018-04-26 14:48:12","expiryTime":"2018-12-31 00:00:00","consumerType":"User","consumerAmount":1,"description":"這是證書描述信息","licenseCheckModel":{"ipAddress":["192.168.245.1","10.0.5.22"],"macAddress":["00-50-56-C0-00-01","50-7B-9D-F9-18-41"],"cpuSerial":"BFEBFBFF000406E3","mainBoardSerial":"L1HF65E00X9"}}
*
*/
@RequestMapping(value = "/generateLicense", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public Map<String, Object> generateLicense(@RequestBody(required = true) LicenseCreatorParam param) {
Map<String, Object> resultMap = new HashMap<>(2);
if (StringUtils.isBlank(param.getLicensePath())) {
param.setLicensePath(licensePath);
}
if(StringUtils.isBlank(param.getPrivateKeysStorePath())){
URL url = null;
try {
url = ResourceUtils.getURL(privateKeysStorePath);
param.setPrivateKeysStorePath(url.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
if(StringUtils.isBlank(param.getKeyPass())){
param.setKeyPass(keyPass);
}
if(StringUtils.isBlank(param.getPrivateAlias())){
param.setPrivateAlias(privateAlias);
}
LicenseCreator licenseCreator = new LicenseCreator(param);
boolean result = licenseCreator.generateLicense();
if (result) {
resultMap.put("result", "ok");
resultMap.put("msg", param);
} else {
resultMap.put("result", "error");
resultMap.put("msg", "證書文件生成失??!");
}
return resultMap;
}
}5、配置文件聲明
server: port: 18099 license: # 生成證書存放位置,也可在生成接口參數(shù)中指定 licensePath: /Users/wuhanxue/Downloads/license/license.lic # 私鑰庫文件位置 privateKeysStorePath: classpath:key/privateKeys.keystore # 私鑰訪問密碼 keyPass: wu@private2024 # 私鑰別名 privateAlias: privateKey
6、我們在resources資源目錄下創(chuàng)建key目錄,并將之間生成的私鑰庫文件privateKeys.keystore放到該文件夾下,后續(xù)用來生成證書

7、啟動該項目,然后調(diào)用證書生成接口,得到證書文件license.lic
接口參數(shù)說明:
- subject: 證書主題,可以以授權(quán)的服務(wù)名來命名,不允許使用中文
- storePass:訪問密鑰庫密碼
- licensePath:生成的證書存儲位置和證書文件名
- expiryTime: 過期時間
- description:描述
- licenseCheckModel: 擴展配置類,詳見代碼倉庫

得到的證書文件license.lic、公鑰文件和密鑰庫密碼storePass我們需要提供給客戶,當(dāng)然密碼可以提前配置在服務(wù)中,僅提供公鑰和證書文件給客戶即可。
2.4 測試模塊
1、新建一個spring web服務(wù),用于測試證書校驗
2、引入license-client依賴
<dependency>
<groupId>com.example</groupId>
<artifactId>license-client</artifactId>
<version>1.0.0</version>
</dependency>3、配置文件聲明
server: port: 1888 license: # 證書subject subject: license-test-web # 公鑰別稱 publicAlias: publicCert # 訪問公鑰庫的密碼 storePass: wu@2024555 # 證書路徑 licensePath: /Users/wuhanxue/Downloads/key/license.lic # 公鑰路徑 publicKeysStorePath: /Users/wuhanxue/Downloads/key/publicCerts.keystore
4、測試接口
@RestController
public class TestController {
@GetMapping("test")
public String test(){
return "test";
}
}5、啟動類添加bean掃描路徑@ComponentScan(basePackages = {"com.example.*"})
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.*"})
public class LicenseTestWebApplication {
public static void main(String[] args) {
SpringApplication.run(LicenseTestWebApplication.class, args);
}
}5、啟動項目
顯示證書安裝成功

6、訪問測試接口

成功返回信息,且有校驗通過提示,說明校驗成功

7、我們繼續(xù)測試校驗不通過的場景,重新生成license文件,并將有效期調(diào)整為1分鐘后,然后等待2分鐘再重啟項目,注意重新生成證書后要重新啟動項目,讓項目重新加載證書
8、首先可以看到啟動項目時已經(jīng)是一分鐘后了,安裝實際失敗了

9、調(diào)用會顯示證書過期,說明正常

10、我們再模擬證書安裝時是有效期內(nèi),調(diào)用時已經(jīng)過了有效期的場景,將有效期調(diào)整為5分鐘后,然后馬上重啟項目,在5分鐘后調(diào)用接口,接口顯示已過期,符合預(yù)期


2.5 完整代碼
完整代碼可見如下代碼倉庫:https://gitee.com/wuhanxue/wu_study/tree/master/demo/license_demo
3.總結(jié)
如上我們演示了trueLicense生成證書及證書校驗的流程,如上演示中我并未針對設(shè)備、ip等進行演示,但代碼倉庫中有對應(yīng)代碼,大家感興趣的可以自行驗證。
到此這篇關(guān)于Java利用trueLicense實現(xiàn)項目離線證書授權(quán)操作步驟的文章就介紹到這了,更多相關(guān)java trueLicense項目離線證書授權(quán)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實現(xiàn)隊列數(shù)據(jù)結(jié)構(gòu)代碼詳解
這篇文章主要介紹了java實現(xiàn)隊列數(shù)據(jù)結(jié)構(gòu)代碼詳解,簡單介紹了隊列結(jié)構(gòu)以應(yīng)用場景,涉及詳細實現(xiàn)代碼,還是比較不錯的,這里分享給大家,需要的朋友可以參考下。2017-11-11
base64_encode和base64_decode的JAVA實現(xiàn)
Base64 編碼其實是將3個8位字節(jié)轉(zhuǎn)換為4個6位這4個六位字節(jié) 其實仍然是8位,只不過高兩位被設(shè)置為0. 當(dāng)一個字節(jié)只有6位有效時,它的取值空間為0 到 2的6次方減1 即63,也就是說被轉(zhuǎn)換的Base64編碼的每一個編碼的取值空間為(0~63).需要的朋友可以參考下2016-04-04
Java高并發(fā)之CyclicBarrier的用法詳解
CyclicBarrier 是 Java 中的一種同步工具,它可以讓多個線程在一個屏障點處等待,直到所有線程都到達該點后,才能繼續(xù)執(zhí)行。本文就來和大家聊聊它的用法,需要的可以參考一下2023-03-03
使用java生成json時產(chǎn)生棧溢出錯誤問題及解決方案
這篇文章主要介紹了使用java生成json時產(chǎn)生棧溢出錯誤問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
java中統(tǒng)一返回前端格式及統(tǒng)一結(jié)果處理返回詳解
這篇文章主要介紹了統(tǒng)一結(jié)果處理的重要性,以及如何在SpringBoot項目中定義和使用統(tǒng)一結(jié)果返回類,通過構(gòu)造器私有化和靜態(tài)方法ok、error,提供了成功和失敗的統(tǒng)一響應(yīng)格式,需要的朋友可以參考下2025-02-02

