package com.nbport.zgwl.seal.utils;

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

/**
 * HMacSHA256签名算法工具类
 *
 * @author xiaofengzhou
 */
public class HMacSHA256Util {

    public static String encrypt(String message, String appSecret) {
        final String algorithm = "HmacSHA256";
        try {
            Mac hmacSha256 = Mac.getInstance(algorithm);
            byte[] keyBytes = appSecret.getBytes(StandardCharsets.UTF_8);
            byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
            hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, algorithm));
            byte[] digestBytes = hmacSha256.doFinal(messageBytes);
            return byteArrayToHexString(digestBytes);
        } catch (Exception e) {
            throw new RuntimeException("HMacSHA256签名计算失败: " + e.getMessage(), e);
        }
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; (bytes != null) && (n < bytes.length); n++) {
            stmp = Integer.toHexString(bytes[n] & 0xFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }
}
