package nckd.jimin.jyyy.bd.common.oauth;

import org.apache.commons.lang.StringUtils;

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

public class SHAUtils {


    public static String getSHA256Hex(String input) {
        try {
            // 创建一个 MessageDigest 实例，并指定算法为 SHA-256
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 将输入字符串转换为字节数组
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 检查时间戳是否一致，默认允许5分钟误差
     * @param timeStamp
     * @return
     */
    public static boolean checkDateTime(String timeStamp){
        long now = System.currentTimeMillis();
        if(StringUtils.isEmpty(timeStamp) || (StringUtils.isNotEmpty(timeStamp) && StringUtils.isNumeric(timeStamp) && Math.abs(now - Long.parseLong(timeStamp)) / 1000 > 5 * 60)){
            return false;
        }
        return true;
    }

}
