package com.jiuzhekan.cbkj.common.utils;

import org.apache.commons.codec.binary.Base64;

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

/**
 * @program: cbkj_interface
 * @description: SHA1计算
 * @author: wangtao
 * @create: 2021-04-06 16:51
 **/
public class HmacSHA1 {

    /**
     * hmac+签名算法 加密
     * @param content  内容
     * @param charset  字符编码
     * @param key	         加密秘钥
     * @param hamaAlgorithm hamc签名算法名称:例如HmacMD5,HmacSHA1,HmacSHA256
     * @return
     */
    public static String getHmacSign(String content, String charset,String key,String hamaAlgorithm){
        byte[] result = null;
        try {
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), hamaAlgorithm);
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance(hamaAlgorithm);
            //用给定密钥初始化 Mac 对象
            mac.init(signinKey);
            //完成 Mac 操作
            byte[] rawHmac;
            rawHmac = mac.doFinal(content.getBytes(charset));
            result = Base64.encodeBase64(rawHmac);

        } catch (NoSuchAlgorithmException e) {
            System.err.println(e.getMessage());
        } catch (InvalidKeyException e) {
            System.err.println(e.getMessage());
        }  catch (IllegalStateException | UnsupportedEncodingException e) {
            System.err.println(e.getMessage());
        }
        if (null != result) {
            return new String(result);
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        String result = "{\n" +
                "\t\"keyArgType\":1,\"keyIndex\":\"fa30ccfe-02fb-489f-9154-b7be682fd1fd\",\"transformation\":\"ECB/PKCS7Padding\",\"input\":\"MTExMTExMTExMTExMTExMQ==\"\n" +
                "}";
        String hmacSign = getHmacSign(result, "UTF-8", "QllLUDJGV09OT1JCV1ZVVQ==", "HmacSHA1");
        System.out.println(hmacSign);

    }
}
