package com.ttstd.controlled.network;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * provision 签名工具。
 *
 * 签名规则须与服务端保持一致：HMAC-SHA256(secret, sn + "|" + nonce + "|" + timestamp)，
 * 输出小写十六进制字符串。
 */
public final class HmacSigner {

    private HmacSigner() {
    }

    public static String signProvision(String secret, String sn, String nonce, long timestamp) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            String data = sn + "|" + nonce + "|" + timestamp;
            byte[] raw = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder(raw.length * 2);
            for (byte b : raw) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new IllegalStateException("HMAC 计算失败", e);
        }
    }
}
