RestfulAuthUtils.java
13.5 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
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
package com.gsc4cloud.gsc.vpc.api.util;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* 简化版HTTP RESTful请求加密认证工具类
* 去掉请求参数参与签名计算,仅基于请求方法、路径、时间戳、随机数和应用密钥
*/
public class RestfulAuthUtils {
// 支持的加密算法
public enum Algorithm {
HMAC_SHA256("HmacSHA256"),
HMAC_SHA1("HmacSHA1"),
HMAC_MD5("HmacMD5");
private final String algorithmName;
Algorithm(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
// 默认算法
private static final Algorithm DEFAULT_ALGORITHM = Algorithm.HMAC_SHA256;
// 时间戳有效期(秒)
private static final int TIMESTAMP_EXPIRE_SECONDS = 300;
// 随机数长度
private static final int NONCE_LENGTH = 16;
/**
* 生成API签名
* @param appKey 应用密钥
* @param appSecret 应用秘钥
* @param method 请求方法
* @param path 请求路径
* @param timestamp 时间戳
* @param nonce 随机数
* @return 签名结果
* @throws NoSuchAlgorithmException 算法不存在异常
* @throws InvalidKeyException 密钥无效异常
*/
public static String generateSignature(String appKey, String appSecret,
String method, String path,
long timestamp, String nonce)
throws NoSuchAlgorithmException, InvalidKeyException {
// 构建签名源字符串
StringBuilder signatureSource = new StringBuilder();
signatureSource.append(method.toUpperCase())
.append("&")
.append(path)
.append("&")
.append(appKey)
.append("&")
.append(timestamp)
.append("&")
.append(nonce);
// 使用HMAC算法生成签名
Mac mac = Mac.getInstance(DEFAULT_ALGORITHM.getAlgorithmName());
SecretKeySpec secretKey = new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8),
DEFAULT_ALGORITHM.getAlgorithmName());
mac.init(secretKey);
byte[] signatureBytes = mac.doFinal(signatureSource.toString().getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(signatureBytes);
}
/**
* 验证API签名
* @param signature 待验证的签名
* @param appKey 应用密钥
* @param appSecret 应用秘钥
* @param method 请求方法
* @param path 请求路径
* @param timestamp 时间戳
* @param nonce 随机数
* @return 验证结果
*/
public static boolean verifySignature(String signature, String appKey, String appSecret,
String method, String path,
long timestamp, String nonce) {
try {
// 检查时间戳是否过期
long currentTime = Instant.now().getEpochSecond();
if (Math.abs(currentTime - timestamp) > TIMESTAMP_EXPIRE_SECONDS) {
System.out.println("签名验证失败:时间戳过期");
return false;
}
// 重新生成签名进行比对
String generatedSignature = generateSignature(appKey, appSecret, method, path, timestamp, nonce);
// 比较签名(使用常量时间比较防止计时攻击)
boolean result = constantTimeEquals(signature, generatedSignature);
if (!result) {
System.out.println("签名验证失败:签名不匹配");
System.out.println("期望签名: " + generatedSignature);
System.out.println("实际签名: " + signature);
}
return result;
} catch (NoSuchAlgorithmException e) {
System.out.println("签名验证失败:算法不存在 - " + e.getMessage());
return false;
} catch (InvalidKeyException e) {
System.out.println("签名验证失败:密钥无效 - " + e.getMessage());
return false;
} catch (Exception e) {
System.out.println("签名验证失败:未知错误 - " + e.getMessage());
return false;
}
}
/**
* 生成请求头
* @param appKey 应用密钥
* @param appSecret 应用秘钥
* @param method 请求方法
* @param path 请求路径
* @return 请求头
* @throws NoSuchAlgorithmException 算法不存在异常
* @throws InvalidKeyException 密钥无效异常
*/
public static Map<String, String> generateRequestHeaders(String appKey, String appSecret,
String method, String path)
throws NoSuchAlgorithmException, InvalidKeyException {
Map<String, String> headers = new HashMap<>();
long timestamp = Instant.now().getEpochSecond();
String nonce = generateNonce();
headers.put("X-AppKey", appKey);
headers.put("X-Timestamp", String.valueOf(timestamp));
headers.put("X-Nonce", nonce);
// 生成签名
String signature = generateSignature(appKey, appSecret, method, path, timestamp, nonce);
headers.put("Authorization", "HMAC " + signature);
return headers;
}
/**
* 生成随机数
* @return 随机数字符串
*/
private static String generateNonce() {
SecureRandom secureRandom = new SecureRandom();
byte[] nonceBytes = new byte[NONCE_LENGTH];
secureRandom.nextBytes(nonceBytes);
return Base64.getEncoder().encodeToString(nonceBytes);
}
/**
* 常量时间比较,防止计时攻击
* @param a 字符串a
* @param b 字符串b
* @return 是否相等
*/
private static boolean constantTimeEquals(String a, String b) {
if (a == null || b == null) {
return false;
}
if (a.length() != b.length()) {
return false;
}
int result = 0;
for (int i = 0; i < a.length(); i++) {
result |= a.charAt(i) ^ b.charAt(i);
}
return result == 0;
}
/**
* 签名验证过滤器
*/
public static class AuthFilter {
private final String appSecret;
public AuthFilter(String appSecret) {
this.appSecret = appSecret;
}
/**
* 验证请求
* @param request 请求对象
* @return 验证结果
*/
public boolean validateRequest(HttpRequest request) {
try {
String appKey = request.getHeader("X-AppKey");
String signatureHeader = request.getHeader("Authorization");
String timestampStr = request.getHeader("X-Timestamp");
String nonce = request.getHeader("X-Nonce");
// 检查必要的请求头
if (appKey == null || signatureHeader == null || timestampStr == null || nonce == null) {
System.out.println("签名验证失败:缺少必要的请求头");
System.out.println("X-AppKey: " + appKey);
System.out.println("Authorization: " + signatureHeader);
System.out.println("X-Timestamp: " + timestampStr);
System.out.println("X-Nonce: " + nonce);
return false;
}
// 解析时间戳
long timestamp;
try {
timestamp = Long.parseLong(timestampStr);
} catch (NumberFormatException e) {
System.out.println("签名验证失败:时间戳格式错误 - " + timestampStr);
return false;
}
// 移除签名前缀
String signature = signatureHeader;
if (signatureHeader.startsWith("HMAC ")) {
signature = signatureHeader.substring(5);
}
System.out.println("开始验证签名:");
System.out.println("请求方法: " + request.getMethod());
System.out.println("请求路径: " + request.getPath());
System.out.println("AppKey: " + appKey);
System.out.println("时间戳: " + timestamp);
System.out.println("随机数: " + nonce);
System.out.println("签名: " + signature);
return verifySignature(signature, appKey, appSecret,
request.getMethod(), request.getPath(),
timestamp, nonce);
} catch (Exception e) {
System.out.println("签名验证失败:" + e.getMessage());
e.printStackTrace();
return false;
}
}
}
/**
* HTTP请求模拟类
*/
public static class HttpRequest {
private final String method;
private final String path;
private final Map<String, String> headers;
public HttpRequest(String method, String path, Map<String, String> headers) {
this.method = method;
this.path = path;
this.headers = headers;
}
public String getMethod() {
return method;
}
public String getPath() {
return path;
}
public Map<String, String> getHeaders() {
return headers;
}
public String getHeader(String name) {
return headers != null ? headers.get(name) : null;
}
}
/**
* 主方法用于测试
*/
public static void main(String[] args) {
try {
System.out.println("=== 简化版RESTful请求加密认证测试 ===\n");
// 测试数据
String appKey = "testAppKey123";
String appSecret = "testAppSecret456";
String method = "GET";
String path = "/api/v1/users";
System.out.println("1. 生成请求头...");
Map<String, String> headers = generateRequestHeaders(appKey, appSecret, method, path);
System.out.println("生成的请求头:");
headers.forEach((key, value) -> System.out.println(" " + key + ": " + value));
// 创建模拟请求
System.out.println("\n2. 创建模拟请求...");
HttpRequest request = new HttpRequest(method, path, headers);
// 创建验证过滤器
System.out.println("\n3. 创建签名验证过滤器...");
AuthFilter authFilter = new AuthFilter(appSecret);
// 验证请求
System.out.println("\n4. 验证请求...");
boolean isValid = authFilter.validateRequest(request);
System.out.println("\n请求验证结果: " + (isValid ? "成功" : "失败"));
// 测试篡改签名的情况
System.out.println("\n=== 测试篡改签名 ===");
Map<String, String> tamperedHeaders = new HashMap<>(headers);
tamperedHeaders.put("Authorization", "HMAC tamperedSignature123");
HttpRequest tamperedRequest = new HttpRequest(method, path, tamperedHeaders);
boolean isTamperedValid = authFilter.validateRequest(tamperedRequest);
System.out.println("篡改签名后的验证结果: " + (isTamperedValid ? "成功" : "失败"));
// 测试不同请求方法
System.out.println("\n=== 测试不同请求方法 ===");
Map<String, String> postHeaders = generateRequestHeaders(appKey, appSecret, "POST", path);
HttpRequest postRequest = new HttpRequest("GET", path, postHeaders); // 使用GET方法但用POST的签名
boolean isMethodValid = authFilter.validateRequest(postRequest);
System.out.println("请求方法不匹配的验证结果: " + (isMethodValid ? "成功" : "失败"));
// 测试不同请求路径
System.out.println("\n=== 测试不同请求路径 ===");
Map<String, String> pathHeaders = generateRequestHeaders(appKey, appSecret, method, "/api/v1/orders");
HttpRequest pathRequest = new HttpRequest(method, path, pathHeaders); // 使用不同路径
boolean isPathValid = authFilter.validateRequest(pathRequest);
System.out.println("请求路径不匹配的验证结果: " + (isPathValid ? "成功" : "失败"));
} catch (Exception e) {
System.err.println("\n测试过程中出现异常: " + e.getMessage());
e.printStackTrace();
}
}
}