package com.yc.ship.module.trade.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;


public class DESUtil {

    /**
     * 密钥算法
     */
    private static final String KEY_ALGORITHM = "DES";

//    private static final String DEFAULT_CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
    private static final String DEFAULT_CIPHER_ALGORITHM = "DES/ECB/ISO10126Padding";


    /**
     * 初始化密钥
     *
     * @return byte[] 密钥
     * @throws Exception
     */
    public static byte[] initSecretKey() throws Exception{
        //返回生成指定算法的秘密密钥的 KeyGenerator 对象
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        //初始化此密钥生成器，使其具有确定的密钥大小
        kg.init(56);
        //生成一个密钥
        SecretKey  secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }

    /**
     * 转换密钥
     *
     * @param key   二进制密钥
     * @return Key  密钥
     * @throws Exception
     */
    private static Key toKey(byte[] key) throws Exception{
        //实例化DES密钥规则
        DESKeySpec dks = new DESKeySpec(key);
        //实例化密钥工厂
        SecretKeyFactory skf = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        //生成密钥
        SecretKey  secretKey = skf.generateSecret(dks);
        return secretKey;
    }

    /**
     * 加密
     *
     * @param data  待加密数据
     * @param key   密钥
     * @return byte[]   加密数据
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data,Key key) throws Exception{
        return encrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
    }

    /**
     * 加密
     *
     * @param data  待加密数据
     * @param key   二进制密钥
     * @return byte[]   加密数据
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data,byte[] key) throws Exception{
        return encrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
    }


    /**
     * 加密
     *
     * @param data  待加密数据
     * @param key   二进制密钥
     * @param cipherAlgorithm   加密算法/工作模式/填充方式
     * @return byte[]   加密数据
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data,byte[] key,String cipherAlgorithm) throws Exception{
        //还原密钥
        Key k = toKey(key);
        return encrypt(data, k, cipherAlgorithm);
    }

    /**
     * 加密
     *
     * @param data  待加密数据
     * @param key   密钥
     * @param cipherAlgorithm   加密算法/工作模式/填充方式
     * @return byte[]   加密数据
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data,Key key,String cipherAlgorithm) throws Exception{
        //实例化
        Cipher cipher = Cipher.getInstance(cipherAlgorithm);
        //使用密钥初始化，设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, key);
        //执行操作
        return cipher.doFinal(data);
    }



    /**
     * 解密
     *
     * @param data  待解密数据
     * @param key   二进制密钥
     * @return byte[]   解密数据
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data,byte[] key) throws Exception{
        return decrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
    }

    /**
     * 解密
     *
     * @param data  待解密数据
     * @param key   密钥
     * @return byte[]   解密数据
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data,Key key) throws Exception{
        return decrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
    }

    /**
     * 解密
     *
     * @param data  待解密数据
     * @param key   二进制密钥
     * @param cipherAlgorithm   加密算法/工作模式/填充方式
     * @return byte[]   解密数据
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data,byte[] key,String cipherAlgorithm) throws Exception{
        //还原密钥
        Key k = toKey(key);
        return decrypt(data, k, cipherAlgorithm);
    }

    /**
     * 解密
     *
     * @param data  待解密数据
     * @param key   密钥
     * @param cipherAlgorithm   加密算法/工作模式/填充方式
     * @return byte[]   解密数据
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data,Key key,String cipherAlgorithm) throws Exception{
        //实例化
        Cipher cipher = Cipher.getInstance(cipherAlgorithm);
        //使用密钥初始化，设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, key);
        //执行操作
        return cipher.doFinal(data);
    }

    private static String  showByteArray(byte[] data){
        if(null == data){
            return null;
        }
        StringBuilder sb = new StringBuilder("{");
        for(byte b:data){
            sb.append(b).append(",");
        }
        sb.deleteCharAt(sb.length()-1);
        sb.append("}");
        return sb.toString();
    }
    public static byte[] encrypt(byte[] data, String password) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes(StandardCharsets.UTF_8));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            return cipher.doFinal(padData(data));
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] decrypt(byte[] src, String key) throws Exception {
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        SecretKey securekey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        return cipher.doFinal(src);
    }

    public static byte[] padData(byte[] data) {
        int blockSize = 8;
        int paddedLength = (data.length + blockSize - 1) / blockSize * blockSize;
        byte[] paddedData = new byte[paddedLength];
        System.arraycopy(data, 0, paddedData, 0, data.length);
        return paddedData;
    }






    public static void main(String[] args) throws Exception {
//        byte[] key = initSecretKey();
//        String msg = "";
//        byte[] key = "t0tbbxbw1r8ym0p816h8".getBytes();
//        // System.out.println("key："+ showByteArray(key));
//        String param = "杨涛:51032219911203499X:";
//        byte[] encryptData = DESCoderUtil.encrypt(param.getBytes("utf-8"), key);
//        String userInfo = Hex.encodeHexStr(encryptData);
//        Map<String, String> header = new HashMap<String, String>();
//        header.put("AppKey", "4789927066");
//        String result = SendHttps.sendGet("https://www.daqctc.com/api/user/api/smart/travel/health/getHealthInfo","userInfo="+userInfo, header);
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        String message = jsonObject.getString("message");
//        if(com.alibaba.druid.util.StringUtils.equals(message,"success")){
//            String data = jsonObject.getString("data");
//            com.alibaba.fastjson.JSONObject jsonObjectData = com.alibaba.fastjson.JSONObject.parseObject(data);
//            String healthCode = jsonObjectData.getString("healthCode");
//            String healthMSG = jsonObjectData.getString("healthMSG");
//            if(!com.alibaba.druid.util.StringUtils.equals(healthCode, "01")){
//                msg = healthMSG;
//            }
//        }else{
//            msg = message;
//        }
//        System.out.println("返回结果: string:"+msg);
//        System.out.println("加密前数据: string:"+data);
//        System.out.println("加密前数据: byte[]:"+showByteArray(data.getBytes()));
//        System.out.println();
//        byte[] encryptData = encrypt(data.getBytes(), key);
//        System.out.println("加密后数据: byte[]:"+showByteArray(encryptData));
//        System.out.println("加密后数据: hexStr:"+Hex.encodeHexStr(encryptData));
//        System.out.println();
//        byte[] decryptData = decrypt(encryptData, key);
//        System.out.println("解密后数据: byte[]:"+showByteArray(decryptData));
//        System.out.println("解密后数据: string:"+new String(decryptData));
        String secretkey ="8717EE05";
        String data ="EA7F0D3F554698BE2A7E208638B5483958B6676B2DEF49B55483FF860C785542DF8AF79FB972751E7073D7BCC8908E64EBE95AC8F86DCE4A96324879660BB8DE45A464D5C0E3BFB5B6F5D4E0A0ABC0BBDFAB6398A618032FA9AA6F7CB4937FE1";

        byte[] encryptedResponse = HexUtil.parseHexStr2Byte(data);
        byte[] decryptedData = DESUtil.decrypt(encryptedResponse, secretkey);
        String  result = new String(decryptedData).trim();
        System.out.println(result);
    }
}
