亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java利用trueLicense實(shí)現(xiàn)項(xiàng)目離線(xiàn)證書(shū)授權(quán)操作步驟

 更新時(shí)間:2024年11月26日 14:39:51   作者:wu@55555  
文章介紹了如何使用trueLicense實(shí)現(xiàn)離線(xiàn)授權(quán)控制,包括生成公私鑰、創(chuàng)建證書(shū)校驗(yàn)?zāi)K、生成證書(shū)模塊和測(cè)試模塊,通過(guò)這種方式,可以控制用戶(hù)使用的項(xiàng)目模塊、授權(quán)周期、使用的設(shè)備和服務(wù)器,感興趣的朋友跟隨小編一起看看吧

0.引言

我們?cè)趯?shí)際項(xiàng)目中,會(huì)遇到開(kāi)發(fā)的項(xiàng)目部署在服務(wù)器上,但可能要控制權(quán)限、控制項(xiàng)目授權(quán)周期等,部署的環(huán)境可能純內(nèi)網(wǎng)使用,因此通過(guò)網(wǎng)絡(luò)接口控制就不可行了,我們期望一種分發(fā)授權(quán)證書(shū)的形式,通過(guò)部署證書(shū)的形式,離線(xiàn)控制用戶(hù)能使用這個(gè)項(xiàng)目的哪個(gè)模塊、使用多久,甚至使用用戶(hù)的哪些設(shè)備、哪臺(tái)服務(wù)器可以使用。

今天我們來(lái)看看這樣的需求如何實(shí)現(xiàn)

1. trueLicense簡(jiǎn)介

1.1 原理簡(jiǎn)介

我們要實(shí)現(xiàn)的離線(xiàn)校驗(yàn),實(shí)際上就是通過(guò)公私鑰+證書(shū)的形式來(lái)實(shí)現(xiàn)的,首先生成公私鑰,然后利用私鑰生成證書(shū),比如x509證書(shū)格式,x509證書(shū)由用戶(hù)公共密鑰和用戶(hù)標(biāo)識(shí)符組成。此外還包括版本號(hào)、證書(shū)序列號(hào)、CA標(biāo)識(shí)符、簽名算法標(biāo)識(shí)、簽發(fā)者名稱(chēng)、證書(shū)有效期等信息

我們的核心目的就是要生成的證書(shū)中包含有效期,即可實(shí)現(xiàn)授權(quán)有效期,然后通過(guò)接口攔截器,每次訪(fǎng)問(wèn)接口時(shí)利用公鑰對(duì)證書(shū)進(jìn)行校驗(yàn),查看證書(shū)是否合法、是否在有效期內(nèi),即可實(shí)現(xiàn)我們進(jìn)行離線(xiàn)控制的目的。

1.2 公鑰私鑰和證書(shū)

部分同學(xué)如果沒(méi)接觸過(guò)加密和驗(yàn)簽的,可能對(duì)公私鑰和證書(shū)沒(méi)什么概念,所以我們先正對(duì)這幾個(gè)概念做個(gè)解釋?zhuān)奖愦蠹依斫狻?/p>

什么是公鑰和私鑰
‌公鑰和私鑰是一對(duì)相互匹配的密鑰,用于加密和解密數(shù)據(jù)。‌ 公鑰用于加密數(shù)據(jù),而私鑰用于解密數(shù)據(jù)。公鑰可以公開(kāi),任何人都可以使用,而私鑰必須保密,只有持有者才能使用。一般會(huì)把公鑰提供給客戶(hù),用于加密,私鑰保留在自己側(cè),用于解密。

那么當(dāng)自己需要加密數(shù)據(jù)發(fā)送給客戶(hù)時(shí)怎么辦呢? 這就需要客戶(hù)再生成一對(duì)公私鑰,由客戶(hù)保留私鑰,我方保留公鑰,發(fā)送數(shù)據(jù)時(shí),我們使用客戶(hù)的公鑰加密數(shù)據(jù),客戶(hù)使用自己的私鑰進(jìn)行解密

公私鑰一般用于非對(duì)稱(chēng)加密中,與對(duì)稱(chēng)加密最大的不同就是,對(duì)稱(chēng)加密加密方和解密方使用的都是同一個(gè)密鑰,在密鑰交換過(guò)程中可能會(huì)產(chǎn)生泄漏的風(fēng)險(xiǎn),而密鑰對(duì)則只用交換雙方的公鑰,提高了安全性

公私鑰長(zhǎng)什么樣呢,實(shí)際就是兩個(gè)字符串,當(dāng)然也可以保存為文件,但實(shí)質(zhì)就是字符串,如下我們生成的一對(duì)公私鑰,一般私鑰會(huì)比公鑰長(zhǎng):

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ū)
電子證書(shū),通常指的是數(shù)字證書(shū)(Digital Certificate),在信息技術(shù)領(lǐng)域,它是一種用于在網(wǎng)絡(luò)上驗(yàn)證身份和保障通信安全的電子證明。電子證書(shū)包含以下幾個(gè)關(guān)鍵組成部分:

證書(shū)持有者的公鑰:這是證書(shū)的主要部分,用于加密信息,只有證書(shū)持有者的私鑰可以解密。
證書(shū)持有者的身份信息:這包括持有者的名稱(chēng)或其他標(biāo)識(shí)信息,用于驗(yàn)證公鑰所屬的身份。
證書(shū)簽發(fā)機(jī)構(gòu)的數(shù)字簽名:證書(shū)由一個(gè)可信的第三方機(jī)構(gòu)——證書(shū)授權(quán)中心(Certificate Authority,簡(jiǎn)稱(chēng)CA)簽發(fā)。CA通過(guò)其私鑰對(duì)證書(shū)內(nèi)容進(jìn)行數(shù)字簽名,以確保證書(shū)內(nèi)容的真實(shí)性和完整性。
有效期:證書(shū)在特定的時(shí)間段內(nèi)有效,過(guò)期后需要更新或更換。
證書(shū)使用目的:證書(shū)可能用于不同的目的,如網(wǎng)頁(yè)安全瀏覽(HTTPS)、電子郵件加密、數(shù)字簽名等。

電子證書(shū)的一般可用于:

身份驗(yàn)證:確認(rèn)網(wǎng)絡(luò)上的通信實(shí)體是真實(shí)的,不是假冒的。
數(shù)據(jù)加密:使用公鑰加密數(shù)據(jù),只有持有對(duì)應(yīng)私鑰的人才能解密。
數(shù)據(jù)完整性:確保在傳輸過(guò)程中數(shù)據(jù)沒(méi)有被篡改。

證書(shū)本身也可以用一串字符串表示,更直觀的我們可以在谷歌瀏覽器上點(diǎn)擊左側(cè)地址欄的圖標(biāo)查看網(wǎng)址https證書(shū)信息

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

1.3 trueLicense簡(jiǎn)介

有了以上基本概念后,我們?cè)賮?lái)介紹trueLicense:

TrueLicense是一個(gè)開(kāi)源的證書(shū)管理引擎,主要用于軟件產(chǎn)品的授權(quán)管理。它的主要功能是在軟件項(xiàng)目交付給客戶(hù)后,通過(guò)簽名機(jī)制來(lái)確??蛻?hù)不能隨意使用該項(xiàng)目。TrueLicense的授權(quán)機(jī)制基于以下原理:

生成密鑰對(duì):使用工具(如KeyTool)生成包含私鑰和公鑰的密鑰對(duì)。
授權(quán)者保留私鑰:授權(quán)者使用私鑰對(duì)包含授權(quán)信息(如使用截止日期、MAC地址等)的license進(jìn)行數(shù)字簽名。
公鑰給使用者:將公鑰放在驗(yàn)證代碼中使用,用于驗(yàn)證license是否符合使用條件。
TrueLicense的使用場(chǎng)景包括設(shè)定軟件的試用期、綁定特定IP或MAC地址等。通過(guò)這種方式,可以在不修改源代碼的情況下,通過(guò)重新生成license來(lái)延長(zhǎng)試用期或修改授權(quán)條件。

前面我們提到過(guò),我們的核心目的就是要生成的證書(shū)中包含有效期,即可實(shí)現(xiàn)授權(quán)有效期,然后通過(guò)接口攔截器,每次訪(fǎng)問(wèn)接口時(shí)利用公鑰對(duì)證書(shū)進(jìn)行校驗(yàn),查看證書(shū)是否合法、是否在有效期內(nèi),而trueLicense就是幫助我們簡(jiǎn)化這一流程,他內(nèi)部封裝了這一系列的操作,我們只需要簡(jiǎn)單的集成即可實(shí)現(xiàn)功能

下面我們來(lái)具體實(shí)操。

2. 操作步驟

首先先介紹下,我們本次演示要構(gòu)造的模塊,一共分為3個(gè)模塊:

  • 證書(shū)校驗(yàn)?zāi)K:集成證書(shū)校驗(yàn)核心邏輯,作為工具包引入到需要進(jìn)行離線(xiàn)授權(quán)的服務(wù)中
  • 證書(shū)生成模塊:用于生成證書(shū),或?qū)ψC書(shū)進(jìn)行續(xù)約
  • 測(cè)試模塊:?jiǎn)为?dú)的一個(gè)用于測(cè)試離線(xiàn)授權(quán)邏輯的模塊,模擬需要進(jìn)行離線(xiàn)授權(quán)的web服務(wù)

2.1 生成公私鑰

2.1.1 keyTool工具介紹

前面提到我們需要生成一個(gè)公私鑰,然后再生成證書(shū),那么公私鑰的生成就可以利用java自帶的KeyTool工具來(lái)實(shí)現(xiàn)

KeyTool 是一個(gè)Java密鑰和證書(shū)管理工具,它是Java SDK的一部分。KeyTool用于管理密鑰庫(kù)(KeyStore),在密鑰庫(kù)中可以存儲(chǔ)私鑰和公鑰證書(shū)。以下是KeyTool的一些主要功能和用途:

生成密鑰對(duì):KeyTool可以生成密鑰對(duì)(公鑰和私鑰),這是加密和安全通信的基礎(chǔ)。
管理密鑰庫(kù):它可以創(chuàng)建和管理密鑰庫(kù)文件,這些文件通常具有.keystore擴(kuò)展名。密鑰庫(kù)用于存儲(chǔ)密鑰和證書(shū)。
導(dǎo)入和導(dǎo)出證書(shū):KeyTool允許用戶(hù)將證書(shū)導(dǎo)入到密鑰庫(kù)中,或者從密鑰庫(kù)中導(dǎo)出證書(shū)。
生成證書(shū)請(qǐng)求:可以生成證書(shū)簽名請(qǐng)求(CSR),這是發(fā)送給證書(shū)頒發(fā)機(jī)構(gòu)(CA)以獲取證書(shū)的過(guò)程的一部分。
查看和管理證書(shū):可以查看密鑰庫(kù)中的證書(shū)詳細(xì)信息,以及設(shè)置或更改其屬性。
設(shè)置別名:在密鑰庫(kù)中,可以為密鑰和證書(shū)設(shè)置別名,以便更容易地引用它們。

以下是KeyTool的一些常用命令:

keytool -genkeypair:生成密鑰對(duì)。
keytool -list:列出密鑰庫(kù)中的條目。
keytool -importcert:導(dǎo)入證書(shū)或證書(shū)鏈。
keytool -exportcert:導(dǎo)出證書(shū)。
keytool -keystore:指定密鑰庫(kù)的名稱(chēng)和位置

2.1.2 生成公私鑰文件

1、生成私鑰庫(kù)文件(因?yàn)閗eytool基于jdk, 所以需要提前安裝jdk),執(zhí)行后可得到privateKeys.keystore文件

謹(jǐn)記這里的密碼庫(kù)密碼storepass為“wu@2024555”,私鑰密碼keypass為"wu@private2024",后續(xù)還會(huì)使用到,私鑰別名為“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ù)說(shuō)明
-genkeypair生成一對(duì)非對(duì)稱(chēng)密鑰
-keysize密鑰長(zhǎng)度
-validity有效期,單位天
-alias私鑰別名
-keystore私鑰文件名
-storepass訪(fǎng)問(wèn)整個(gè)密碼庫(kù)的密碼
-keypass別名對(duì)應(yīng)私鑰的密碼
-dname證書(shū)持有者詳細(xì)信息

CN=localhost:CN是Common Name的縮寫(xiě),通常用于指定域名或IP地址
OU=localhost:OU是Organizational Unit的縮寫(xiě),表示組織單位
O=localhost:O是Organization的縮寫(xiě),表示組織名
L=SH:L是Locality的縮寫(xiě),表示城市或地區(qū)
ST=SH:ST是State的縮寫(xiě),表示州或省
C=CN:C是Country的縮寫(xiě),表示國(guó)家代碼 |

2、導(dǎo)出別名為"privateKey"的密鑰對(duì)的證書(shū)文件,執(zhí)行后得到certfile.cer文件

keytool -exportcert -alias "privateKey" -keystore "privateKeys.keystore" -storepass "wu@2024555" -file "certfile.cer"

3、將證書(shū)文件導(dǎo)入公鑰庫(kù),用于生成公鑰文件publicCerts.keystore

keytool -import -alias "publicCert" -file "certfile.cer" -keystore "publicCerts.keystore" -storepass "wu@2024555"

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

2.2 license校驗(yàn)?zāi)K

注:如下僅貼出核心代碼,完整代碼可見(jiàn)如下代碼倉(cāng)庫(kù):
https://gitee.com/wuhanxue/wu_study/tree/master/demo/license_demo

1、首先定義如下配置路徑,用于后續(xù)安裝、校驗(yàn)證書(shū)

license:
  # 證書(shū)subject
  subject: license-test-web
  # 公鑰別稱(chēng)
  publicAlias: publicCert
  # 訪(fǎng)問(wèn)公鑰庫(kù)的密碼
  storePass: wu@2024555
  # 證書(shū)路徑
  licensePath: /data/license/license.lic
  # 公鑰路徑
  publicKeysStorePath: /data/license/publicCerts.keystore

2、創(chuàng)建springboot項(xiàng)目license-client,刪除啟動(dòng)類(lèi),將該項(xiàng)目作為核心校驗(yàn)?zāi)K,后續(xù)引入其他項(xiàng)目中使用,項(xiàng)目依賴(lài)及配置如下

<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系列公共庫(kù) -->
        <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對(duì)自動(dòng)解析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的依賴(lài)配置-->
            <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)建證書(shū)校驗(yàn)配置實(shí)體類(lèi)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LicenseVerifyParam {
    /**
     * 證書(shū)subject
     */
    private String subject;
    /**
     * 公鑰別稱(chēng)
     */
    private String publicAlias;
    /**
     * 訪(fǎng)問(wèn)公鑰庫(kù)的密碼
     */
    private String storePass;
    /**
     * 證書(shū)生成路徑
     */
    private String licensePath;
    /**
     * 密鑰庫(kù)存儲(chǔ)路徑
     */
    private String publicKeysStorePath;
}

4、為了實(shí)現(xiàn)還可通設(shè)備、ip等控制授權(quán),我們需要?jiǎng)?chuàng)建擴(kuò)展證書(shū)管理器,如不需要的可以省略該步,使用LicenseManager即可

該類(lèi)中拓展了獲取linux、window等系統(tǒng)下ip地址、mac地址、cpu、主板信息等操作,完整類(lèi)方法可見(jiàn)代碼倉(cāng)庫(kù)

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ù)器硬件信息校驗(yàn)
 * @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";
    //默認(rèn)BUFSIZE
    private static final int DEFAULT_BUFSIZE = 8 * 1024;
    public CustomLicenseManager() {
    }
    public CustomLicenseManager(LicenseParam param) {
        super(param);
    }
    /**
     * @title create
     * @description 復(fù)寫(xiě)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ù)寫(xiě)install方法,其中validate方法調(diào)用本類(lèi)中的validate方法,校驗(yàn)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ù)寫(xiě)verify方法,調(diào)用本類(lèi)中的validate方法,校驗(yàn)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 校驗(yàn)生成證書(shū)的參數(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("證書(shū)失效時(shí)間不能早于當(dāng)前時(shí)間");
        }
        if (null != notBefore && null != notAfter && notAfter.before(notBefore)) {
            throw new LicenseContentException("證書(shū)生效時(shí)間不能晚于證書(shū)失效時(shí)間");
        }
        final String consumerType = content.getConsumerType();
        if (null == consumerType) {
            throw new LicenseContentException("用戶(hù)類(lèi)型不能為空");
        }
    }
    /**
     * @title validate
     * @description 復(fù)寫(xiě)validate方法,增加IP地址、Mac地址等其他信息校驗(yàn)
     */
    @Override
    protected synchronized void validate(final LicenseContent content)
            throws LicenseContentException {
        //1. 首先調(diào)用父類(lèi)的validate方法
        super.validate(content);
        //2. 然后校驗(yàn)自定義的License參數(shù)
        //License中可被允許的參數(shù)信息
        LicenseCheckModel expectedCheckModel = (LicenseCheckModel) content.getExtra();
        if (expectedCheckModel != null) {
            //當(dāng)前服務(wù)器真實(shí)的參數(shù)信息
            LicenseCheckModel serverCheckModel = getServerInfos();
            if (serverCheckModel != null) {
                //校驗(yàn)IP地址
                if (!checkIpAddress(expectedCheckModel.getIpAddress(), serverCheckModel.getIpAddress())) {
                    throw new LicenseContentException("當(dāng)前服務(wù)器的IP沒(méi)在授權(quán)范圍內(nèi)");
                }
                //校驗(yàn)Mac地址
                if (!checkIpAddress(expectedCheckModel.getMacAddress(), serverCheckModel.getMacAddress())) {
                    throw new LicenseContentException("當(dāng)前服務(wù)器的Mac地址沒(méi)在授權(quán)范圍內(nèi)");
                }
                //校驗(yàn)主板序列號(hào)
                if (!checkSerial(expectedCheckModel.getMainBoardSerial(), serverCheckModel.getMainBoardSerial())) {
                    throw new LicenseContentException("當(dāng)前服務(wù)器的主板序列號(hào)沒(méi)在授權(quán)范圍內(nèi)");
                }
                //校驗(yàn)CPU序列號(hào)
                if (!checkSerial(expectedCheckModel.getCpuSerial(), serverCheckModel.getCpuSerial())) {
                    throw new LicenseContentException("當(dāng)前服務(wù)器的CPU序列號(hào)沒(méi)在授權(quán)范圍內(nèi)");
                }
            } else {
                throw new LicenseContentException("不能獲取服務(wù)器硬件信息");
            }
        }
    }
    /**
     * @title load
     * @description 重寫(xiě)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ù)器需要額外校驗(yàn)的License參數(shù)
     */
    private LicenseCheckModel getServerInfos() {
        //操作系統(tǒng)類(lèi)型
        String osName = System.getProperty("os.name").toLowerCase();
        AbstractServerInfos abstractServerInfos = null;
        //根據(jù)不同操作系統(tǒng)類(lèi)型選擇不同的數(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ù)器類(lèi)型
            abstractServerInfos = new LinuxServerInfos();
        }
        return abstractServerInfos.getServerInfos();
    }
    /**
     * @title checkIpAddress
     * @description 校驗(yàn)當(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 校驗(yàn)當(dāng)前服務(wù)器硬件(主板、CPU等)序列號(hào)是否在可允許范圍內(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、實(shí)現(xiàn)證書(shū)管理器LicenseManager生成器,這里我們通過(guò)雙檢鎖來(lái)安全輸出單例

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、實(shí)現(xiàn)密鑰參數(shù)擴(kuò)展類(lèi)CustomKeyStoreParam,用于聲明密鑰、證書(shū)位置在指定路徑,而非項(xiàng)目中

import de.schlichtherle.license.AbstractKeyStoreParam;
import java.io.*;
/**
 * @author benjamin5
 * @Description 自定義KeyStoreParam,用于將公私鑰存儲(chǔ)文件存放到其他磁盤(pán)位置而不是項(xiàng)目中
 * @createTime 2024/10/31
 */
public class CustomKeyStoreParam extends AbstractKeyStoreParam {
    /**
     * 公鑰/私鑰在磁盤(pán)上的存儲(chǔ)路徑
     */
    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ù)寫(xiě)de.schlichtherle.license.AbstractKeyStoreParam的getStream()方法
     * 用于將公私鑰存儲(chǔ)文件存放到其他磁盤(pán)位置而不是項(xiàng)目中
     */
    @Override
    public InputStream getStream() throws IOException {
        final InputStream in = new FileInputStream(new File(storePath));
        if (null == in){
            throw new FileNotFoundException(storePath);
        }
        return in;
    }
}

7、實(shí)現(xiàn)證書(shū)安裝和校驗(yàn)類(lèi)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校驗(yàn)類(lèi)
 * @createTime 2024/10/31
 */
public class LicenseVerify {
    private static Logger logger = LogManager.getLogger(LicenseVerify.class);
    /**
     * @title install
     * @description 安裝License證書(shū)
     */
    public synchronized LicenseContent install(LicenseVerifyParam param){
        LicenseContent result = null;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1. 安裝證書(shū)
        try{
            LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
            licenseManager.uninstall();
            result = licenseManager.install(new File(param.getLicensePath()));
            logger.info(MessageFormat.format("證書(shū)安裝成功,證書(shū)有效期:{0} - {1}",format.format(result.getNotBefore()),format.format(result.getNotAfter())));
        }catch (Exception e){
            logger.error("證書(shū)安裝失??!",e);
        }
        return result;
    }
    /**
     * @title verify
     * @description 校驗(yàn)License證書(shū)
     */
    public boolean verify(){
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //2. 校驗(yàn)證書(shū)
        try {
            LicenseContent licenseContent = licenseManager.verify();
            System.out.println(MessageFormat.format("證書(shū)校驗(yàn)通過(guò),證書(shū)有效期:{0} - {1}",format.format(licenseContent.getNotBefore()),format.format(licenseContent.getNotAfter())));
            return true;
        }catch (Exception e){
            logger.error("證書(shū)校驗(yàn)失??!",e);
            return false;
        }
    }
    /**
     * @title initLicenseParam
     * @description 初始化證書(shū)生成參數(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、然后在項(xiàng)目啟動(dòng)時(shí)安裝證書(shū),通過(guò)ApplicationListener實(shí)現(xiàn)項(xiàng)目啟動(dòng)觸發(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 在項(xiàng)目啟動(dòng)時(shí)安裝證書(shū)
 * @createTime 2024/10/31
 */
@Component
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger logger = LogManager.getLogger(LicenseCheckListener.class);
    /**
     * 證書(shū)subject
     */
    @Value("${license.subject}")
    private String subject;
    /**
     * 公鑰別稱(chēng)
     */
    @Value("${license.publicAlias}")
    private String publicAlias;
    /**
     * 訪(fǎng)問(wèn)公鑰庫(kù)的密碼
     */
    @Value("${license.storePass}")
    private String storePass;
    /**
     * 證書(shū)生成路徑
     */
    @Value("${license.licensePath}")
    private String licensePath;
    /**
     * 密鑰庫(kù)存儲(chǔ)路徑
     */
    @Value("${license.publicKeysStorePath}")
    private String publicKeysStorePath;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //root application context 沒(méi)有parent
        ApplicationContext context = event.getApplicationContext().getParent();
        if (context == null) {
            logger.info("++++++++ 開(kāi)始安裝證書(shū) ++++++++");
            LicenseVerifyParam param = new LicenseVerifyParam();
            param.setSubject(subject);
            param.setPublicAlias(publicAlias);
            param.setStorePass(storePass);
            param.setLicensePath(licensePath);
            param.setPublicKeysStorePath(publicKeysStorePath);
            LicenseVerify licenseVerify = new LicenseVerify();
            //安裝證書(shū)
            licenseVerify.install(param);
            logger.info("++++++++ 證書(shū)安裝結(jié)束 ++++++++");
        }
    }
}

9、最后實(shí)現(xiàn)接口攔截器,在攔截器中校驗(yàn)證書(shū)

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 證書(shū)校驗(yàn)攔截器
 * @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();
        //校驗(yàn)證書(shū)是否有效
        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","您的許可證無(wú)效或過(guò)期,請(qǐng)重新申請(qǐng)!");
            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項(xiàng)目license-server,引入依賴(lài),注意將上述的license-client項(xiàng)目也引入進(jìn)去,生成證書(shū)需要使用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ū)生成參數(shù)類(lèi),LicenseCheckModel子類(lèi)代碼詳見(jiàn)代碼倉(cāng)庫(kù)

@Data
public class LicenseCreatorParam implements Serializable {
    private static final long serialVersionUID = -7793154252684580872L;
    /**
     * 證書(shū)subject
     */
    private String subject;
    /**
     * 密鑰別稱(chēng)
     */
    private String privateAlias;
    /**
     * 密鑰密碼(需要妥善保管,不能讓使用者知道)
     */
    private String keyPass;
    /**
     * 訪(fǎng)問(wèn)秘鑰庫(kù)的密碼
     */
    private String storePass;
    /**
     * 證書(shū)生成路徑
     */
    private String licensePath;
    /**
     * 密鑰庫(kù)存儲(chǔ)路徑
     */
    private String privateKeysStorePath;
    /**
     * 證書(shū)生效時(shí)間
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date issuedTime = new Date();
    /**
     * 證書(shū)失效時(shí)間
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date expiryTime;
    /**
     * 用戶(hù)類(lèi)型
     */
    private String consumerType = "user";
    /**
     * 用戶(hù)數(shù)量
     */
    private Integer consumerAmount = 1;
    /**
     * 描述信息
     */
    private String description = "";
    /**
     * 額外的服務(wù)器硬件校驗(yàn)信息
     */
    private LicenseCheckModel licenseCheckModel;
}

3、創(chuàng)建證書(shū)生成類(lèi)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生成類(lèi)
 *
 */
public class LicenseCreator {
    private static Logger logger = LogManager.getLogger(LicenseCreator.class);
    /**
     * CN=localhost:CN是Common Name的縮寫(xiě),通常用于指定域名或IP地址
     * OU=localhost:OU是Organizational Unit的縮寫(xiě),表示組織單位
     * O=localhost:O是Organization的縮寫(xiě),表示組織名
     * L=SH:L是Locality的縮寫(xiě),表示城市或地區(qū)
     * ST=SH:ST是State的縮寫(xiě),表示州或省
     * C=CN:C是Country的縮寫(xiě),表示國(guó)家代碼
     */
    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證書(shū)
     * @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("證書(shū)生成失敗:{0}",param),e);
            return false;
        }
    }
    /**
     * 初始化證書(shū)生成參數(shù)
     * @return de.schlichtherle.license.LicenseParam
     */
    private LicenseParam initLicenseParam(){
        Preferences preferences = Preferences.userNodeForPackage(LicenseCreator.class);
        //設(shè)置對(duì)證書(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è)置證書(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());
        //擴(kuò)展校驗(yàn)服務(wù)器硬件信息
        licenseContent.setExtra(param.getLicenseCheckModel());
        return licenseContent;
    }
}

4、最后聲明證書(shū)創(chuàng)建接口

@RestController
@RequestMapping("/license")
public class LicenseCreatorController {
    /**
     * 證書(shū)生成路徑
     */
    @Value("${license.licensePath}")
    private String licensePath;
    @Value("${license.privateKeysStorePath}")
    private String privateKeysStorePath;
    @Value("${license.keyPass}")
    private String keyPass;
    @Value("${license.privateAlias}")
    private String privateAlias;
    /**
     * 生成證書(shū)
     *
     * @param param 生成證書(shū)需要的參數(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":"這是證書(shū)描述信息","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", "證書(shū)文件生成失?。?);
        }
        return resultMap;
    }
}

5、配置文件聲明

server:
  port: 18099
license:
  # 生成證書(shū)存放位置,也可在生成接口參數(shù)中指定
  licensePath: /Users/wuhanxue/Downloads/license/license.lic
  # 私鑰庫(kù)文件位置
  privateKeysStorePath: classpath:key/privateKeys.keystore
  # 私鑰訪(fǎng)問(wèn)密碼
  keyPass: wu@private2024
  # 私鑰別名
  privateAlias: privateKey

6、我們?cè)趓esources資源目錄下創(chuàng)建key目錄,并將之間生成的私鑰庫(kù)文件privateKeys.keystore放到該文件夾下,后續(xù)用來(lái)生成證書(shū)

7、啟動(dòng)該項(xiàng)目,然后調(diào)用證書(shū)生成接口,得到證書(shū)文件license.lic

接口參數(shù)說(shuō)明:

  • subject: 證書(shū)主題,可以以授權(quán)的服務(wù)名來(lái)命名,不允許使用中文
  • storePass:訪(fǎng)問(wèn)密鑰庫(kù)密碼
  • licensePath:生成的證書(shū)存儲(chǔ)位置和證書(shū)文件名
  • expiryTime: 過(guò)期時(shí)間
  • description:描述
  • licenseCheckModel: 擴(kuò)展配置類(lèi),詳見(jiàn)代碼倉(cāng)庫(kù)

得到的證書(shū)文件license.lic、公鑰文件和密鑰庫(kù)密碼storePass我們需要提供給客戶(hù),當(dāng)然密碼可以提前配置在服務(wù)中,僅提供公鑰和證書(shū)文件給客戶(hù)即可。

2.4 測(cè)試模塊

1、新建一個(gè)spring web服務(wù),用于測(cè)試證書(shū)校驗(yàn)

2、引入license-client依賴(lài)

<dependency>
            <groupId>com.example</groupId>
            <artifactId>license-client</artifactId>
            <version>1.0.0</version>
</dependency>

3、配置文件聲明

server:
  port: 1888
license:
  # 證書(shū)subject
  subject: license-test-web
  # 公鑰別稱(chēng)
  publicAlias: publicCert
  # 訪(fǎng)問(wèn)公鑰庫(kù)的密碼
  storePass: wu@2024555
  # 證書(shū)路徑
  licensePath: /Users/wuhanxue/Downloads/key/license.lic
  # 公鑰路徑
  publicKeysStorePath: /Users/wuhanxue/Downloads/key/publicCerts.keystore

4、測(cè)試接口

@RestController
public class TestController {
    @GetMapping("test")
    public String test(){
        return "test";
    }
}

5、啟動(dòng)類(lèi)添加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、啟動(dòng)項(xiàng)目
顯示證書(shū)安裝成功

6、訪(fǎng)問(wèn)測(cè)試接口

成功返回信息,且有校驗(yàn)通過(guò)提示,說(shuō)明校驗(yàn)成功

7、我們繼續(xù)測(cè)試校驗(yàn)不通過(guò)的場(chǎng)景,重新生成license文件,并將有效期調(diào)整為1分鐘后,然后等待2分鐘再重啟項(xiàng)目,注意重新生成證書(shū)后要重新啟動(dòng)項(xiàng)目,讓項(xiàng)目重新加載證書(shū)

8、首先可以看到啟動(dòng)項(xiàng)目時(shí)已經(jīng)是一分鐘后了,安裝實(shí)際失敗了

9、調(diào)用會(huì)顯示證書(shū)過(guò)期,說(shuō)明正常

10、我們?cè)倌M證書(shū)安裝時(shí)是有效期內(nèi),調(diào)用時(shí)已經(jīng)過(guò)了有效期的場(chǎng)景,將有效期調(diào)整為5分鐘后,然后馬上重啟項(xiàng)目,在5分鐘后調(diào)用接口,接口顯示已過(guò)期,符合預(yù)期


2.5 完整代碼

完整代碼可見(jiàn)如下代碼倉(cāng)庫(kù):https://gitee.com/wuhanxue/wu_study/tree/master/demo/license_demo

3.總結(jié)

如上我們演示了trueLicense生成證書(shū)及證書(shū)校驗(yàn)的流程,如上演示中我并未針對(duì)設(shè)備、ip等進(jìn)行演示,但代碼倉(cāng)庫(kù)中有對(duì)應(yīng)代碼,大家感興趣的可以自行驗(yàn)證。

到此這篇關(guān)于Java利用trueLicense實(shí)現(xiàn)項(xiàng)目離線(xiàn)證書(shū)授權(quán)操作步驟的文章就介紹到這了,更多相關(guān)java trueLicense項(xiàng)目離線(xiàn)證書(shū)授權(quán)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java多線(xiàn)程中sleep和wait區(qū)別

    Java多線(xiàn)程中sleep和wait區(qū)別

    本文主要介紹了Java多線(xiàn)程中sleep和wait區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • java實(shí)現(xiàn)隊(duì)列數(shù)據(jù)結(jié)構(gòu)代碼詳解

    java實(shí)現(xiàn)隊(duì)列數(shù)據(jù)結(jié)構(gòu)代碼詳解

    這篇文章主要介紹了java實(shí)現(xiàn)隊(duì)列數(shù)據(jù)結(jié)構(gòu)代碼詳解,簡(jiǎn)單介紹了隊(duì)列結(jié)構(gòu)以應(yīng)用場(chǎng)景,涉及詳細(xì)實(shí)現(xiàn)代碼,還是比較不錯(cuò)的,這里分享給大家,需要的朋友可以參考下。
    2017-11-11
  • SpringBoot?多環(huán)境打包最佳實(shí)踐記錄

    SpringBoot?多環(huán)境打包最佳實(shí)踐記錄

    SpringBoot通過(guò)配置多環(huán)境文件和在打包時(shí)指定激活的環(huán)境,實(shí)現(xiàn)多環(huán)境打包與部署,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • 解決Java J2EE亂碼問(wèn)題的方法

    解決Java J2EE亂碼問(wèn)題的方法

    這篇文章主要為大家詳細(xì)介紹了解決Java J2EE亂碼問(wèn)題的方法的相關(guān)資料,需要的朋友可以參考下
    2016-04-04
  • 聊一聊Java中的Steam流

    聊一聊Java中的Steam流

    當(dāng)我們需要處理的數(shù)據(jù)量很大的時(shí)候,為了提高性能,就需要使用到并行處理,這樣的處理方式是很復(fù)雜的,流可以幫助開(kāi)發(fā)者節(jié)約寶貴的時(shí)間,讓以上的事情變得輕松,本文就和大家聊一聊Java中的Steam流,感興趣的同學(xué)跟著小編一起來(lái)看看吧
    2023-07-07
  • base64_encode和base64_decode的JAVA實(shí)現(xiàn)

    base64_encode和base64_decode的JAVA實(shí)現(xiàn)

    Base64 編碼其實(shí)是將3個(gè)8位字節(jié)轉(zhuǎn)換為4個(gè)6位這4個(gè)六位字節(jié) 其實(shí)仍然是8位,只不過(guò)高兩位被設(shè)置為0. 當(dāng)一個(gè)字節(jié)只有6位有效時(shí),它的取值空間為0 到 2的6次方減1 即63,也就是說(shuō)被轉(zhuǎn)換的Base64編碼的每一個(gè)編碼的取值空間為(0~63).需要的朋友可以參考下
    2016-04-04
  • Java高并發(fā)之CyclicBarrier的用法詳解

    Java高并發(fā)之CyclicBarrier的用法詳解

    CyclicBarrier 是 Java 中的一種同步工具,它可以讓多個(gè)線(xiàn)程在一個(gè)屏障點(diǎn)處等待,直到所有線(xiàn)程都到達(dá)該點(diǎn)后,才能繼續(xù)執(zhí)行。本文就來(lái)和大家聊聊它的用法,需要的可以參考一下
    2023-03-03
  • 使用SpringBoot2.x配置靜態(tài)文件緩存

    使用SpringBoot2.x配置靜態(tài)文件緩存

    這篇文章主要介紹了使用SpringBoot2.x配置靜態(tài)文件緩存的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 使用java生成json時(shí)產(chǎn)生棧溢出錯(cuò)誤問(wèn)題及解決方案

    使用java生成json時(shí)產(chǎn)生棧溢出錯(cuò)誤問(wèn)題及解決方案

    這篇文章主要介紹了使用java生成json時(shí)產(chǎn)生棧溢出錯(cuò)誤問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • java中統(tǒng)一返回前端格式及統(tǒng)一結(jié)果處理返回詳解

    java中統(tǒng)一返回前端格式及統(tǒng)一結(jié)果處理返回詳解

    這篇文章主要介紹了統(tǒng)一結(jié)果處理的重要性,以及如何在SpringBoot項(xiàng)目中定義和使用統(tǒng)一結(jié)果返回類(lèi),通過(guò)構(gòu)造器私有化和靜態(tài)方法ok、error,提供了成功和失敗的統(tǒng)一響應(yīng)格式,需要的朋友可以參考下
    2025-02-02

最新評(píng)論