package org.dromara.zjk.zwy.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.Base64;

public class HmacSm3SignUtil {

    // 生成 sign
    public static String generateSign(String appId, String secretKey, Map<String, String> params) {
        String paramString = buildParamString(params);
        String raw = appId + secretKey + paramString;
        return hmacSm3Base64(raw, secretKey);
    }

    // 构造签名字符串（参数按 key 排序）
    private static String buildParamString(Map<String, String> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append(":").append(params.get(key)).append(",");
        }
        if (sb.length() > 0) {
            sb.setLength(sb.length() - 1); // 去掉最后一个逗号
        }
        return sb.toString();
    }

    // HMAC-SM3 实现（注意：需要集成国密 Provider）
    public static String hmacSm3Base64(String message, String secretKey) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSM3");
            Mac mac = Mac.getInstance("HmacSM3"); // 若集成 Provider，写 Mac.getInstance("HmacSM3", "GmProvider")
            mac.init(keySpec);
            byte[] result = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            throw new RuntimeException("HMAC-SM3 签名失败", e);
        }
    }

    // 示例生成 random 和 nonce
    public static String generateRandom() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String generateNonce() {
        return String.valueOf(System.currentTimeMillis());
    }
}

