package com.fufan.mtsaas.util;

import lombok.extern.slf4j.Slf4j;

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

/**
 * @TODO Hmac计算文件摘要
 * @AUTHOR Liby
 * @CREATE 2018/7/23
 * @VERSION 1.0
 **/
@Slf4j
public class Hmac {

    private static final String MAC_NAME = "HmacMD5";
    private static final String ENCODING = "UTF-8";

    public static String encryptHmacMD5(String key,String data){
        Mac mac = null;
        String resultString = null;
        try {
            byte[] bytes=key.getBytes(ENCODING);
            SecretKey secretKey = new SecretKeySpec(bytes,MAC_NAME);
            mac = Mac.getInstance(MAC_NAME);
            mac.init(secretKey);
            byte[] resultBytes =  mac.doFinal(data.getBytes());
            resultString = bytesToHexString(resultBytes);
        } catch ( UnsupportedEncodingException e ) {
            log.error("加签失败：",e);
        } catch ( NoSuchAlgorithmException e ) {
            log.error("加签失败：",e);
        } catch ( InvalidKeyException e ) {
            log.error("加签失败：",e);
        }
        return resultString;
    }

    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        String key = UUID.randomUUID().toString().replace("-","");
        System.out.println(key);
        String mac = Hmac.encryptHmacMD5(key,"测试数据加签");
        System.out.println(mac);
    }

}
