吉安感知网项目-后端
xiebin
2026-01-06 d207a86cdf1ab52ef8cb7cd83bad8fceab8038cf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package org.sxkj.common.utils.license;
 
import java.io.*;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
 
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.sxkj.common.constant.CommonConstant;
 
/**
 * 这个类,在打包的时候,不发布到现场。
 *
 * @author stzhang
 */
public class LicenseUtils {
    public final static String licenseSourceFileName = "LICENSE.txt";
    public final static String licenseFileName = "LICENSE.lic";
 
    public static void initLicensePath(String licenseFilePath, LicenseData licenseData) {
        System.out.println("-----------开始初始化路径-----------");
        try {
            String[] content = convertLicenseDataToFileContent(licenseData);
 
            initLicensePath(licenseFilePath, licenseSourceFileName, content);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println("-----------初始化路径完成-----------");
    }
 
 
    /**
     * 初始化 License
     *
     * @param licenseData
     * @return
     */
    public static byte[] genLicenseFile( LicenseData licenseData) {
        System.out.println("-----------开始生成证书-----------");
        String[] content = convertLicenseDataToFileContent(licenseData);
        byte[] bytes;
        try {
            bytes = genLicenseFile(content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
 
 
        System.out.println("-----------生成证书完成-----------");
        return bytes;
    }
 
    /**
     * 初始化目录
     *
     * @param licensePath
     * @param sourceFileName
     * @param defaultLicenseContent
     * @throws Exception
     */
    private static void initLicensePath(String licensePath, String sourceFileName, String[] defaultLicenseContent) throws Exception {
        File file = new File(licensePath + File.separator + sourceFileName);
        File filePath = new File(licensePath);
        if (filePath.exists()) {
            System.out.println("路径已经存在:" + filePath.getAbsolutePath());
        } else {
            filePath.mkdirs();
        }
        if (file.exists()) {
            System.out.println("License源文件已经存在:" + file.getAbsolutePath());
        } else {
            List<String> lines = new ArrayList<String>();
            for (int j = 0, len = defaultLicenseContent.length; j < len; j++) {
                if (StringUtils.isNotEmpty(defaultLicenseContent[j])) {
                    lines.add(defaultLicenseContent[j]);
                }
            }
            FileUtils.writeLines(file, "UTF-8", lines);
            System.out.println("初始化路径完成:" + file.getAbsolutePath());
        }
 
    }
 
 
    /**
     * 生成证书License文件
     *
     * @param defaultLicenseContent: 默认产生的内容
     * @throws Exception
     */
    private static byte[] genLicenseFile( String[] defaultLicenseContent) throws Exception {
        // 加载证书
        PrivateKey privateKey = RSAEnCoder.getPrivateKey(CryptoPrivateKeys.KEYMODULUS, CryptoPrivateKeys.PRIVATEKEYEXPONENT);
 
        byte[] sByte = stringArrayToBytesWithEncoding(defaultLicenseContent, "UTF-8");
        byte[] encoderData = RSAEnCoder.encryptRSA(sByte, privateKey);
        String sign = RSAEnCoder.sign(encoderData, privateKey);
        //把签名也写进证书, 进行License的自我校验。
        byte[] signBytes = ("\n" + sign).getBytes();
        byte[] raw = new byte[encoderData.length + signBytes.length];
        //合并两个byte[]
        System.arraycopy(encoderData, 0, raw, 0, encoderData.length);
        System.arraycopy(signBytes, 0, raw, encoderData.length, signBytes.length);
        // 双重加密
        byte[] encoderaw = RSAEnCoder.encryptRSA(raw, privateKey);
        return encoderaw;
 
    }
 
    public static byte[] stringArrayToBytesWithEncoding(String[] strings, String charsetName)
        throws UnsupportedEncodingException {
 
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 
        for (String str : strings) {
            byte[] bytes = str.getBytes(charsetName); // 使用指定编码
            outputStream.write(bytes, 0, bytes.length);
            outputStream.write('\n'); // 可选:添加分隔符
        }
 
        return outputStream.toByteArray();
    }
 
    /**
     * 校验证书文件
     *
     * @param licenseFilePath 文件路径
     * @param currentDate     当前时间
     * @return
     * @throws Exception
     */
    public static boolean checkLicense(String licenseFilePath, Date currentDate) throws Exception {
        // 加载证书
        PublicKey publicKey = RSADeCoder.getPublicKey(CryptoPublicKeys.KEYMODULUS, CryptoPublicKeys.PUBLICKEYEXPONENT);
        File licenseFile = new File(licenseFilePath);
        if (!licenseFile.exists()) {
            throw new Exception("没有获取License文件");
        }
        FileInputStream fis = FileUtils.openInputStream(licenseFile);
        if (fis.available() == 0) {
            throw new FileNotFoundException("License加密文件为空");
        }
        fis.close();
        //首先读入License文件
        byte[] encoderData = FileUtils.readFileToByteArray(licenseFile);
        byte[] sbytes = RSADeCoder.decryptRSA(encoderData, publicKey);
        byte[] firstEncoderData = null;
        byte[] secondSignData = null;
        int index = 0;
        for (int len = sbytes.length; index < len; index++) {
            if (sbytes[index] == '\n') {
                firstEncoderData = new byte[index];
                secondSignData = new byte[len - index - 1];
                //合并两个byte[]
                System.arraycopy(sbytes, 0, firstEncoderData, 0, firstEncoderData.length);
                System.arraycopy(sbytes, index + 1, secondSignData, 0, secondSignData.length);
                //如果已经是base64编码, 则直接返回
                if (isArrayByteBase64(secondSignData)) {
                    break;
                }
            }
        }
        String sign = new String(secondSignData);
 
        boolean verify = RSADeCoder.verify(firstEncoderData, sign, publicKey);
        if (!verify) {
            throw new RuntimeException("License签名校验无效,请确认这证书的有效性.");
        }
        //再次解密, 得到最终的授权内容
        byte[] textBytes = RSADeCoder.decryptRSA(firstEncoderData, publicKey);
        System.out.println("授权文件详情:\n" + new String(textBytes));
        HashMap<String, String> prop = genDataFromArrayByte(textBytes);
        String licenseType = prop.get("LICENSETYPE");
        System.out.println("授权软件给:\n" + prop.get("LICENSENAME"));
        String machineCode = prop.get("MACHINECODE");
        String needCheckMachineCode = prop.get("CHECKMACHINECODE");
        if ((Boolean.TRUE.toString().equalsIgnoreCase(needCheckMachineCode))) {
            //唯一机器码
            String machCode = getSerialNumHDForLinux();
            if (StringUtils.isEmpty(machineCode) || ("," + machineCode + ",").indexOf("," + machCode + ",") < 0) {
                //--机器码的校验
                throw new RuntimeException("License校验,机器码与当前机器码不同");
            }
 
        }
        if ("2".equals(licenseType)) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
            String expireDay = prop.get("EXPIREDAY");
            Date expireDate = df.parse(expireDay);
            if (currentDate.after(expireDate)) {
                throw new RuntimeException("License已经过期,请联系厂商重新获取License授权.");
            }
        }
        return true;
 
    }
 
    /**
     * 获取文件过期时间
     *
     * @param licenseFilePath 文件路径
     * @return
     * @throws Exception
     */
    public static Date getLicenseExipreDate(String licenseFilePath) throws Exception {
        // 加载证书
        PublicKey publicKey = RSADeCoder.getPublicKey(CryptoPublicKeys.KEYMODULUS, CryptoPublicKeys.PUBLICKEYEXPONENT);
        File licenseFile = new File(licenseFilePath);
        if (!licenseFile.exists()) {
            throw new Exception("没有获取License文件");
        }
        FileInputStream fis = FileUtils.openInputStream(licenseFile);
        if (fis.available() == 0) {
            throw new FileNotFoundException("License加密文件为空");
        }
        fis.close();
        //首先读入License文件
        byte[] encoderData = FileUtils.readFileToByteArray(licenseFile);
        byte[] sbytes = RSADeCoder.decryptRSA(encoderData, publicKey);
        byte[] firstEncoderData = null;
        byte[] secondSignData = null;
        int index = 0;
        for (int len = sbytes.length; index < len; index++) {
            if (sbytes[index] == '\n') {
                firstEncoderData = new byte[index];
                secondSignData = new byte[len - index - 1];
                //合并两个byte[]
                System.arraycopy(sbytes, 0, firstEncoderData, 0, firstEncoderData.length);
                System.arraycopy(sbytes, index + 1, secondSignData, 0, secondSignData.length);
                //如果已经是base64编码, 则直接返回
                if (isArrayByteBase64(secondSignData)) {
                    break;
                }
            }
        }
        String sign = new String(secondSignData);
 
        boolean verify = RSADeCoder.verify(firstEncoderData, sign, publicKey);
        if (!verify) {
            throw new RuntimeException("License签名校验无效,请确认这证书的有效性.");
        }
        //再次解密, 得到最终的授权内容
        byte[] textBytes = RSADeCoder.decryptRSA(firstEncoderData, publicKey);
        System.out.println("授权文件详情:\n" + new String(textBytes));
        HashMap<String, String> prop = genDataFromArrayByte(textBytes);
        String licenseType = prop.get("LICENSETYPE");
        System.out.println("授权软件给:\n" + prop.get("LICENSENAME"));
        String machineCode = prop.get("MACHINECODE");
        String needCheckMachineCode = prop.get("CHECKMACHINECODE");
        if ((Boolean.TRUE.toString().equalsIgnoreCase(needCheckMachineCode))) {
            //唯一机器码
            String machCode = getSerialNumHDForLinux();
            if (StringUtils.isEmpty(machineCode) || ("," + machineCode + ",").indexOf("," + machCode + ",") < 0) {
                //--机器码的校验
                throw new RuntimeException("License校验,机器码与当前机器码不同");
            }
 
        }
        if ("2".equals(licenseType)) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
            String expireDay = prop.get("EXPIREDAY");
            Date expireDate = df.parse(expireDay);
            return expireDate;
        }
        return null;
    }
 
    private static HashMap<String, String> genDataFromArrayByte(byte[] b) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(b)));
        HashMap<String, String> data = new HashMap<String, String>();
        String str = null;
        while ((str = br.readLine()) != null) {
            if (StringUtils.isNotEmpty(str)) {
                str = str.trim();
                int pos = str.indexOf("=");
                if (pos <= 0) continue;
                if (str.length() > pos + 1) {
                    data.put(str.substring(0, pos).trim().toUpperCase(), str.substring(pos + 1).trim());
                } else {
                    data.put(str.substring(0, pos).trim().toUpperCase(), "");
                }
            }
        }
        return data;
    }
 
    private static boolean isArrayByteBase64(byte[] b) {
        try {
            if (Base64.isArrayByteBase64(b)) {
                return true;
            }
            return false;
        } catch (Exception e) {//nothing todo
            return false;
        }
    }
 
    /**
     * 获取机器唯一码
     *
     * @return
     * @throws IOException
     */
    public static String getSerialNumHDForLinux() throws IOException {
        String machineIdLinux = "";
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            return "";
        }
        try {
            StringBuffer output = new StringBuffer();
 
            Process p = Runtime.getRuntime().exec("/bin/bash -c\"hdparm -I /dev/sda | grep Serial\"");
            BufferedReader sNumReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
 
            String line = "";
            while ((line = sNumReader.readLine()) != null) {
                output.append(line + "\n");
            }
            machineIdLinux = output.toString().substring(output.indexOf("\n"), output.length()).trim();
 
        } catch (IOException e) {
            e.getMessage();
            throw e;
        }
        return machineIdLinux;
    }
 
    public static String[] convertLicenseDataToFileContent(LicenseData licenseData) {
        List<String> contentList = new ArrayList<>();
 
        if (licenseData.getLicenseId() != null) {
            contentList.add("licenseId=" + licenseData.getLicenseId());
        }
        if (licenseData.getLicenseName() != null) {
            contentList.add("licenseName=" + licenseData.getLicenseName());
        }
        if (licenseData.getLicenseType() != null) {
            contentList.add("licenseType=" + licenseData.getLicenseType());
        }
        if (licenseData.getExpireDay() != null) {
            contentList.add("expireDay=" + DateUtils.formatDate(licenseData.getExpireDay(), CommonConstant.YYYY_MM_DD)); // Using timestamp
        }
        if (licenseData.getPrintClientCount() != null) {
            contentList.add("printClientCount=" + licenseData.getPrintClientCount());
        }
        if (licenseData.getCheckMachineCode() != null) {
            contentList.add("checkMachineCode=" + licenseData.getCheckMachineCode());
        }
        if (licenseData.getMachineCode() != null && !licenseData.getMachineCode().isEmpty()) {
            contentList.add("machineCode=" + String.join(",", licenseData.getMachineCode()));
        }
 
        return contentList.toArray(new String[0]);
    }
 
}