package com.crm.rely.backend.util;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


/**
 * @program: cwg-my-base
 * @description:
 * @author: houn
 * @create: 2019-05-07 11:08
 */
public class HAMCSHA1Util {


    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    /**
     * hamcsha1加密
     * @param data 数据
     * @param key 秘钥
     * @return
     */
    public static String hamcsha1(String data, String key) {
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            return byte2hex(mac.doFinal(data.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    //二行制转字符串
    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        String genHMAC = hamcsha1("getMethods?key=911b4f6a-a4d2-48cb-9c8f-68a77c3ec39c&timestamp=1606814088",
                "mJtkXX2x53uix563S2d8H7KqPv6wF83dPIL5");
        System.out.println(genHMAC.length());
        System.out.println(genHMAC);
    }
}
