使用trueLicense实现Java工程license机制(包括license的生成和验证)
由于公司要求,需要对交付的软件产品做授权,比如试用版1个月的使用时间,服务器数量限制等等,这个时候license就派上用场了。不同于在代码中直接加上时间约束,需要重新授权的时候使用license可以避免修改源码,改动部署,授权方直接生成一个新的license发送给使用方替换掉原来的license文件即可。下面将讲述使用truelicense来实现license的生成和使用。Truelicense是一个开源的证书管理引擎,详细介绍见 https:// truelicense.java.net/ 。此处也借鉴了网上的教程,但没找到哪个是原创,就在此感谢大佬一波吧~~
一、license授权机制的原理
1、 生成密钥对,方法有很多。
2、 授权者保留私钥,使用私钥对包含授权信息(如使用截止日期、机器码、MAC地址等)的license进行数字签名。
3、 公钥给使用者(放在验证的代码中使用),用于验证license是否符合使用条件。
二、制作license的具体步骤
第一步:使用keytool生成密钥对
以下命令在dos命令行执行,注意当前执行目录,最后生成的密钥对即在该目录下:
1、首先要用KeyTool工具来生成私匙库
keytool -genkey -alias privatekey -keysize 1024 -keystore privateKeys.store -validity 3650
参数说明:
- -alias:别名为privatekey
- –validity 3650:10年有效
- -keysize 1024:大小,默认为2048,使用默认的太大,使用时会有问题,会报以下错误:
keytool error: java.security.InvalidKeyException: The security strength of SHA-1 digest algorithm is not sufficient for this key size
截图说明:
此处输入的为密钥库口令:shelby123,之后按照提示信息进行填写即可。
确认上一步骤无问题后,需要输入“privatekey(私钥)”的密钥口令,十分重要,不可让客户知道,此处为了方便,我直接按回车,与密钥库口令相同。
生成的私钥如下所示:
2、然后导出证书
keytool -export -alias privatekey -file certfile.cer -keystore privateKeys.store
截图说明:
生成的证书如下所示:
3、然后再把这个证书文件导入到公匙库1、 首先LicenseManagerHolder.java类:
keytool -import -alias publiccert -file certfile.cer -keystore publicCerts.store
最后生成文件privateKeys.store、publicCerts.store拷贝出来备用。
截图说明:
生成的公钥如下所示:
第二步:生成证书(该部分代码由授权者独立保管执行)
此步骤需要使用trueLicense进行生成,这里可以新建一个java项目来进行操作,此处我只把代码贴出来,新建项目的操作不再演示。
1、Maven依赖
<dependency>
<groupId>de.schlichtherle.truelicense</groupId>
<artifactId>truelicense-core</artifactId>
<version>1.33</version>
<scope>provided</scope>
</dependency>
2、 LicenseManagerHolder.java
/**
* LicenseManager单例模式下的证书管理器
public class
LicenseManagerHolder {
private static LicenseManager licenseManager;
public static synchronized LicenseManager getLicenseManager(LicenseParam licenseParams) {
if (licenseManager == null) {
licenseManager = new LicenseManager(licenseParams);
return licenseManager;
}
3、主要生成license的代码CreateLicense.java
/**
* CreateLicense 生成证书
public class CreateLicense {
//common param
private static String PRIVATEALIAS = "";
private static String KEYPWD = "";
private static String STOREPWD = "";
private static String SUBJECT = "";
private static String licPath = "";
private static String priPath = "";
//license content
private static String issuedTime = "";
private static String notBefore = "";
private static String notAfter = "";
private static String consumerType = "";
private static int consumerAmount = 0;
private static String info = "";
// 为了方便直接用的API里的例子
// X500Princal是一个证书文件的固有格式,详见API
private final static X500Principal DEFAULTHOLDERANDISSUER =
new X500Principal("CN=shelby, OU=org, O=org, L=china, ST=china, C=china");
public void setParam(String propertiesPath) {
// 获取参数
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream(propertiesPath);
try {
prop.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
PRIVATEALIAS = prop.getProperty("PRIVATEALIAS");
STOREPWD = prop.getProperty("STOREPWD");
SUBJECT = prop.getProperty("SUBJECT");
KEYPWD = prop.getProperty("KEYPWD");
licPath = prop.getProperty("licPath");
priPath = prop.getProperty("priPath");
//license content
issuedTime = prop.getProperty("issuedTime");
notBefore = prop.getProperty("notBefore");
notAfter = prop.getProperty("notAfter");
consumerType = prop.getProperty("consumerType");
consumerAmount = Integer.valueOf(prop.getProperty("consumerAmount"));
info = prop.getProperty("info");
// 返回生成证书时需要的参数
private static LicenseParam initLicenseParams() {
Preferences preference = Preferences.userNodeForPackage(CreateLicense.class);
// 设置对证书内容加密的对称密码
CipherParam cipherParam = new DefaultCipherParam(STOREPWD);
// 参数1,2从哪个Class.getResource()获得密钥库;参数3密钥库的别名;参数4密钥库存储密码;参数5密钥库密码
KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(
CreateLicense.class, priPath, PRIVATEALIAS, STOREPWD, KEYPWD);
// 返回生成证书时需要的参数
LicenseParam licenseParams = new DefaultLicenseParam(SUBJECT,
preference, privateStoreParam, cipherParam);
return licenseParams;
// 通过外部配置文件构建证书的的相关信息
public final static LicenseContent createLicenseContent() {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
LicenseContent content = new LicenseContent();
content.setSubject(SUBJECT);
content.setHolder(DEFAULTHOLDERANDISSUER);
content.setIssuer(DEFAULTHOLDERANDISSUER);
try {
content.setIssued(format.parse(issuedTime));
content.setNotBefore(format.parse(notBefore));
content.setNotAfter(format.parse(notAfter));
// 扩展
content.setExtra(new Object());
} catch (ParseException e) {
e.printStackTrace();
content.setConsumerType(consumerType);
content.setConsumerAmount(consumerAmount);
content.setInfo(info);
return content;
public boolean create() {
try {
/************** 证书发布者端执行 ******************/
LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(initLicenseParams());
licenseManager.store((createLicenseContent()), new File(licPath));
} catch (Exception e) {
e.printStackTrace();
System.out.println("客户端证书生成失败!");
return false;
System.out.println("服务器端生成证书成功!");
return true;
}
4、测试程序licenseCreateTest.java
public class licenseCreateTest {
public static void main(String[] args) {
CreateLicense cLicense = new CreateLicense();
//获取参数(param.properties为参数配置文件)
cLicense.setParam("./param.properties");
//生成证书
cLicense.create();
}
5、生成时使用到的param.properties
##########common parameters###########
#alias:私钥的别名
PRIVATEALIAS=privatekey
#key(important!):该密码生成密钥对的密码,需要妥善保管,不能让使用者知道
KEYPWD=shelby23
#STOREPWD:该密码是在使用keytool生成密钥对时设置的密钥库的访问密码
STOREPWD=shelby23
#SUBJECT:项目的唯一识别码
SUBJECT=shelby
#licPath:生成证书的地址
licPath=license.lic
#priPath:密钥库的地址
priPath=E:\\LicenseTest\\1529550189837\\LicenseCreate\\src\\cn\\melina\\license\\privateKeys.store
##########license content###########
#issuedTime:发布日期
issuedTime=2018-06-21
#notBeforeTime:有效开始日期
notBefore=2018-06-21
#notAfterTime:有效截止日期
notAfter=2028-06-21
#consumerType
consumerType=user
#ConsumerAmount
consumerAmount=1
#info
info=this is a license
根据properties文件可以看出,这里只简单设置了使用时间的限制,当然可以自定义添加更多限制。该文件中表示授权者拥有私钥,并且知道生成密钥对的密码。并且设置license的内容。
第三步:验证证书(使用证书)(该部分代码结合需要授权的程序使用)
1、 首先LicenseManagerHolder.java类,同上。
2、 然后是主要验证license的代码VerifyLicense.java
public class VerifyLicense {
//common param
private static String PUBLICALIAS = "";
private static String STOREPWD = "";
private static String SUBJECT = "";
private static String licPath = "";
private static String pubPath = "";
// 返回验证证书需要的参数
private static LicenseParam initLicenseParams() {
Preferences preference = Preferences
.userNodeForPackage(VerifyLicense.class);
CipherParam cipherParam = new DefaultCipherParam(STOREPWD);
KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(
VerifyLicense.class, pubPath, PUBLICALIAS, STOREPWD, null);
LicenseParam licenseParams = new DefaultLicenseParam(SUBJECT,
preference, privateStoreParam, cipherParam);
return licenseParams;
public boolean verify() {
LicenseProperties licenseProperties = SpringContextHolder.getBean(LicenseProperties.class);
PUBLICALIAS = licenseProperties.getPublicAlias();
STOREPWD = licenseProperties.getStorePwd();
SUBJECT = licenseProperties.getSubject();
licPath = licenseProperties.getLicPath();
pubPath = licenseProperties.getPubPath();
/************** 证书使用者端执行 ******************/
LicenseManager licenseManager = LicenseManagerHolder
.getLicenseManager(initLicenseParams());
// 安装证书
try {
licenseManager.install(new File(licPath));
System.out.println("客户端安装证书成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("客户端证书安装失败!");
return false;
// 验证证书
try {
licenseManager.verify();
System.out.println("客户端验证证书成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("客户端证书验证失效!");
return false;
return true;
}
在verify()方法中:
LicensePropertieslicenseProperties = SpringContextHolder.getBean(LicenseProperties.class);
此方法是SpringBoot引进Properties配置文件的方式,如果你并没有使用SpringBoot,可使用一下形式获取参数:
// propertiesPath为配置文件路径
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream(propertiesPath);
3、 测试程序licenseVerifyTest.java
// 非SpringBoot项目可直接main方法测试,SpringBoot项目需要使用junit进行测试
public class licenseVerifyTest {
public static void main(String[] args){
VerifyLicense vLicense = new VerifyLicense();