一、简述

开发的软件产品在交付使用的时候,往往有一段时间的试用期,这期间我们不希望自己的代码被客户二次拷贝,这个时候 license 就派上用场了,license 的功能包括设定有效期、绑定 ip、绑定 mac 等。授权方直接生成一个 license 给使用方使用,如果需要延长试用期,也只需要重新生成一份 license 即可,无需手动修改源代码。

TrueLicense 是一个开源的证书管理引擎,详细介绍见 https://truelicense.java.net/

首先介绍下 license 授权机制的原理:

  1. 生成密钥对,包含私钥和公钥。
  2. 授权者保留私钥,使用私钥对授权信息诸如使用截止日期,mac 地址等内容生成 license 签名证书。
  3. 公钥给使用者,放在代码中使用,用于验证 license 签名证书是否符合使用条件。

二、生成密钥对

以下命令在 window cmd 命令窗口执行,注意当前执行目录,最后生成的密钥对即在该目录下:

1、首先要用 KeyTool 工具来生成私匙库:(-alias别名 -validity 3650 表示10年有效)

  1. keytool -genkey -alias privatekey -keysize 1024 -keystore privateKeys.store -validity 3650

2、然后把私匙库内的证书导出到一个文件当中

  1. keytool -export -alias privatekey -file certfile.cer -keystore privateKeys.store

3、然后再把这个证书文件导入到公匙库

  1. keytool -import -alias publiccert -file certfile.cer -keystore publicCerts.store

最后生成的文件 privateKeys.store(私钥)、publicCerts.store(公钥)拷贝出来备用。

三、准备工作

首先,我们需要引入 truelicense 的 jar 包,用于实现我们的证书管理。

  1. <dependency>
  2. <groupId>de.schlichtherle.truelicense</groupId>
  3. <artifactId>truelicense-core</artifactId>
  4. <version>1.33</version>
  5. </dependency>

然后,我们建立一个单例模式下的证书管理器。

  1. public class LicenseManagerHolder {
  2. private static volatile LicenseManager licenseManager = null;
  3. private LicenseManagerHolder() {
  4. }
  5. public static LicenseManager getLicenseManager(LicenseParam param) {
  6. if (licenseManager == null) {
  7. synchronized (LicenseManagerHolder.class) {
  8. if (licenseManager == null) {
  9. licenseManager = new LicenseManager(param);
  10. }
  11. }
  12. }
  13. return licenseManager;
  14. }
  15. }

四、利用私钥生成证书

利用私钥生成证书,我们需要两部分内容,一部分是私钥的配置信息(私钥的配置信息在生成私钥库的过程中获得),一部分是自定义的项目证书信息。如下展示:

  1. ########## 私钥的配置信息 ###########
  2. # 私钥的别名
  3. private.key.alias=privatekey
  4. # privateKeyPwd(该密码是生成密钥对的密码 — 需要妥善保管,不能让使用者知道)
  5. private.key.pwd=123456
  6. # keyStorePwd(该密码是访问密钥库的密码 — 使用 keytool 生成密钥对时设置,使用者知道该密码)
  7. key.store.pwd=123456
  8. # 项目的唯一识别码
  9. subject=demo
  10. # 密钥库的地址(放在 resource 目录下)
  11. priPath=/privateKeys.store
  12. ########## license content ###########
  13. # 发布日期
  14. issuedTime=2019-09-12
  15. # 有效开始日期
  16. notBefore=2019-09-12
  17. # 有效截止日期
  18. notAfter=2019-12-30
  19. # ip 地址
  20. ipAddress=192.168.31.25
  21. # mac 地址
  22. macAddress=5C-C5-D4-3E-CA-A6
  23. # 使用者类型,用户(user)、电脑(computer)、其他(else)
  24. consumerType=user
  25. # 证书允许使用的消费者数量
  26. consumerAmount=1
  27. # 证书说明
  28. info=power by xiamen yungu
  29. #生成证书的地址
  30. licPath=D:\\license.lic

接下来,就是如何生成证书的实操部分了

  1. @Slf4j
  2. public class CreateLicense {
  3. /**
  4. * X500Princal 是一个证书文件的固有格式,详见API
  5. */
  6. private final static X500Principal DEFAULT_HOLDERAND_ISSUER = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US");
  7. private String priAlias;
  8. private String privateKeyPwd;
  9. private String keyStorePwd;
  10. private String subject;
  11. private String priPath;
  12. private String issued;
  13. private String notBefore;
  14. private String notAfter;
  15. private String ipAddress;
  16. private String macAddress;
  17. private String consumerType;
  18. private int consumerAmount;
  19. private String info;
  20. private String licPath;
  21. /**
  22. * 构造器,参数初始化
  23. *
  24. * @param confPath 参数配置文件路径
  25. */
  26. public CreateLicense(String confPath) {
  27. // 获取参数
  28. Properties prop = new Properties();
  29. try (InputStream in = getClass().getResourceAsStream(confPath)) {
  30. prop.load(in);
  31. } catch (IOException e) {
  32. log.error("CreateLicense Properties load inputStream error.", e);
  33. }
  34. //common param
  35. priAlias = prop.getProperty("private.key.alias");
  36. privateKeyPwd = prop.getProperty("private.key.pwd");
  37. keyStorePwd = prop.getProperty("key.store.pwd");
  38. subject = prop.getProperty("subject");
  39. priPath = prop.getProperty("priPath");
  40. // license content
  41. issued = prop.getProperty("issuedTime");
  42. notBefore = prop.getProperty("notBefore");
  43. notAfter = prop.getProperty("notAfter");
  44. ipAddress = prop.getProperty("ipAddress");
  45. macAddress = prop.getProperty("macAddress");
  46. consumerType = prop.getProperty("consumerType");
  47. consumerAmount = Integer.valueOf(prop.getProperty("consumerAmount"));
  48. info = prop.getProperty("info");
  49. licPath = prop.getProperty("licPath");
  50. }
  51. /**
  52. * 生成证书,在证书发布者端执行
  53. *
  54. * @throws Exception
  55. */
  56. public void create() throws Exception {
  57. LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(initLicenseParams());
  58. licenseManager.store(buildLicenseContent(), new File(licPath));
  59. log.info("------ 证书发布成功 ------");
  60. }
  61. /**
  62. * 初始化证书的相关参数
  63. *
  64. * @return
  65. */
  66. private LicenseParam initLicenseParams() {
  67. Class<CreateLicense> clazz = CreateLicense.class;
  68. Preferences preferences = Preferences.userNodeForPackage(clazz);
  69. // 设置对证书内容加密的对称密码
  70. CipherParam cipherParam = new DefaultCipherParam(keyStorePwd);
  71. // 参数 1,2 从哪个Class.getResource()获得密钥库;
  72. // 参数 3 密钥库的别名;
  73. // 参数 4 密钥库存储密码;
  74. // 参数 5 密钥库密码
  75. KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(clazz, priPath, priAlias, keyStorePwd, privateKeyPwd);
  76. // 返回生成证书时需要的参数
  77. return new DefaultLicenseParam(subject, preferences, privateStoreParam, cipherParam);
  78. }
  79. /**
  80. * 通过外部配置文件构建证书的的相关信息
  81. *
  82. * @return
  83. * @throws ParseException
  84. */
  85. public LicenseContent buildLicenseContent() throws ParseException {
  86. LicenseContent content = new LicenseContent();
  87. SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd");
  88. content.setConsumerAmount(consumerAmount);
  89. content.setConsumerType(consumerType);
  90. content.setHolder(DEFAULT_HOLDERAND_ISSUER);
  91. content.setIssuer(DEFAULT_HOLDERAND_ISSUER);
  92. content.setIssued(formate.parse(issued));
  93. content.setNotBefore(formate.parse(notBefore));
  94. content.setNotAfter(formate.parse(notAfter));
  95. content.setInfo(info);
  96. // 扩展字段
  97. Map<String, String> map = new HashMap<>(4);
  98. map.put("ip", ipAddress);
  99. map.put("mac", macAddress);
  100. content.setExtra(map);
  101. return content;
  102. }
  103. }

最后,来尝试生成一份证书吧!

  1. public static void main(String[] args) throws Exception {
  2. CreateLicense clicense = new CreateLicense("/licenseCreateParam.properties");
  3. clicense.create();
  4. }

四、利用公钥验证证书

利用公钥生成证书,我们需要有公钥库、license 证书等信息。

  1. ########## 公钥的配置信息 ###########
  2. # 公钥别名
  3. public.alias=publiccert
  4. # 该密码是访问密钥库的密码 — 使用 keytool 生成密钥对时设置,使用者知道该密码
  5. key.store.pwd=123456
  6. # 项目的唯一识别码 — 和私钥的 subject 保持一致
  7. subject = yungu
  8. # 证书路径(我这边配置在了 linux 根路径下,即 /license.lic )
  9. license.dir=/license.lic
  10. # 公共库路径(放在 resource 目录下)
  11. public.store.path=/publicCerts.store

接下来就是怎么用公钥验证 license 证书,怎样验证 ip、mac 地址等信息的过程了~

  1. @Slf4j
  2. public class VerifyLicense {
  3. private String pubAlias;
  4. private String keyStorePwd;
  5. private String subject;
  6. private String licDir;
  7. private String pubPath;
  8. public VerifyLicense() {
  9. // 取默认配置
  10. setConf("/licenseVerifyParam.properties");
  11. }
  12. public VerifyLicense(String confPath) {
  13. setConf(confPath);
  14. }
  15. /**
  16. * 通过外部配置文件获取配置信息
  17. *
  18. * @param confPath 配置文件路径
  19. */
  20. private void setConf(String confPath) {
  21. // 获取参数
  22. Properties prop = new Properties();
  23. InputStream in = getClass().getResourceAsStream(confPath);
  24. try {
  25. prop.load(in);
  26. } catch (IOException e) {
  27. log.error("VerifyLicense Properties load inputStream error.", e);
  28. }
  29. this.subject = prop.getProperty("subject");
  30. this.pubAlias = prop.getProperty("public.alias");
  31. this.keyStorePwd = prop.getProperty("key.store.pwd");
  32. this.licDir = prop.getProperty("license.dir");
  33. this.pubPath = prop.getProperty("public.store.path");
  34. }
  35. /**
  36. * 安装证书证书
  37. */
  38. public void install() {
  39. try {
  40. LicenseManager licenseManager = getLicenseManager();
  41. licenseManager.install(new File(licDir));
  42. log.info("安装证书成功!");
  43. } catch (Exception e) {
  44. log.error("安装证书失败!", e);
  45. Runtime.getRuntime().halt(1);
  46. }
  47. }
  48. private LicenseManager getLicenseManager() {
  49. return LicenseManagerHolder.getLicenseManager(initLicenseParams());
  50. }
  51. /**
  52. * 初始化证书的相关参数
  53. */
  54. private LicenseParam initLicenseParams() {
  55. Class<VerifyLicense> clazz = VerifyLicense.class;
  56. Preferences pre = Preferences.userNodeForPackage(clazz);
  57. CipherParam cipherParam = new DefaultCipherParam(keyStorePwd);
  58. KeyStoreParam pubStoreParam = new DefaultKeyStoreParam(clazz, pubPath, pubAlias, keyStorePwd, null);
  59. return new DefaultLicenseParam(subject, pre, pubStoreParam, cipherParam);
  60. }
  61. /**
  62. * 验证证书的合法性
  63. */
  64. public boolean vertify() {
  65. try {
  66. LicenseManager licenseManager = getLicenseManager();
  67. LicenseContent verify = licenseManager.verify();
  68. log.info("验证证书成功!");
  69. Map<String, String> extra = (Map) verify.getExtra();
  70. String ip = extra.get("ip");
  71. InetAddress inetAddress = InetAddress.getLocalHost();
  72. String localIp = inetAddress.toString().split("/")[1];
  73. if (!Objects.equals(ip, localIp)) {
  74. log.error("IP 地址验证不通过");
  75. return false;
  76. }
  77. String mac = extra.get("mac");
  78. String localMac = getLocalMac(inetAddress);
  79. if (!Objects.equals(mac, localMac)) {
  80. log.error("MAC 地址验证不通过");
  81. return false;
  82. }
  83. log.info("IP、MAC地址验证通过");
  84. return true;
  85. } catch (LicenseContentException ex) {
  86. log.error("证书已经过期!", ex);
  87. return false;
  88. } catch (Exception e) {
  89. log.error("验证证书失败!", e);
  90. return false;
  91. }
  92. }
  93. /**
  94. * 得到本机 mac 地址
  95. *
  96. * @param inetAddress
  97. * @throws SocketException
  98. */
  99. private String getLocalMac(InetAddress inetAddress) throws SocketException {
  100. //获取网卡,获取地址
  101. byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
  102. StringBuffer sb = new StringBuffer();
  103. for (int i = 0; i < mac.length; i++) {
  104. if (i != 0) {
  105. sb.append("-");
  106. }
  107. //字节转换为整数
  108. int temp = mac[i] & 0xff;
  109. String str = Integer.toHexString(temp);
  110. if (str.length() == 1) {
  111. sb.append("0" + str);
  112. } else {
  113. sb.append(str);
  114. }
  115. }
  116. return sb.toString().toUpperCase();
  117. }
  118. }

有了公钥的验证过程了,等下!事情还没结束呢!我们需要在项目启动的时候,安装 licnese 证书,然后验证ip、mac 等信息。如果校验不通过,就阻止项目启动!

  1. @Component
  2. public class LicenseCheck {
  3. @PostConstruct
  4. public void init() {
  5. VerifyLicense vlicense = new VerifyLicense();
  6. vlicense.install();
  7. if (!vlicense.vertify()) {
  8. Runtime.getRuntime().halt(1);
  9. }
  10. }
  11. }

基于 TrueLicense 的项目证书验证的更多相关文章

  1. 基于TrueLicense实现产品License验证功能

    受朋友所托,需要给产品加上License验证功能,进行试用期授权,在试用期过后,产品不再可用. 通过研究调查,可以利用Truelicense开源框架实现,下面分享一下如何利用Truelicense实现 ...

  2. 重温WCF之WCF传输安全(十三)(4)基于SSL的WCF对客户端采用证书验证(转)

    转载地址:http://www.cnblogs.com/lxblog/archive/2012/09/20/2695397.html 前一篇我们演示了基于SSL的WCF 对客户端进行用户名和密码方式的 ...

  3. [转]基于Starling移动项目开发准备工作

    最近自己趁业余时间做的flash小游戏已经开发得差不多了,准备再完善下ui及数值后,投放到国外flash游戏站.期间也萌生想法,想把游戏拓展到手机平台.这两天尝试了下,除去要接入ane接口的工作,小游 ...

  4. python基于LeanCloud的短信验证

    python基于LeanCloud的短信验证 1. 获取LeanCloud的Id.Key 2. 安装Flask框架和Requests库 pip install flask pip install re ...

  5. ASP.NET MVC基于标注特性的Model验证:将ValidationAttribute应用到参数上

    原文:ASP.NET MVC基于标注特性的Model验证:将ValidationAttribute应用到参数上 ASP.NET MVC默认采用基于标准特性的Model验证机制,但是只有应用在Model ...

  6. ASP.NET MVC基于标注特性的Model验证:一个Model,多种验证规则

    原文:ASP.NET MVC基于标注特性的Model验证:一个Model,多种验证规则 对于Model验证,理想的设计应该是场景驱动的,而不是Model(类型)驱动的,也就是对于同一个Model对象, ...

  7. 【腾讯Bugly干货分享】iOS 中 HTTPS 证书验证浅析

    本文来自于腾讯Bugly公众号(weixinBugly),未经作者同意,请勿转载,原文地址:https://mp.weixin.qq.com/s/-fLLTtip509K6pNOTkflPQ 导语 本 ...

  8. 解决https证书验证不通过的问题

    1.报错信息 java.security.cert.CertificateException: No name matching api.weibo.com found; nested excepti ...

  9. 在Tomcat中采用基于表单的安全验证

    .概述   (1)基于表单的验证 基于From的安全认证可以通过TomcatServer对Form表单中所提供的数据进行验证,基于表单的验证使系统开发者可以自定义用户的登陆页面和报错页面.这种验证方法 ...

随机推荐

  1. 性能测试专题:Locust工具实战之“蝗虫”降世

    阅读全文需5分钟. 1. 前言 在上一篇文章中,我们已经为大家介绍了什么是Locust,具体可参照:性能专题:Locust工具实战之开篇哲学三问,简单来说,Locust 是基于 Python 语言下的 ...

  2. 正确理解 PHP 的重载

    PHP 的重载跟 Java 的重载不同,不可混为一谈.Java 允许类中存在多个同名函数,每个函数的参数不相同,而 PHP 中只允许存在一个同名函数.例如,Java 的构造函数可以有多个,PHP 的构 ...

  3. Centos7 搭建LAMP环境(编译安装)

    1.查看系统版本 [niemx@localhost ~]$ cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core) 2.安装软件准备 ...

  4. Hadoop简述

    Haddop是什么? Hadoop是一个由Apache基金会所开发的分布式系统基础架构 主要解决,海量数据的存储和海量数据的分析计算问题. Hadoop三大发行版本 Apache版本最原始(最基础)的 ...

  5. python+selenium +unittest生成HTML测试报告

    python+selenium+HTMLTestRunner+unittest生成HTML测试报告 首先要准备HTMLTestRunner文件,官网的HTMLTestRunner是python2语法写 ...

  6. css三大特效之层叠性

    css三大特效之层叠性

  7. DNS资源记录的七类

    在Microsoft产品系列中,ADDS是一个很出色的设计平台,说到AD,那么我们就不得不提起他的合作伙伴--DNS,相信大家都知道,DNS在AD中的重要地位,就如男人和女人一样,要想有所作为,他们2 ...

  8. 对 /langversion 无效;必须是 ISO-1、ISO-2、3、4、5 或 Default

    反编译或者.net用更高版本打开时会出现这个问题,解决办法如下: 1.网页版程序,将解决方案中的Web.config中的 /langversion 的值改为指定的值,既可以解决,我这里采用的是默认值, ...

  9. 聚类-K-Means

    1.什么是K-Means? K均值算法聚类 关键词:K个种子,均值聚类的概念:一种无监督的学习,事先不知道类别,自动将相似的对象归到同一个簇中 K-Means算法是一种聚类分析(cluster ana ...

  10. php 第1讲 html介绍 html运行原理①

    1. html (hypertext mark-up language )是 超文本编辑语言,主要的用处是做网页,可以在网页上显示文字.图形.动画.视频... “标记“有时候也称之为“元素” 动态网页 ...