2022-11-30
后端
00
请注意,本文编写于 647 天前,最后修改于 110 天前,其中某些信息可能已经过时。

目录

一、简介
1、代码封装
2.1 获取服务器信息
2.1.1 AbstractServerInfos抽象类
2.1.2 LinuxServerInfos实现类
2.1.3 WindowsServerInfos实现类
2.2 LicenseExtraModel定义校检自定义实体类
2.3 LicenseCreatorParam
2.4 CustomLicenseManager校检类添加自定义校检
2.5 LicenseCreator
二、注册号验证

一、简介

根据上篇整合TrueLicense,完成基础证书有效期,本篇记录加入获取客户服务器的基本信息,如:IP、Mac地址、CPU序列号、主板序列号,注册号等限制 加入自定义校检原文

1、代码封装

2.1 获取服务器信息

2.1.1 AbstractServerInfos抽象类

获取客户服务器的基本信息,如:IP、Mac地址、CPU序列号、主板序列号等

客户端、服务端都需要放置服务器信息3个类

import com.zr.ams.config.license.LicenseExtraModel; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; /** * 用于获取客户服务器的基本信息,如:IP、Mac地址、CPU序列号、主板序列号等 * @author Chen Shaohua * @date 2022/11/16 14:52 */ public abstract class AbstractServerInfos { private static Logger logger = LogManager.getLogger(AbstractServerInfos.class); /** * 组装需要额外校验的License参数 * @return */ public LicenseExtraModel getServerInfos() { LicenseExtraModel result = new LicenseExtraModel(); try { result.setIpAddress(this.getIpAddress()); result.setMacAddress(this.getMacAddress()); result.setCpuSerial(this.getCPUSerial()); result.setMainBoardSerial(this.getMainBoardSerial()); } catch (Exception e) { logger.error("获取服务器硬件信息失败", e); } return result; } /** * 获取IP地址 * @return * @throws Exception */ protected abstract List<String> getIpAddress() throws Exception; /** * 获取Mac地址 * @return * @throws Exception */ protected abstract List<String> getMacAddress() throws Exception; /** * 获取CPU序列号 * @return * @throws Exception */ protected abstract String getCPUSerial() throws Exception; /** * 获取主板序列号 * @return * @throws Exception */ protected abstract String getMainBoardSerial() throws Exception; /** * 获取当前服务器所有符合条件的InetAddress * @return * @throws Exception */ protected List<InetAddress> getLocalAllInetAddress() throws Exception { List<InetAddress> result = new ArrayList<>(4); // 遍历所有的网络接口 for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) { NetworkInterface iface = (NetworkInterface) networkInterfaces.nextElement(); // 在所有的接口下再遍历IP for (Enumeration inetAddresses = iface.getInetAddresses(); inetAddresses.hasMoreElements(); ) { InetAddress inetAddr = (InetAddress) inetAddresses.nextElement(); //排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress类型的IP地址 if (!inetAddr.isLoopbackAddress() /*&& !inetAddr.isSiteLocalAddress()*/ && !inetAddr.isLinkLocalAddress() && !inetAddr.isMulticastAddress()) { result.add(inetAddr); } } } return result; } /** * 获取某个网络接口的Mac地址 * @param inetAddr * @return */ protected String getMacByInetAddress(InetAddress inetAddr) { try { byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress(); StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < mac.length; i++) { if (i != 0) { stringBuffer.append("-"); } //将十六进制byte转化为字符串 String temp = Integer.toHexString(mac[i] & 0xff); if (temp.length() == 1) { stringBuffer.append("0" + temp); } else { stringBuffer.append(temp); } } return stringBuffer.toString().toUpperCase(); } catch (SocketException e) { e.printStackTrace(); } return null; } }

2.1.2 LinuxServerInfos实现类

import com.baomidou.mybatisplus.core.toolkit.StringUtils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetAddress; import java.util.List; import java.util.stream.Collectors; /** * 用于获取客户Linux服务器的基本信息 * * @author Chen Shaohua * @date 2022/11/16 14:54 */ public class LinuxServerInfos extends AbstractServerInfos { @Override protected List<String> getIpAddress() throws Exception { List<String> result = null; //获取所有网络接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if (inetAddresses != null && inetAddresses.size() > 0) { result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList()); } return result; } @Override protected List<String> getMacAddress() throws Exception { List<String> result = null; //1. 获取所有网络接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if (inetAddresses != null && inetAddresses.size() > 0) { //2. 获取所有网络接口的Mac地址 result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList()); } return result; } @Override protected String getCPUSerial() throws Exception { //序列号 String serialNumber = ""; //使用dmidecode命令获取CPU序列号 String[] shell = {"/bin/bash", "-c", "dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"}; Process process = Runtime.getRuntime().exec(shell); process.getOutputStream().close(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine().trim(); if (StringUtils.isNotBlank(line)) { serialNumber = line; } reader.close(); return serialNumber; } @Override protected String getMainBoardSerial() throws Exception { //序列号 String serialNumber = ""; //使用dmidecode命令获取主板序列号 String[] shell = {"/bin/bash", "-c", "dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"}; Process process = Runtime.getRuntime().exec(shell); process.getOutputStream().close(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine().trim(); if (StringUtils.isNotBlank(line)) { serialNumber = line; } reader.close(); return serialNumber; } }

2.1.3 WindowsServerInfos实现类

import java.net.InetAddress; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; /** * 用于获取客户Windows服务器的基本信息 * * @author Chen Shaohua * @date 2022/11/16 14:54 */ public class WindowsServerInfos extends AbstractServerInfos { @Override protected List<String> getIpAddress() throws Exception { List<String> result = null; //获取所有网络接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if (inetAddresses != null && inetAddresses.size() > 0) { result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList()); } return result; } @Override protected List<String> getMacAddress() throws Exception { List<String> result = null; //1. 获取所有网络接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if (inetAddresses != null && inetAddresses.size() > 0) { //2. 获取所有网络接口的Mac地址 result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList()); } return result; } @Override protected String getCPUSerial() throws Exception { //序列号 String serialNumber = ""; //使用WMIC获取CPU序列号 Process process = Runtime.getRuntime().exec("wmic cpu get processorid"); process.getOutputStream().close(); Scanner scanner = new Scanner(process.getInputStream()); if (scanner.hasNext()) { scanner.next(); } if (scanner.hasNext()) { serialNumber = scanner.next().trim(); } scanner.close(); return serialNumber; } @Override protected String getMainBoardSerial() throws Exception { //序列号 String serialNumber = ""; //使用WMIC获取主板序列号 Process process = Runtime.getRuntime().exec("wmic baseboard get serialnumber"); process.getOutputStream().close(); Scanner scanner = new Scanner(process.getInputStream()); if (scanner.hasNext()) { scanner.next(); } if (scanner.hasNext()) { serialNumber = scanner.next().trim(); } scanner.close(); return serialNumber; } }

2.2 LicenseExtraModel定义校检自定义实体类

IP地址、MAC地址、CPU序列号、主板序列号等信息,注册号是单独加的校检规则,主要用于和前段来解析,防止java项目被破解。

package com.zr.ams.config.license; import lombok.Data; import java.io.Serializable; import java.util.List; /** * 自定义需要校验的License参数,可以增加一些额外需要校验的参数,比如项目信息,ip地址信息等等 * * @author Chen Shaohua * @date 2022/11/15 15:29 */ @Data public class LicenseExtraModel implements Serializable { private static final long serialVersionUID = -2314678441082223148L; /** * 可被允许的IP地址 */ private List<String> ipAddress; /** * 可被允许的MAC地址 */ private List<String> macAddress; /** * 可被允许的CPU序列号 */ private String cpuSerial; /** * 可被允许的主板序列号 */ private String mainBoardSerial; /** * 注册码 */ private String registrationCode; }

2.3 LicenseCreatorParam

生成证书需要的参数实体类添加LicenseExtraModel

/** * 额外的服务器硬件校验信息 */ private LicenseExtraModel licenseExtraModel;

2.4 CustomLicenseManager校检类添加自定义校检

校检方法在

import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.zr.ams.config.licenseClicet.serviceAbstract.AbstractServerInfos; import com.zr.ams.config.licenseClicet.serviceAbstract.LinuxServerInfos; import com.zr.ams.config.licenseClicet.serviceAbstract.WindowsServerInfos; import de.schlichtherle.license.*; import de.schlichtherle.xml.GenericCertificate; import de.schlichtherle.xml.XMLConstants; 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; /** * 自定义LicenseManager,用于增加额外的信息校验(除了LicenseManager的校验,我们还可以在这个类里面添加额外的校验信息) * * @author Chen Shaohua * @date 2022/11/15 15:31 */ public class CustomLicenseManager extends LicenseManager { private static Logger logger = LogManager.getLogger(CustomLicenseManager.class); public CustomLicenseManager(LicenseParam param) { super(param); } /** * 复写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); } /** * 复写install方法,其中validate方法调用本类中的validate方法,校验IP地址、Mac地址等其他信息 */ @Override protected synchronized LicenseContent install(final byte[] key, final LicenseNotary notary) throws Exception { final GenericCertificate certificate = getPrivacyGuard().key2cert(key); notary.verify(certificate); final LicenseContent content = (LicenseContent) this.load(certificate.getEncoded()); this.validate(content); setLicenseKey(key); setCertificate(certificate); return content; } /** * 复写verify方法,调用本类中的validate方法,校验IP地址、Mac地址等其他信息 */ @Override protected synchronized LicenseContent verify(final LicenseNotary notary) throws Exception { // Load license key from preferences, final byte[] key = getLicenseKey(); if (null == key) { throw new NoLicenseInstalledException(getLicenseParam().getSubject()); } GenericCertificate certificate = getPrivacyGuard().key2cert(key); notary.verify(certificate); final LicenseContent content = (LicenseContent) this.load(certificate.getEncoded()); this.validate(content); setCertificate(certificate); return content; } /** * 校验生成证书的参数信息 */ 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("证书失效时间不能早于当前时间"); } if (null != notBefore && null != notAfter && notAfter.before(notBefore)) { throw new LicenseContentException("证书生效时间不能晚于证书失效时间"); } final String consumerType = content.getConsumerType(); if (null == consumerType) { throw new LicenseContentException("用户类型不能为空"); } } /** * 复写validate方法,用于增加我们额外的校验信息 */ @Override protected synchronized void validate(final LicenseContent content) throws LicenseContentException { //1. 首先调用父类的validate方法 super.validate(content); //2. 然后校验自定义的License参数,去校验我们的license信息 LicenseExtraModel expectedCheckModel = (LicenseExtraModel)content.getExtra(); // 做我们自定义的校验 //当前服务器真实的参数信息 if (expectedCheckModel != null) { LicenseExtraModel serverCheckModel = getServerInfos(); if (expectedCheckModel != null && serverCheckModel != null) { //校验IP地址 if (!checkIpAddress(expectedCheckModel.getIpAddress(), serverCheckModel.getIpAddress())) { throw new LicenseContentException("当前服务器的IP没在授权范围内"); } //校验Mac地址 if (!checkIpAddress(expectedCheckModel.getMacAddress(), serverCheckModel.getMacAddress())) { throw new LicenseContentException("当前服务器的Mac地址没在授权范围内"); } //校验主板序列号 if (!checkSerial(expectedCheckModel.getMainBoardSerial(), serverCheckModel.getMainBoardSerial())) { throw new LicenseContentException("当前服务器的主板序列号没在授权范围内"); } //校验CPU序列号 if (!checkSerial(expectedCheckModel.getCpuSerial(), serverCheckModel.getCpuSerial())) { throw new LicenseContentException("当前服务器的CPU序列号没在授权范围内"); } } else { throw new LicenseContentException("不能获取服务器硬件信息"); } } else { throw new LicenseContentException("不能获取服务器硬件信息"); } } /** * 重写XMLDecoder解析XML */ private Object load(String encoded) { BufferedInputStream inputStream = null; XMLDecoder decoder = null; try { inputStream = new BufferedInputStream(new ByteArrayInputStream(encoded.getBytes(XMLConstants.XML_CHARSET))); decoder = new XMLDecoder(new BufferedInputStream(inputStream, XMLConstants.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; } /** * 获取当前服务器需要额外校验的License参数 * * @return demo.LicenseCheckModel * @author zifangsky * @date 2018/4/23 14:33 * @since 1.0.0 */ private LicenseExtraModel getServerInfos() { //操作系统类型 String osName = System.getProperty("os.name").toLowerCase(); AbstractServerInfos abstractServerInfos = null; //根据不同操作系统类型选择不同的数据获取方法 if (osName.startsWith("windows")) { abstractServerInfos = new WindowsServerInfos(); } else if (osName.startsWith("linux")) { abstractServerInfos = new LinuxServerInfos(); } else {//其他服务器类型 abstractServerInfos = new LinuxServerInfos(); } return abstractServerInfos.getServerInfos(); } /** * 校验当前服务器的IP/Mac地址是否在可被允许的IP范围内<br/> * <p> * 如果存在IP在可被允许的IP/Mac地址范围内,则返回true * * @return boolean * @author zifangsky * @date 2018/4/24 11:44 * @since 1.0.0 */ 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; } } /** * 校验当前服务器硬件(主板、CPU等)序列号是否在可允许范围内 * * @return boolean * @author zifangsky * @date 2018/4/24 14:38 * @since 1.0.0 */ 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; } } }

2.5 LicenseCreator

生成证书时添加自定义校检类

1、根据客户服务器生成相应的服务器信息

2、注册号根据自己定义的规则生成,前段相应解析

注:生成证书也不用在客户服务器执行,要么通过手动查看客户的服务信息,或者只把获取服务器这个代码写一个脚本执行拿到服务器信息,最后再把私钥拿到放到自己本地也可以生成证书

AbstractServerInfos abstractServerInfos = new WindowsServerInfos(); LicenseExtraModel licenseExtraModel = abstractServerInfos.getServerInfos(); //注册码生成 licenseExtraModel.setRegistrationCode(createRegistrationCode(param.getSubject(), currentDate, param.getExpiryTime())); param.setLicenseExtraModel(licenseExtraModel);

二、注册号验证

controller层通过注册的licenseVerify,licenseVerify.getLicenseExtraModel()可以拿到证书中的注册号,传给前台解析

import com.zr.ams.config.license.LicenseVerify; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author Chen Shaohua * @date 2022/11/15 16:21 */ @RestController public class LicenseTest { private LicenseVerify licenseVerify; @Autowired public void setLicenseVerify(LicenseVerify licenseVerify) { this.licenseVerify = licenseVerify; } @RequestMapping(value = "/licenseVerify") public void licenseVerify() { System.out.println("licese是否有效:" + licenseVerify.verify()); } @RequestMapping(value = "/registrationCode") public Result registrationCode() { JSONObject jsonObject = new JSONObject(); if (!licenseVerify.verify()) { return Result.error().message("license已过期!"); } jsonObject.set("code", licenseVerify.getLicenseExtraModel().getRegistrationCode()); jsonObject.set("company", licenseVerify.getSubject()); return Result.ok().data(jsonObject); } }

本文作者:酷少少

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!