AESUtil.java
3.34 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package com.qgutech.util;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
/**
* @author xxx
* @date 2024/12/25 11:31
* @description
*/
public class AESUtil {
/**
* 偏移量
*
* 说明:偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
* 此处值与前端偏移量值保持一致
*/
private static String iv = "37fa77f6a3b0462d";
private static String uniqueKey = "1234567890123456";
/**
* 加密算法
*/
private static String Algorithm = "AES";
/**
* 算法/模式/补码方式
*/
private static String AlgorithmProvider = "AES/CBC/PKCS5Padding";
/**
* 加密
*
* @param src 加密内容
* @return
* @throws Exception
*/
public static String encrypt(String src) throws Exception {
byte[] key = uniqueKey.getBytes();
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] cipherBytes = cipher.doFinal(src.getBytes("UTF-8"));
return byteToHexString(cipherBytes);
}
/**
* 解密
*
* @param enc 加密内容
* @return
* @throws Exception
*/
public static String decrypt(String enc) throws Exception {
byte[] key = uniqueKey.getBytes();
SecretKey secretKey = new SecretKeySpec(key, Algorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
Cipher cipher = Cipher.getInstance(AlgorithmProvider);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] hexBytes = hexStringToBytes(enc);
byte[] plainBytes = cipher.doFinal(hexBytes);
return new String(plainBytes, "UTF-8");
}
/**
* 将byte数组转换为16进制字符串
*
* @param src
* @return
*/
private static String byteToHexString(byte[] src) {
return Hex.encodeHexString(src);
}
/**
* 将16进制字符串转换为byte数组
*
* @param hexString
* @return
*/
private static byte[] hexStringToBytes(String hexString) throws DecoderException {
return Hex.decodeHex(hexString);
}
/**
* AES加密、解密测试方法
*
* @param args
*/
public static void main(String[] args) {
try {
// 唯一key作为密钥
// 加密前数据,此处数据与前端数据一致(加密内容包含有时间戳),请注意查看前端加密前数据
String src = "hczd";
System.out.println("密钥:" + uniqueKey);
System.out.println("原字符串:" + src);
// 加密
String encrypt = encrypt(src);
System.out.println("加密:" + encrypt);
// 解密
String decrypt = decrypt(encrypt);
System.out.println("解密:" + decrypt);
} catch (Exception e) {
e.printStackTrace();
}
}
}