package com.m2pool.lease.utils;

import java.math.BigInteger;
import java.security.MessageDigest;

public class HashUtils {

    private static final String key = "9f3c7a12";

    /**
     * 将十六进制字符串转换为字节数组 (两个字符代表一个字节)
     * @param hex 十六进制字符串
     * @return 转换后的字节数组
     */
    public static byte[] hexStringToByteArray(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i+1), 16));
        }
        return data;
    }

    public static String sha256(Long input) {
        try {
            // 获取 SHA-256 算法的 MessageDigest 实例
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            String key = getkey(input);
            // 将十六进制字符串转换为字节数组
            byte[] inputBytes = hexStringToByteArray(key);
            //时间戳 + 秘钥

            // 将输入字节数组进行 SHA-256 哈希计算
            byte[] hashBytes = digest.digest(inputBytes);
            String s = JnaUtils.bytesToHex(hashBytes);
            return s;
        } catch (Exception e) {
            throw new RuntimeException("SHA-256算法不可用", e);
        }
    }

    /**
     * 获取key
     * @param timestamp 时间戳
     * @return key
     */
    public static String getkey(Long timestamp){
        String inputStr = timestamp.toString();
        // 将字符串转换为 BigInteger 对象，指定基数为 10
        BigInteger decimalValue = new BigInteger(inputStr, 10);
        // 将 BigInteger 对象转换为十六进制字符串
        return decimalValue.toString(16) + key;
    }

    public static void main(String[] args) throws Exception {
    }
}
