package com.artfess.base.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.Charset;

public class DESUtils {

    //加密、解密密匙  8个长度
    //考虑用map维护不同版本的偏移量
    private static String key = "SecretKe";

    private static final String ALGORITHM = "DES";

    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";

    /**
     * 对给定的字符串以指定的编码方式和密钥进行加密
     *
     * @param srcStr  待加密的字符串
     * @param charset 字符集，如utf8
     * @param sKey    密钥
     */
    public static String encrypt(String srcStr, Charset charset, String sKey) {
        byte[] src = srcStr.getBytes(charset);
        byte[] buf = DESUtils.encrypt(src, sKey);
        return DESUtils.parseByte2HexStr(buf);
    }

    /**
     * 对给定的密文以指定的编码方式和密钥进行解密
     *
     * @param hexStr  需要解密的密文
     * @param charset 字符集
     * @param sKey    密钥
     * @return 解密后的原文
     * @throws Exception
     */
    public static String decrypt(String hexStr, Charset charset, String sKey) throws Exception {
        byte[] src = DESUtils.parseHexStr2Byte(hexStr);
        byte[] buf = DESUtils.decrypt(src, sKey);
        return new String(buf, charset);
    }

    public static byte[] encrypt(byte[] data, String sKey) {
        try {
            byte[] key = sKey.getBytes();

            IvParameterSpec iv = new IvParameterSpec(key);
            DESKeySpec desKey = new DESKeySpec(key);

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey securekey = keyFactory.generateSecret(desKey);

            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

            cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);

            return cipher.doFinal(data);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param src
     * @param sKey
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] src, String sKey) throws Exception {
        byte[] key = sKey.getBytes();
        // 初始化向量
        IvParameterSpec iv = new IvParameterSpec(key);
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(key);
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
        // 真正开始解密操作
        return cipher.doFinal(src);
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr==null || hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    //utf8加密
    public static String myEncrypt(String data) {
        return DESUtils.encrypt(data, Charset.forName("utf8"), key);
    }

    //utf8解密
    public static String myDecrypt(String data) {
        try {
            if(StringUtil.isNotEmpty(data)) {
                return DESUtils.decrypt(data, Charset.forName("utf8"), key);
            }else{
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        String deptName = "成都振讯科技";
        String version = "1.01";
        String type = "1";//1临时 2永久
        String install = "2020-12-30";
        String endDay = "2020-12-30";
        String mac = "C03FD50F1872";
        String ip = "199.199.199.204";
        String user = "20";//用户数限制 -1不限制
        String randomStr = "QWERTYUIOPL0123456789KJHGFDSAZXCVBNM";//干扰字符串

        StringBuffer joiner = new StringBuffer(deptName);
        joiner.append(",").append(version).append(",").append(type);
        joiner.append(",").append(install).append(",").append(endDay);
        joiner.append(",").append(mac).append(",").append(ip);
        joiner.append(",").append(randomStr).append(",").append(user);

        String enc = myEncrypt(joiner.toString());
        String finalCrptStr = "02KSzdRHHnyiKa2G9lOaKk5WggskSfcxXHclB/" + enc;

        System.out.println(finalCrptStr);
        System.out.println(myDecrypt(finalCrptStr.split("/")[1]));
    }
}