SignUtil.java 2.42 KB
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();
    }
}