SpringBoot数据加解密
RSAUtil工具类:
//前端公钥
public static final String PUBLIC_KEY = "xxxxx";
// public static final String PUBLIC_KEY = "xxxxxxxx";
public static final String PRIVATE_KEY = "xxxxxxx";
//前端私钥
// public static final String PRIVATE_KEY = "xxxxxx";
// RSA最大加密明文大小
private static final int MAX_ENCRYPT_BLOCK = 117;
// RSA最大解密密文大小
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* RAS非对称加密,随机生成密钥对
*
* @return 密钥对
*/
public static Map<String, String> genKeyPair() {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 初始化密钥对生成器,密钥大小为96-1024位
assert keyPairGen != null;
keyPairGen.initialize(1024, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
// 将公钥和私钥保存到Map
Map<String, String> res = new HashMap<String, String>(2) {{
}};
String pub = new String(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
String pri = new String(Base64.getEncoder().encodeToString((privateKey.getEncoded())));
System.out.println(pub);
System.out.println(pri);
return res;
}
/**
* RAS非对称加密: 公钥加密
*
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
*/
public static String encrypt(String str, String publicKey) {
//base64编码的公钥
byte[] decoded = Base64.getDecoder().decode(publicKey);
RSAPublicKey pubKey;
String outStr = null;
try {
pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
// 分段加密
// URLEncoder编码解决中文乱码问题
byte[] data = URLEncoder.encode(str, "UTF-8").getBytes("UTF-8");
// 加密时超过117字节就报错。为此采用分段加密的办法来加密
byte[] enBytes = null;
for (int i = 0; i < data.length; i += MAX_ENCRYPT_BLOCK) {
// 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_ENCRYPT_BLOCK));
enBytes = ArrayUtils.addAll(enBytes, doFinal);
}
outStr = Base64.getEncoder().encodeToString(enBytes);
} catch (InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException |
NoSuchPaddingException | NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
//RSA加密
return outStr;
}
/**
* RSA私钥解密
*
* @param str 加密字符串
* @param privateKey 私钥
* @return 铭文
*/
public static String decrypt(String str, String privateKey) {
try {
str = str.replaceAll(" ","");
//base64编码的私钥
byte[] decoded = Base64.getDecoder().decode(privateKey);
RSAPrivateKey priKey;
//RSA解密
Cipher cipher;
String outStr = null;
priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
byte[] data = Base64.getDecoder().decode(str.getBytes("UTF-8"));
// 返回UTF-8编码的解密信息
int inputLen = data.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(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * 128;
}
byte[] decryptedData = out.toByteArray();
out.close();
return URLDecoder.decode(new String(decryptedData, "UTF-8"), "UTF-8");
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException(e);
} catch (BadPaddingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
// genKeyPair();
String str = "jack";
// 加密后的数据
String encryptData = null;
try {
// 使用公钥加密
encryptData = encrypt(str ,PUBLIC_KEY);
System.out.println(encryptData);
} catch (Exception e) {
log.error("加密失败 {}", e);
}
// 解密后的数据
String decryptData = null;
try {
// 使用私钥解密
decryptData = decrypt(encryptData, PRIVATE_KEY);
System.out.println(decryptData);
} catch (Exception e) {
e.printStackTrace();
}
}
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
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
定义解密注解
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DecryptApi {
}
1
2
3
4
5
6
2
3
4
5
6
在get请求上添加注解
@GetMapping("test")
public void test(@DecryptApi String username, @DecryptApi String password){
}
1
2
3
4
5
2
3
4
5
定义参数解析器
public class AbsHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
private Logger logger=LoggerFactory.getLogger(AbsHandlerMethodArgumentResolver.class);
@Override
public boolean supportsParameter(MethodParameter parameter) {
logger.info("正在调用执行:{}",parameter.getMember().getName());
return parameter.hasParameterAnnotation(DecryptApi.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
logger.info("对用户请求进行解析");
Parameter parameter = methodParameter.getParameter();
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
String data = request.getParameter(parameter.getName());
String decrypt = RSAUtil.decrypt(data, RSAUtil.PRIVATE_KEY);
return decrypt;
}
}
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
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
注册参数解析器
@Configuration
public class AbsWebMvcConfigurerAdapter extends WebMvcConfigurationSupport {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new AbsHandlerMethodArgumentResolver());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
前端传参:
curl --location '127.0.0.1:9999/test?username=HXZDFybpqHLvpw7wSB5zjeJ9MbnPFdSOyp7CgCRMxTrI8xUrBrdIahTD%2FIEEiybik6OosGsrEzHiZpIKrMgzpD5FhquAklPNNi%2Bntkf6SVZLCOIWUoDV5jOVYnRSDzU4MigRpOCyiMy5T%2Fzyt%2FlXl%2BP7EBVwuivXQWN%2FM5K60ws%3D&password=HXZDFybpqHLvpw7wSB5zjeJ9MbnPFdSOyp7CgCRMxTrI8xUrBrdIahTD%2FIEEiybik6OosGsrEzHiZpIKrMgzpD5FhquAklPNNi%2Bntkf6SVZLCOIWUoDV5jOVYnRSDzU4MigRpOCyiMy5T%2Fzyt%2FlXl%2BP7EBVwuivXQWN%2FM5K60ws%3D'
1
上次更新: 2024/08/12, 14:38:19