yanderong
2026-06-10 0a50085d6ef51274c28d3915446af6d9ddd91cd2
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
package com.stylefeng.guns.modular.system.util;
 
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
/**
 * 签名工具
 *
 * @author Lux
 * @version 1.0.0
 * @since 2026/6/5 11:20
 */
public class SignUtil {
 
    private static final String HMAC_SHA256 = "HmacSHA256";
 
    /**
     * 数据上报生成签名
     *
     * @param method 请求方式
     * @param url 请求路基,api的路径
     * @param accessKey 身份标识
     * @param accessSecret 密钥
     * @param timestamp 时间戳,精确到秒
     * @param nonce 唯一随机数,6位随机数
     * @return 签名后的数据
     */
    public static String generateSign(String method, String url, String accessKey, String accessSecret, String timestamp, String nonce) {
        try {
            String data = String.format("%s&%s&%s&%s&%s", method.toUpperCase(), url, accessKey, timestamp, nonce);
 
            Mac mac = Mac.getInstance(HMAC_SHA256);
            SecretKeySpec secretKeySpec = new SecretKeySpec(accessSecret.getBytes(StandardCharsets.UTF_8), HMAC_SHA256);
            mac.init(secretKeySpec);
            byte[] signBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(signBytes);
        } catch (Exception e) {
            throw new RuntimeException("生成签名失败", e);
        }
    }
 
}