package cn.reghao.oss.store.util;

import cn.reghao.jutil.jdk.converter.ByteHex;

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

/**
 * @author reghao
 * @date 2023-10-17 14:57:33
 */
public class SignatureUtil {
    private static final String ALGORITHM = "HmacSHA256";

    public static String sign(String message, String secret) {
        try {
            Mac hmac = Mac.getInstance(ALGORITHM);
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            hmac.init(secretKey);
            byte[] bytes = hmac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return ByteHex.bytes2Hex(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean valid(String message, String secret, String signature) {
        return signature != null && signature.equals(sign(message, secret));
    }
}
