package com.dxhy.sign.util;

import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

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

import lombok.extern.slf4j.Slf4j;

/**
 * HmacSHA1工具类
 *
 * @author jiaohongyang
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
@Slf4j
public class HmacSHA1Util {

    /**
     * HmacSHA1生成签名值
     *
     * @param data
     *            数据
     * @param key
     *            密钥
     * @return 签名值
     */
    public static String hmacsha1(String data, String key) {
        byte[] keyData = key.getBytes(Charset.forName("UTF-8"));
        try {
            SecretKey signingKey = new SecretKeySpec(keyData, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] doFinal = mac.doFinal(data.getBytes());
            return byteArrayToHexStr(doFinal);
        } catch (NoSuchAlgorithmException e) {
            log.error("NoSuchAlgorithmException", e);
        } catch (InvalidKeyException e) {
            log.error("InvalidKeyException", e);
        } catch (Exception e) {
            log.error("未知异常", e);
        }
        return null;
    }

    /**
     * 将字节数组转换成16进制字符串
     *
     * @param byteArray
     *            要转码的字节数组
     * @return 返回转码后的16进制字符串
     */
    public static String byteArrayToHexStr(byte[] byteArray) {
        StringBuilder buffer = new StringBuilder(byteArray.length * 2);
        int i;
        for (i = 0; i < byteArray.length; i++) {
            // 小于十前面补零
            if (((int)byteArray[i] & 0xff) < 0x10) {
                buffer.append("0");
            }
            buffer.append(Long.toString((int)byteArray[i] & 0xff, 16));
        }
        return buffer.toString();
    }

}
