Commit be3bab8f by zhouyachao

初始版本

parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.byit</groupId>
<artifactId>licensebuild</artifactId>
<version>0.0.1</version>
<name>licensebuild</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.byit.licensebuild.license.LicenseGenerator</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<!-- <goal>single</goal>-->
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Manifest-Version: 1.0
Main-Class: com.byit.licensebuild.license.LicenseGenerator
Manifest-Version: 1.0
Main-Class: com.byit.licensebuild.license.LicenseGenerator
package com.byit.licensebuild.license;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
//import it.sauronsoftware.base64.Base64;
//若报错,编译路径移除jdk,再添加jdk
/** */
/**
* <p>
* BASE64编码解码工具包
* </p>
* <p>
* 依赖javabase64-1.3.1.jar 或 common-codec
* </p>
*
* @author IceWee
* @date 2012-5-19
* @version 1.0
*/
public class Base64Utils {
/** *//**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/** *//**
* <p>
* BASE64字符串解码为二进制数据
* </p>
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception {
//return Base64.decode(base64.getBytes());
return new BASE64Decoder().decodeBuffer(base64);
}
/** *//**
* <p>
* 二进制数据编码为BASE64字符串
* </p>
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
//return new String(Base64.encode(bytes));
return new BASE64Encoder().encode(bytes);
}
/** *//**
* <p>
* 将文件编码为BASE64字符串
* </p>
* <p>
* 大文件慎用,可能会导致内存溢出
* </p>
*
* @param filePath 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/** *//**
* <p>
* BASE64字符串转回文件
* </p>
*
* @param filePath 文件绝对路径
* @param base64 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/** *//**
* <p>
* 文件转换为二进制数组
* </p>
*
* @param filePath 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/** *//**
* <p>
* 二进制数据写文件
* </p>
*
* @param bytes 二进制数据
* @param filePath 文件生成目录
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
// if (!destFile.getParentFile().exists()) {
// destFile.getParentFile().mkdirs();
// }
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}
package com.byit.licensebuild.license;
/**
* @program: result-spring-boot-starter
* @description:
* @author: guoqingming
* @create: 2018-12-12 21:44
**/
public class BizException extends RuntimeException {
private int code;
private String msg;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public BizException(String msg) {
super(msg);
this.code = 500;
this.msg = msg;
}
}
package com.byit.licensebuild.license;
import java.util.Collection;
import java.util.Objects;
/**
* @program:
* @description: 用于参数检查
* @author: guoqingming
* @create: 2018-12-10 16:02
**/
public class CheckUtil {
/**
* 检查字符串是否为空
* @param str
* @param msg
*/
public static void isBlank(String str,String msg){
if(null == str || "".equals(str)){
throw new BizException(msg);
}
}
/**
* 检查表达式是否为真
* @param expression
* @param msg
*/
public static void isTrue(boolean expression,String msg){
if(expression){
throw new BizException(msg);
}
}
/**
* 检查对象是否为空
* @param obj
* @param msg
*/
public static void isNull(Object obj, String msg) {
if(Objects.isNull(obj)){
throw new BizException(msg);
}
}
/**
* 检查集合是否为空及集合是否有元素
* @param c
* @param msg
*/
public static void isEmpty(Collection c, String msg) {
if(c == null || c.isEmpty()){
throw new BizException(msg);
}
}
}
package com.byit.licensebuild.license;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
/**
* 文件工具类
* @author happyqing
*/
public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
* 获得类的基路径,打成jar包也可以正确获得路径
* @return
*/
public static String getBasePath(){
/*
/D:/zhao/Documents/NetBeansProjects/docCompare/build/classes/
/D:/zhao/Documents/NetBeansProjects/docCompare/dist/bundles/docCompare/app/docCompare.jar
*/
String filePath = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile();
if (filePath.endsWith(".jar")){
filePath = filePath.substring(0, filePath.lastIndexOf("/"));
try {
//解决路径中有空格%20的问题
filePath = URLDecoder.decode(filePath, "UTF-8");
} catch (UnsupportedEncodingException ex) {
}
}
File file = new File(filePath);
filePath = file.getAbsolutePath();
return filePath;
}
public static void main(String[] args){
System.out.println(getBasePath());
}
}
package com.byit.licensebuild.license;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.springframework.util.StringUtils;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Date;
/**
* 生成license
* @author happyqing
* 2014.6.15
*/
public class LicenseGenerator {
/**
* serial:由客户提供
* timeEnd:过期时间
*/
//private static String licensestatic = "serial=VMware-42 1c 65 cb 7b e1 b5 c9-43 de c1 91 9d b0 a4 38;" +
//"timeEnd=1565971200000";
private static String licensestatic = "";
private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbrw0Y+UOVvBo1W56aqYpnZTfxNf4do1BpJszG\n" +
"EPk1md9Lh5F6SAiQSvfVTxURB98uK15UrY6KeW2TOQARQ5ay/vA5UQl5FEUfjKGKn+E2L0aUTLrJ\n" +
"G44Z5BwdmUNXi99apLjP1QKsR3iqjJNk7lFXFDmwBemdJii8TuhnLOj0dQIDAQAB";
/**
* RSA算法
* 公钥和私钥是一对,此处只用私钥加密
*/
public static final String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANuvDRj5Q5W8GjVbnpqpimdlN/E1\n" +
"/h2jUGkmzMYQ+TWZ30uHkXpICJBK99VPFREH3y4rXlStjop5bZM5ABFDlrL+8DlRCXkURR+MoYqf\n" +
"4TYvRpRMuskbjhnkHB2ZQ1eL31qkuM/VAqxHeKqMk2TuUVcUObAF6Z0mKLxO6Gcs6PR1AgMBAAEC\n" +
"gYEAjrGYt1UJklQZTflR/zIK5Xg4qyQgCI5RJ8v9DNZvmWJ2STAozZ3GejtH2bVBgMt1Kx8eabBG\n" +
"Oyn+g7dtlMkrM6pQDkbg94g3SYTUIKhmDFkZBvWAIL4ZySbK3ks0RaypV2hoLkHmNCtEp0nx75JB\n" +
"cq189qO6EZGvzEu6mOzupeECQQD+ZTeAMNDOUq/lM5UW+ns5IBla5HoDKQXi+q2iaSg5OyALSRTa\n" +
"4RVtrsUvNFQtIAGiHErdR744MbPOwaqsdA+pAkEA3RHIuLSh5Dr84W82i+LJbHseHniF1962B6Mr\n" +
"+/XotzEL/PkG1AZ0ab9L3aM6dwluzmLdi01Km4Uh8REBMZ/t7QJBAI78jSl8RqDxUPRe/dmgiEof\n" +
"hKDV8s577Fcb1ySGPpmMZgJx3Ur5YHX52dMicn26k7BufpXJkV08cngv2qJ7yaECQD2gAIEksWBq\n" +
"5SV+mAkErjuUUoAR/tV/WuTkIpW5Jicy//GEBdhC+F6mGeLt5pVaRs43lySG5j5WLXEC2X9Y4r0C\n" +
"QB6LYnJiYqUoElK6rv5vkWLOjK/qvfgYd9aHgUIE3tJY6jKI1kWIFvG2qQ6GTgpS14vibmtN5cTz\n" +
"hSSj+eKQfOA=";
public static void generator() throws Exception {
System.out.println("私钥加密——公钥解密");
//String source = "568b8fa5cdfd8a2623bda1d8ab7b7b34";
System.out.println("原文字:\r\n" + licensestatic);
byte[] data = licensestatic.getBytes();
byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
Base64Utils.byteArrayToFile(encodedData, FileUtil.getBasePath() + File.separator + "license.dat");
System.out.println("文件license路径:\r\n" + FileUtil.getBasePath() + File.separator + "license.dat");
}
public static void main(String[] args) throws Exception {
String uniqueCode = "";
String timeEnd = "2019-12-05 13:00:00";
Date date = null;
for (String arg : args) {
if (arg.toLowerCase().startsWith("-uniquecode=")) {
uniqueCode = arg.substring("-uniqueCode=".length());
}
if (arg.toLowerCase().startsWith("-timeend=")) {
timeEnd = arg.substring("-timeEnd=".length());
}
}
if(StringUtils.isEmpty(uniqueCode)){
uniqueCode = UniqueCode.uniqueCode();
}
if(StringUtils.isEmpty(timeEnd)){
date = new Date();
}else{
date = DateUtil.parse(timeEnd, DatePattern.NORM_DATETIME_PATTERN);
}
licensestatic = "serial=" + uniqueCode + ";"
+"timeEnd=" + date.getTime();
generator();
byte[] license = Base64Utils.fileToByte
(FileUtil.getBasePath() + File.separator + "license.dat");
byte[] bytes = RSAUtils.decryptByPublicKey(license, publicKey);
String decryptedData = new String(bytes);
System.out.println("解密后文字:\r\n" + decryptedData);
}
}
package com.byit.licensebuild.license;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import java.util.Date;
/**
* @program: ddmp-parent
* @description:
* @author: guoqingming
* @create: 2019-08-16 10:58
**/
public class LicenseUtil {
public static final String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANuvDRj5Q5W8GjVbnpqpimdlN/E1\n" +
"/h2jUGkmzMYQ+TWZ30uHkXpICJBK99VPFREH3y4rXlStjop5bZM5ABFDlrL+8DlRCXkURR+MoYqf\n" +
"4TYvRpRMuskbjhnkHB2ZQ1eL31qkuM/VAqxHeKqMk2TuUVcUObAF6Z0mKLxO6Gcs6PR1AgMBAAEC\n" +
"gYEAjrGYt1UJklQZTflR/zIK5Xg4qyQgCI5RJ8v9DNZvmWJ2STAozZ3GejtH2bVBgMt1Kx8eabBG\n" +
"Oyn+g7dtlMkrM6pQDkbg94g3SYTUIKhmDFkZBvWAIL4ZySbK3ks0RaypV2hoLkHmNCtEp0nx75JB\n" +
"cq189qO6EZGvzEu6mOzupeECQQD+ZTeAMNDOUq/lM5UW+ns5IBla5HoDKQXi+q2iaSg5OyALSRTa\n" +
"4RVtrsUvNFQtIAGiHErdR744MbPOwaqsdA+pAkEA3RHIuLSh5Dr84W82i+LJbHseHniF1962B6Mr\n" +
"+/XotzEL/PkG1AZ0ab9L3aM6dwluzmLdi01Km4Uh8REBMZ/t7QJBAI78jSl8RqDxUPRe/dmgiEof\n" +
"hKDV8s577Fcb1ySGPpmMZgJx3Ur5YHX52dMicn26k7BufpXJkV08cngv2qJ7yaECQD2gAIEksWBq\n" +
"5SV+mAkErjuUUoAR/tV/WuTkIpW5Jicy//GEBdhC+F6mGeLt5pVaRs43lySG5j5WLXEC2X9Y4r0C\n" +
"QB6LYnJiYqUoElK6rv5vkWLOjK/qvfgYd9aHgUIE3tJY6jKI1kWIFvG2qQ6GTgpS14vibmtN5cTz\n" +
"hSSj+eKQfOA=";
private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbrw0Y+UOVvBo1W56aqYpnZTfxNf4do1BpJszG\n" +
"EPk1md9Lh5F6SAiQSvfVTxURB98uK15UrY6KeW2TOQARQ5ay/vA5UQl5FEUfjKGKn+E2L0aUTLrJ\n" +
"G44Z5BwdmUNXi99apLjP1QKsR3iqjJNk7lFXFDmwBemdJii8TuhnLOj0dQIDAQAB";
public static LicenseVerifyData verifyLicense(byte[] license) {
LicenseVerifyData data = new LicenseVerifyData();
try {
String result = UniqueCode.uniqueCode();
try {
byte[] bytes = RSAUtils.decryptByPublicKey(license, publicKey);
String decryptedData = new String(bytes);
String cpuSerialPart = decryptedData.split(";")[0];
String cpuSerial = cpuSerialPart.split("=")[1];
if (!result.equals(cpuSerial)) {
data.setFlag(false);
data.setMsg("CPU序列号不一致,license校验失败");
return data;
}
String expiredTimePart = decryptedData.split(";")[1];
String expiredTimeStr = expiredTimePart.split("=")[1];
Date date = new Date(Long.valueOf(expiredTimeStr));
Date now = new Date();
CheckUtil.isTrue(now.after(date), StrUtil.format("license已过期,过期时间:{}", DateUtil.format(date, "yyyy-MM-dd")));
if (now.after(date)) {
data.setFlag(false);
data.setMsg(StrUtil.format("license已过期,过期时间:{}", DateUtil.format(date, "yyyy-MM-dd")));
return data;
}
data.setFlag(true);
return data;
} catch (Exception e) {
data.setFlag(false);
data.setMsg("解密失败");
System.out.println("解密失败:" + e);
return data;
}
} catch (Exception e) {
data.setFlag(false);
data.setMsg("获取服务器CPU序列号失败");
System.out.println("解密失败:"+ e);
return data;
}
}
public static void main(String[] args) throws Exception {
byte[] license = Base64Utils.fileToByte
("/Users/guo/workroom/ddmp-parent/ddmp-web-starter/target/classes/license.dat");
verifyLicense(license);
System.out.println("验证结束");
}
}
package com.byit.licensebuild.license;
import java.io.Serializable;
/**
* @program: ddmp-parent
* @description: license验证结果
* @author: guoqingming
* @create: 2019-08-16 15:07
**/
public class LicenseVerifyData implements Serializable {
private boolean flag;
private String msg;
public LicenseVerifyData() {
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.byit.licensebuild.license;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/** */
/**
* <p>
* RSA公钥/私钥/签名工具包
* </p>
* <p>
* 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
* </p>
* <p>
* 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
* </p>
*
* @author IceWee
* @date 2012-4-26
* @version 1.0
*/
public class RSAUtils {
/** *//**
* 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/** *//**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/** *//**
* 获取公钥的key
*/
private static final String PUBLIC_KEY = "RSAPublicKey";
/** *//**
* 获取私钥的key
*/
private static final String PRIVATE_KEY = "RSAPrivateKey";
/** *//**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/** *//**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/** *//**
* <p>
* 生成密钥对(公钥和私钥)
* </p>
*
* @return
* @throws Exception
*/
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/** *//**
* <p>
* 用私钥对信息生成数字签名
* </p>
*
* @param data 已加密数据
* @param privateKey 私钥(BASE64编码)
*
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64Utils.encode(signature.sign());
}
/** *//**
* <p>
* 校验数字签名
* </p>
*
* @param data 已加密数据
* @param publicKey 公钥(BASE64编码)
* @param sign 数字签名
*
* @return
* @throws Exception
*
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64Utils.decode(sign));
}
/** *//**
* <P>
* 私钥解密
* </p>
*
* @param encryptedData 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/** *//**
* <p>
* 公钥解密
* </p>
*
* @param encryptedData 已加密数据
* @param publicKey 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/** *//**
* <p>
* 公钥加密
* </p>
*
* @param data 源数据
* @param publicKey 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/** *//**
* <p>
* 私钥加密
* </p>
*
* @param data 源数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/** *//**
* <p>
* 获取私钥
* </p>
*
* @param keyMap 密钥对
* @return
* @throws Exception
*/
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64Utils.encode(key.getEncoded());
}
/** *//**
* <p>
* 获取公钥
* </p>
*
* @param keyMap 密钥对
* @return
* @throws Exception
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64Utils.encode(key.getEncoded());
}
}
package com.byit.licensebuild.license;
import cn.hutool.core.util.RuntimeUtil;
/**
* @author zhouyachao
* @description: TODO
* @createDate 获得机器唯一码
* Linux 运行 dmidecode -s system-serial-number 命令
* window 运行 wmic bios get serialnumber 命令
*/
public class UniqueCode {
/**
* 获得机器唯一码
* @return
* @throws Exception
*/
public static String uniqueCode() throws Exception{
String result = "";
String osName = System.getProperties().getProperty("os.name");
System.out.println(osName);
if(osName.toLowerCase().indexOf("linux") >= 0) {
Process process = Runtime.getRuntime().exec("dmidecode -s system-serial-number");
result = RuntimeUtil.getResult(process).replace("\n", "");
}else if(osName.toLowerCase().indexOf("windows") >= 0 ) {
System.out.println("running in Windows");
Process process = Runtime.getRuntime().exec("wmic bios get serialnumber");
result = RuntimeUtil.getResult(process).replace("\n", "").replace("\r", "").trim();
}else {
throw new Exception("license不支持该系统");
}
return result;
}
}
package com.byit.licensebuild;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LicensebuildApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment