package com.friday.custody.api.util;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class GJDFHmac
{
    private static final String KEY_MAC = "HmacSHA1";
    private static final String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public static String encryptBase64(byte[] key)
            throws Exception
    {
        return new String(Base64.getEncoder().encode(key), "UTF-8");
    }

    public static byte[] decryptBase64(String key)
            throws Exception
    {
        return Base64.getDecoder().decode(key);
    }

    public static String init()
    {
        String str = "";
        try {
            KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
            SecretKey key = generator.generateKey();
            str = encryptBase64(key.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static byte[] encryptHMAC(byte[] data, String key)
    {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(secretKey);
            bytes = mac.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static String encryptHMAC(String data, String key)
    {
        if ((data == null) || (data.trim().equals(""))) {
            return null;
        }
        try
        {
            byte[] bytes = encryptHMAC(data.getBytes("UTF-8"), key);
            return new String(Base64.getEncoder().encode(bytes), "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String byteToHexString(byte b)
    {
        int ret = b;
        if (ret < 0) {
            ret += 256;
        }
        int m = ret / 16;
        int n = ret % 16;
        return hexDigits[m] + hexDigits[n];
    }

    private static String byteArrayToHexString(byte[] bytes)
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(byteToHexString(bytes[i]));
        }
        return sb.toString();
    }
}