package com.sifang.modules.customer.utils;


import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HmacUtil {

    private static final String KEY="21+20t4jm4DlkMv3nA5OSf76GrH+ifEORkO3T2yztec=";

    public static String HMACSHA256(String data, String key) throws Exception {
        if(StringUtil.isBlank(key)){
            key = KEY;
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : signData) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) throws Exception {
       long custime =System.currentTimeMillis();
       System.out.println(custime);
        String s=HMACSHA256(String.valueOf(custime),"21+20t4jm4DlkMv3nA5OSf76GrH+ifEORkO3T2yztec=");
        System.out.println(s);
      //  isEffectiveDate(1631616453099L);
        String aq = sha256_mac(String.valueOf(custime),KEY);
        System.out.println(aq);
    }
    /**
     * 判断时间是否在一分钟之内
    */
    public static boolean isEffectiveDate(long hqtime){

        Long s = (System.currentTimeMillis() - hqtime) / (1000 * 60);

        System.out.println(s);
        return s>0;
    }


    public static String sha256_mac(String message,String key){
        String outPut= null;
        try{
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(),"HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
            outPut = byteArrayToHexString(bytes);
        }catch (Exception e){
            System.out.println("Error HmacSHA256========"+e.getMessage());
        }
        return outPut;
    }
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                sb.append('0');
            sb.append(stmp);
        }
        return sb.toString().toLowerCase();
    }

}
