hardwareEncryption.java
3.01 KB
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
package etelligens.com.foodsafety.utils;
import java.math.BigInteger;
import java.nio.ByteBuffer;
/**
* @author wj
* @Description: 获取硬件中的指令加密
* @create 2023/12/27 14:53
**/
public class hardwareEncryption {
public static byte[] CRC16_XMODEM(byte[] data,int type){
int len = data.length;
int wCRCin = 0x0000;
int wCPoly = 0x0483;
int i,j;
if(type == 1)
{
wCPoly = 0x6072;
}
for(i=0;i<len;i++)
{
wCRCin = wCRCin^(data[i]<<8);
for(j=0;j<8;j++)
{
if((wCRCin & 0x8000)>0) wCRCin = (wCRCin<<1)^wCPoly;
else wCRCin = wCRCin<<1;
}
}
return intToByteArray(wCRCin & 0x0000ffff);
}
public static byte[] intToByteArray(int value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
public static byte[] intTo8DigitHexString(int decimalNumber) {
// 使用 Integer.toHexString() 将整数转为十六进制字符串
String hexString = Integer.toHexString(decimalNumber);
// 如果十六进制字符串长度不足8位,前面补0
while (hexString.length() < 8) {
hexString = "0" + hexString;
}
return hexStringToByteArray(hexString);
}
private static byte[] hexStringToByteArray(String hexString) {
// 确保字符串长度为偶数
if (hexString.length() % 2 != 0) {
throw new IllegalArgumentException("Hex string length must be even.");
}
// 计算字节数组的长度
int byteArrayLength = hexString.length() / 2;
byte[] byteArray = new byte[byteArrayLength];
// 解析每两个字符为一个字节
for (int i = 0; i < byteArrayLength; i++) {
int index = i * 2;
int intValue = Integer.parseInt(hexString.substring(index, index + 2), 16);
byteArray[i] = (byte) intValue;
}
return byteArray;
}
public static byte[] concatenateArrays(byte[] first, byte[] second) {
ByteBuffer buffer = ByteBuffer.allocate(first.length + second.length);
buffer.put(first);
buffer.put(second);
return buffer.array();
}
public static byte[] removeFirstAndLast(byte[] originalArray) {
if (originalArray.length < 3) {
// 如果数组长度小于3,无法去掉第一个和最后一个元素
return new byte[0];
}
byte[] newArray = new byte[originalArray.length - 2];
System.arraycopy(originalArray, 1, newArray, 0, newArray.length);
return newArray;
}
public static byte[] removeFirstTwo(byte[] originalArray) {
if (originalArray.length < 2) {
// 如果数组长度小于3,无法去掉第一个和第二个元素
return new byte[0];
}
byte[] newArray = new byte[originalArray.length - 2];
System.arraycopy(originalArray, 2, newArray, 0, newArray.length);
return newArray;
}
}