SignUtil.java
2.42 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
package cn.com.glsx.stoassistant.utils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* 签名工具类
*/
public class SignUtil {
private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
private static final String SIGN_KEY = "X-Sign";
private static final String SECRET_PARAM = "secret=";
/**
* 生成签名
*/
public static String generateSign(Map<String, Object> params, String secret) {
// 1. 参数排序
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
// 2. 拼接参数
StringBuilder sb = new StringBuilder();
for (String key : keys) {
if (SIGN_KEY.equals(key) || params.get(key) == null || "".equals(params.get(key))) {
continue;
}
sb.append(key).append("=").append(params.get(key)).append("&");
}
String stringToSign = sb.toString();
stringToSign = stringToSign + SECRET_PARAM + secret;
// 3. 计算HMAC-SHA256签名
return calculateHmacSha256(secret, stringToSign);
}
/**
* 计算 HMAC-SHA256 签名
*/
private static String calculateHmacSha256(String secret, String data) {
try {
Mac sha256_HMAC = Mac.getInstance(HMAC_SHA256_ALGORITHM);
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_SHA256_ALGORITHM);
sha256_HMAC.init(secretKey);
byte[] hashBytes = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
return bytesToHex(hashBytes);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("HMAC-SHA256 algorithm not available", e);
} catch (InvalidKeyException e) {
throw new RuntimeException("Invalid secret key", e);
}
}
/**
* 将字节数组转换为16进制字符串
*/
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}