package com.yuchen.saas.park.api.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import sun.misc.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;

/**
 * @Author: baichaojie
 * @CreateTime: 2024/10/30 16:17
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
public class HmacSha1Util {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";


    public static String genHmac(String data, String key) throws Exception {
        //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
        //生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        //用给定密钥初始化 Mac 对象
        mac.init(signinKey);
        //完成 Mac 操作
        byte[] rawHmac = mac.doFinal(data.getBytes("GBK"));
        //return new BASE64Encoder().encodeBuffer(Hex.encodeHexString(rawHmac).getBytes());
        byte[] decodedBytes = Base64.getDecoder().decode(Hex.encodeHexString(rawHmac).getBytes());
        return new String(decodedBytes);
    }

    /**
     * @description: 利用java原生的类实现SHA256加密
     * @author: chd
     * @param: [str]
     * @return: java.lang.String
     * @throws:
     */
    public static String getSHA256(String str) {
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodestr = byte2Hex(messageDigest.digest());
        } catch (Exception e) {
            log.error("sha256加密异常！", e);
        }
        return encodestr;
    }

    /**
     * @description: 将byte转为16进制
     * @author: chd
     * @param: [bytes]
     * @return: java.lang.String
     * @throws:
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}
