AES加密解密工具类

常用数据传输加密

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
/**
* 密钥
*/
private static final String KEY = "8f2ae598bc768a12341312313121412412c9";
/**
* 偏移量
*/
private static final String OFFSET = "34b373131231241212412bfd7d4790f";
/**
* 编码
*/
private static final String ENCODING = "UTF-8";
/**
* 算法
*/
private static final String ALGORITHM = "AES";
/**
* 默认的加密算法
*/
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

/**
* 加密
*
* @param data
* @return
*/
public static String encrypt(String data) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.US_ASCII), ALGORITHM);
//使用CBC模式,需要一个向量iv,可增加加密算法的强度
IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(data.getBytes(ENCODING));
//此处使用BASE64做转码
return parseByte2HexStr(encrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 解密
*
* @param data
* @return
*/
public static String decrypt(String data) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.US_ASCII), ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] buffer = parseHexStr2Byte(data);
byte[] encrypted = cipher.doFinal(buffer);
return new String(encrypted, ENCODING);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
private static String parseByte2HexStr(byte[] buf) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toLowerCase());
}
return sb.toString();
}

/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}

相关文章

统一响应返回工具类

JWT加密解密工具类