package com.fs.live.utils;

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

public class VerifyUtils {

    /**
     * 验证签名
     */
    public static boolean verifySignature(String liveId, String userId, String userType, String secret, String signature) throws Exception {
        String expected = generateSignature(liveId, userId, userType, secret);
        return expected.equals(signature);
    }

    /**
     * 生成签名：将 liveId、userId、userType 按顺序拼接后，用 HMAC-SHA256 算法生成签名
     *
     * @param liveId   直播间ID
     * @param userId   用户ID
     * @param userType 用户类型
     * @param secret   共享密钥
     * @return 十六进制格式的签名
     * @throws Exception e
     */
    private static String generateSignature(String liveId, String userId, String userType, String secret) throws Exception {
        String data = liveId + userId + userType + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(keySpec);
        byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(rawHmac);
    }

    /**
     * 将字节数组转换为十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
